@sun-asterisk/sunlint 1.3.30 → 1.3.32

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.
@@ -1,12 +1,10 @@
1
1
  /**
2
2
  * S031 Main Analyzer - Set Secure flag for Session Cookies
3
- * Primary: Symbol-based analysis (when available)
4
- * Fallback: Regex-based for all other cases
3
+ * Uses symbol-based analysis only (regex-based removed)
5
4
  * Command: node cli.js --rule=S031 --input=examples/rule-test-fixtures/rules/S031_secure_session_cookies --engine=heuristic
6
5
  */
7
6
 
8
7
  const S031SymbolBasedAnalyzer = require("./symbol-based-analyzer.js");
9
- const S031RegexBasedAnalyzer = require("./regex-based-analyzer.js");
10
8
 
11
9
  class S031Analyzer {
12
10
  constructor(options = {}) {
@@ -26,14 +24,7 @@ class S031Analyzer {
26
24
  this.semanticEngine = options.semanticEngine || null;
27
25
  this.verbose = options.verbose || false;
28
26
 
29
- // Configuration
30
- this.config = {
31
- useSymbolBased: true, // Primary approach
32
- fallbackToRegex: true, // Secondary approach
33
- regexBasedOnly: false, // Can be set to true for pure mode
34
- };
35
-
36
- // Initialize analyzers
27
+ // Initialize symbol analyzer only
37
28
  try {
38
29
  this.symbolAnalyzer = new S031SymbolBasedAnalyzer(this.semanticEngine);
39
30
  if (process.env.SUNLINT_DEBUG) {
@@ -43,48 +34,39 @@ class S031Analyzer {
43
34
  console.error(`🔧 [S031] Error creating symbol analyzer:`, error);
44
35
  }
45
36
 
46
- try {
47
- this.regexAnalyzer = new S031RegexBasedAnalyzer(this.semanticEngine);
48
- if (process.env.SUNLINT_DEBUG) {
49
- console.log(`🔧 [S031] Regex analyzer created successfully`);
50
- }
51
- } catch (error) {
52
- console.error(`🔧 [S031] Error creating regex analyzer:`, error);
37
+ if (process.env.SUNLINT_DEBUG) {
38
+ console.log(`🔧 [S031] Constructor completed`);
53
39
  }
54
40
  }
55
41
 
56
42
  /**
57
43
  * Initialize analyzer with semantic engine
58
-
59
44
  */
60
- async initialize(semanticEngine) {
61
- this.semanticEngine = semanticEngine;
62
-
63
- if (process.env.SUNLINT_DEBUG) {
64
- console.log(`🔧 [S031] Main analyzer initializing...`);
45
+ async initialize(semanticEngine = null) {
46
+ if (semanticEngine) {
47
+ this.semanticEngine = semanticEngine;
65
48
  }
49
+ this.verbose = semanticEngine?.verbose || false;
66
50
 
67
- // Initialize both analyzers
51
+ // Initialize symbol analyzer
68
52
  if (this.symbolAnalyzer) {
69
53
  await this.symbolAnalyzer.initialize?.(semanticEngine);
70
54
  }
71
- if (this.regexAnalyzer) {
72
- await this.regexAnalyzer.initialize?.(semanticEngine);
73
- }
74
55
 
75
- // Clean up if needed
76
- if (this.regexAnalyzer) {
77
- this.regexAnalyzer.cleanup?.();
56
+ // Ensure verbose flag is propagated
57
+ if (this.symbolAnalyzer) {
58
+ this.symbolAnalyzer.verbose = this.verbose;
78
59
  }
79
60
 
80
- if (process.env.SUNLINT_DEBUG) {
81
- console.log(`🔧 [S031] Main analyzer initialized successfully`);
61
+ if (this.verbose) {
62
+ console.log(
63
+ `🔧 [S031] Analyzer initialized - verbose: ${this.verbose}`
64
+ );
82
65
  }
83
66
  }
84
67
 
85
68
  /**
86
69
  * Single file analysis method for testing
87
-
88
70
  */
89
71
  analyzeSingle(filePath, options = {}) {
90
72
  if (process.env.SUNLINT_DEBUG) {
@@ -141,122 +123,95 @@ class S031Analyzer {
141
123
  // Create a Map to track unique violations and prevent duplicates
142
124
  const violationMap = new Map();
143
125
 
144
- // 1. Try Symbol-based analysis first (primary)
145
- if (
146
- this.config.useSymbolBased &&
147
- this.semanticEngine?.project &&
148
- this.semanticEngine?.initialized
149
- ) {
126
+ // Symbol-based analysis only
127
+ if (this.semanticEngine?.project && this.semanticEngine?.initialized) {
150
128
  try {
151
129
  if (process.env.SUNLINT_DEBUG) {
152
- console.log(`🔧 [S031] Trying symbol-based analysis...`);
130
+ console.log(`🔧 [S031] Running symbol-based analysis...`);
153
131
  }
154
132
  const sourceFile = this.semanticEngine.project.getSourceFile(filePath);
155
133
  if (sourceFile) {
156
134
  if (process.env.SUNLINT_DEBUG) {
157
- console.log(`🔧 [S031] Source file found, analyzing...`);
135
+ console.log(
136
+ `🔧 [S031] Source file found, analyzing with symbol-based...`
137
+ );
158
138
  }
159
- const symbolViolations = await this.symbolAnalyzer.analyze(
139
+
140
+ const violations = await this.symbolAnalyzer.analyze(
160
141
  sourceFile,
161
142
  filePath
162
143
  );
163
144
 
164
- // Add to violation map with deduplication
165
- symbolViolations.forEach((violation) => {
166
- // Create a cookie-specific key to allow multiple violations for same cookie at different locations
167
- const cookieName = this.extractCookieName(violation.message) || "";
168
- const key = `cookie:${cookieName}:line:${violation.line}:secure`;
145
+ // Add violations to map to deduplicate and add filePath
146
+ violations.forEach((v) => {
147
+ const key = `${v.line}:${v.column}:${v.message}`;
169
148
  if (!violationMap.has(key)) {
170
- violationMap.set(key, violation);
149
+ v.analysisStrategy = "symbol-based";
150
+ v.filePath = filePath;
151
+ v.file = filePath; // Also add 'file' for compatibility
152
+ violationMap.set(key, v);
171
153
  }
172
154
  });
173
155
 
174
156
  if (process.env.SUNLINT_DEBUG) {
175
157
  console.log(
176
- `🔧 [S031] Symbol analysis completed: ${symbolViolations.length} violations`
158
+ `✅ [S031] Symbol-based analysis: ${violations.length} violations`
177
159
  );
178
160
  }
161
+
162
+ const finalViolations = Array.from(violationMap.values());
163
+ return finalViolations; // Return deduplicated violations with filePath
179
164
  } else {
180
165
  if (process.env.SUNLINT_DEBUG) {
181
- console.log(`🔧 [S031] Source file not found, falling back...`);
166
+ console.log(`⚠️ [S031] Source file not found in project`);
182
167
  }
183
168
  }
184
169
  } catch (error) {
185
- console.warn(`⚠ [S031] Symbol analysis failed:`, error.message);
170
+ console.warn(`⚠️ [S031] Symbol analysis failed: ${error.message}`);
186
171
  }
187
- }
188
-
189
- // 2. Try Regex-based analysis (fallback or additional)
190
- if (this.config.fallbackToRegex || this.config.regexBasedOnly) {
191
- try {
192
- if (process.env.SUNLINT_DEBUG) {
193
- console.log(`🔧 [S031] Trying regex-based analysis...`);
194
- }
195
- const regexViolations = await this.regexAnalyzer.analyze(filePath);
196
-
197
- // Add to violation map with deduplication
198
- regexViolations.forEach((violation) => {
199
- // Create a cookie-specific key to allow multiple violations for same cookie at different locations
200
- const cookieName = this.extractCookieName(violation.message) || "";
201
- const key = `cookie:${cookieName}:line:${violation.line}:secure`;
202
- if (!violationMap.has(key)) {
203
- violationMap.set(key, violation);
204
- }
205
- });
206
-
207
- if (process.env.SUNLINT_DEBUG) {
208
- console.log(
209
- `🔧 [S031] Regex analysis completed: ${regexViolations.length} violations`
210
- );
211
- }
212
- } catch (error) {
213
- console.warn(`⚠ [S031] Regex analysis failed:`, error.message);
172
+ } else {
173
+ if (process.env.SUNLINT_DEBUG) {
174
+ console.log(`🔄 [S031] Symbol analysis conditions check:`);
175
+ console.log(` - semanticEngine: ${!!this.semanticEngine}`);
176
+ console.log(
177
+ ` - semanticEngine.project: ${!!this.semanticEngine?.project}`
178
+ );
179
+ console.log(
180
+ ` - semanticEngine.initialized: ${this.semanticEngine?.initialized}`
181
+ );
182
+ console.log(`🔄 [S031] Symbol analysis unavailable`);
214
183
  }
215
184
  }
216
185
 
217
- // Convert Map values to array and add filePath to each violation
218
- const finalViolations = Array.from(violationMap.values()).map(
219
- (violation) => ({
220
- ...violation,
221
- filePath: filePath,
222
- file: filePath, // Also add 'file' for compatibility
223
- })
224
- );
225
-
226
186
  if (process.env.SUNLINT_DEBUG) {
227
- console.log(
228
- `🔧 [S031] File analysis completed: ${finalViolations.length} unique violations`
229
- );
187
+ console.log(`🔧 [S031] Analysis completed: ${violationMap.size} violations`);
230
188
  }
231
-
232
- return finalViolations;
189
+ return Array.from(violationMap.values());
233
190
  }
234
191
 
235
192
  /**
236
- * Extract cookie name from violation message for better deduplication
193
+ * Methods for compatibility with different engine invocation patterns
237
194
  */
238
- extractCookieName(message) {
239
- try {
240
- const match = message.match(
241
- /Session cookie "([^"]+)"|Session cookie from "([^"]+)"/
242
- );
243
- return match ? match[1] || match[2] : "";
244
- } catch (error) {
245
- return "";
246
- }
195
+ async analyzeFileWithSymbols(filePath, options = {}) {
196
+ return this.analyzeFile(filePath, options);
247
197
  }
248
198
 
249
- /**
250
- * Clean up resources
199
+ async analyzeWithSemantics(filePath, options = {}) {
200
+ return this.analyzeFile(filePath, options);
201
+ }
251
202
 
203
+ /**
204
+ * Get analyzer metadata
252
205
  */
253
- cleanup() {
254
- if (this.symbolAnalyzer?.cleanup) {
255
- this.symbolAnalyzer.cleanup();
256
- }
257
- if (this.regexAnalyzer?.cleanup) {
258
- this.regexAnalyzer.cleanup();
259
- }
206
+ getMetadata() {
207
+ return {
208
+ rule: "S031",
209
+ name: "Set Secure flag for Session Cookies",
210
+ category: "security",
211
+ type: "symbol-based",
212
+ description:
213
+ "Uses symbol-based analysis to detect session cookies missing Secure flag",
214
+ };
260
215
  }
261
216
  }
262
217
 
@@ -1,296 +0,0 @@
1
- /**
2
- * S031 Regex-Based Analyzer - Set Secure flag for Session Cookies
3
- * Fallback analysis using regex patterns
4
-
5
- */
6
-
7
- const fs = require("fs");
8
-
9
- class S031RegexBasedAnalyzer {
10
- constructor(semanticEngine = null) {
11
- this.semanticEngine = semanticEngine;
12
- this.ruleId = "S031";
13
- this.category = "security";
14
-
15
- // Session cookie indicators
16
- this.sessionIndicators = [
17
- "session",
18
- "sessionid",
19
- "sessid",
20
- "jsessionid",
21
- "phpsessid",
22
- "asp.net_sessionid",
23
- "connect.sid",
24
- "auth",
25
- "token",
26
- "jwt",
27
- "csrf",
28
- ];
29
-
30
- // Regex patterns for cookie detection
31
- this.cookiePatterns = [
32
- // Express/Node.js patterns
33
- /res\.cookie\s*\(\s*['"`]([^'"`]+)['"`]\s*,([^)]+)\)/gi,
34
- /response\.cookie\s*\(\s*['"`]([^'"`]+)['"`]\s*,([^)]+)\)/gi,
35
- /\.setCookie\s*\(\s*['"`]([^'"`]+)['"`]\s*,([^)]+)\)/gi,
36
-
37
- // Set-Cookie header patterns
38
- /setHeader\s*\(\s*['"`]Set-Cookie['"`]\s*,\s*['"`]([^'"`]+)['"`]\s*\)/gi,
39
- /writeHead\s*\([^,]*,\s*{[^}]*['"`]Set-Cookie['"`]\s*:\s*['"`]([^'"`]+)['"`]/gi,
40
-
41
- // Document.cookie assignments
42
- /document\.cookie\s*=\s*['"`]([^'"`]+)['"`]/gi,
43
-
44
- // Session middleware patterns
45
- /session\s*\(\s*{([^}]+)}/gi,
46
- /\.use\s*\(\s*session\s*\(\s*{([^}]+)}/gi,
47
- ];
48
- }
49
-
50
- /**
51
- * Initialize analyzer
52
-
53
- */
54
- async initialize(semanticEngine) {
55
- this.semanticEngine = semanticEngine;
56
- if (process.env.SUNLINT_DEBUG) {
57
- console.log(`🔧 [S031] Regex-based analyzer initialized`);
58
- }
59
- }
60
-
61
- /**
62
- * Check if file should be skipped (test files)
63
- */
64
- shouldSkipFile(filePath) {
65
- const testPatterns = [
66
- /\.test\.(ts|tsx|js|jsx)$/,
67
- /\.spec\.(ts|tsx|js|jsx)$/,
68
- /__tests__\//,
69
- /__mocks__\//,
70
- /\/tests?\//,
71
- /\/fixtures?\//,
72
- ];
73
- return testPatterns.some((pattern) => pattern.test(filePath));
74
- }
75
-
76
- /**
77
- * Analyze file content using regex patterns
78
-
79
- */
80
- async analyze(filePath) {
81
- if (process.env.SUNLINT_DEBUG) {
82
- console.log(`🔍 [S031] Regex-based analysis for: ${filePath}`);
83
- }
84
-
85
- // Skip test files
86
- if (this.shouldSkipFile(filePath)) {
87
- if (process.env.SUNLINT_DEBUG) {
88
- console.log(`⏭ [S031] Skipping test file: ${filePath}`);
89
- }
90
- return [];
91
- }
92
-
93
- let content;
94
- try {
95
- content = fs.readFileSync(filePath, "utf8");
96
- } catch (error) {
97
- if (process.env.SUNLINT_DEBUG) {
98
- console.error(`❌ [S031] File read error:`, error);
99
- }
100
- throw error;
101
- }
102
-
103
- const violations = [];
104
- const lines = content.split("\n");
105
-
106
- // Check each pattern
107
- for (const pattern of this.cookiePatterns) {
108
- this.checkPattern(pattern, content, lines, violations, filePath);
109
- }
110
-
111
- // Check for custom cookie utilities (e.g., StorageUtils.setCookie)
112
- this.checkCustomCookieUtilities(content, lines, violations, filePath);
113
-
114
- return violations;
115
- }
116
-
117
- /**
118
- * Check specific regex pattern for violations
119
-
120
- */
121
- checkPattern(pattern, content, lines, violations, filePath) {
122
- let match;
123
- pattern.lastIndex = 0; // Reset regex state
124
-
125
- while ((match = pattern.exec(content)) !== null) {
126
- const matchText = match[0];
127
- const cookieName = match[1] || "";
128
- const cookieOptions = match[2] || match[1] || "";
129
-
130
- // Check if this is a session cookie
131
- if (!this.isSessionCookie(cookieName, matchText)) {
132
- continue;
133
- }
134
-
135
- // Check if secure flag is present
136
- if (!this.hasSecureFlag(cookieOptions, matchText)) {
137
- const lineNumber = this.getLineNumber(content, match.index);
138
-
139
- this.addViolation(
140
- matchText,
141
- lineNumber,
142
- violations,
143
- `Session cookie "${cookieName || "unknown"}" missing Secure flag`
144
- );
145
- }
146
- }
147
- }
148
-
149
- /**
150
- * Check if cookie name or context indicates session cookie
151
-
152
- */
153
- isSessionCookie(cookieName, matchText) {
154
- const textToCheck = (cookieName + " " + matchText).toLowerCase();
155
- return this.sessionIndicators.some((indicator) =>
156
- textToCheck.includes(indicator.toLowerCase())
157
- );
158
- }
159
-
160
- /**
161
- * Check if secure flag is present in cookie options
162
- */
163
- hasSecureFlag(cookieOptions, fullMatch) {
164
- const textToCheck = cookieOptions + " " + fullMatch;
165
-
166
- // Check for secure config references (likely safe)
167
- const secureConfigPatterns = [
168
- /\bcookieConfig\b/i,
169
- /\bsecureConfig\b/i,
170
- /\bsafeConfig\b/i,
171
- /\bdefaultConfig\b/i,
172
- /\.\.\..*config/i, // spread operator with config
173
- /config.*secure/i,
174
- ];
175
-
176
- // If using a secure config reference, assume it's safe
177
- if (secureConfigPatterns.some((pattern) => pattern.test(textToCheck))) {
178
- return true;
179
- }
180
-
181
- // Check for various secure flag patterns
182
- const securePatterns = [
183
- /secure\s*:\s*true/i,
184
- /secure\s*=\s*true/i,
185
- /;\s*secure\s*[;\s]/i,
186
- /;\s*secure$/i,
187
- /['"`]\s*secure\s*['"`]/i,
188
- /"secure"\s*:\s*true/i,
189
- /'secure'\s*:\s*true/i,
190
- /\bsecure\b/i, // Simple secure keyword
191
- ];
192
-
193
- return securePatterns.some((pattern) => pattern.test(textToCheck));
194
- }
195
-
196
- /**
197
- * Get line number from content position
198
-
199
- */
200
- getLineNumber(content, position) {
201
- const beforeMatch = content.substring(0, position);
202
- return beforeMatch.split("\n").length;
203
- }
204
-
205
- /**
206
- * Add violation to results
207
-
208
- */
209
- addViolation(source, lineNumber, violations, message) {
210
- violations.push({
211
- ruleId: this.ruleId,
212
- source: source.trim(),
213
- category: this.category,
214
- line: lineNumber,
215
- column: 1,
216
- message: `Insecure session cookie: ${message}`,
217
- severity: "error",
218
- });
219
- }
220
-
221
- /**
222
- * Check for custom cookie utility functions with variable names
223
- * Handles cases like: StorageUtils.setCookie(STORAGE_KEY.ACCESS_TOKEN, value)
224
- */
225
- checkCustomCookieUtilities(content, lines, violations, filePath) {
226
- // Pattern to match custom cookie utilities with variable references
227
- // Matches: Utils.setCookie(VARIABLE_NAME, value) or Utils.setCookie(VARIABLE_NAME, value, options)
228
- const customCookiePattern = /(\w+\.setCookie)\s*\(\s*([A-Z_][A-Z0-9_.]*)\s*,\s*([^,)]+)(?:\s*,\s*([^)]*))?\s*\)/gi;
229
-
230
- let match;
231
- customCookiePattern.lastIndex = 0;
232
-
233
- while ((match = customCookiePattern.exec(content)) !== null) {
234
- const methodCall = match[1]; // e.g., "StorageUtils.setCookie"
235
- const cookieNameVar = match[2]; // e.g., "STORAGE_KEY.ACCESS_TOKEN"
236
- const cookieValue = match[3]; // e.g., "response.user?.access_token || ''"
237
- const cookieOptions = match[4] || ""; // e.g., options object if present
238
- const matchText = match[0];
239
-
240
- // Check if this looks like a session cookie based on variable name or value
241
- if (!this.isSessionCookieLikely(cookieNameVar, cookieValue, matchText)) {
242
- continue;
243
- }
244
-
245
- // Check if secure flag is present in options
246
- if (!this.hasSecureFlag(cookieOptions, matchText)) {
247
- const lineNumber = this.getLineNumber(content, match.index);
248
-
249
- // Extract a friendly cookie name from the variable
250
- const friendlyCookieName = this.extractFriendlyCookieName(cookieNameVar);
251
-
252
- this.addViolation(
253
- matchText,
254
- lineNumber,
255
- violations,
256
- `Session cookie from "${friendlyCookieName}" missing Secure flag - add secure flag to options`
257
- );
258
- }
259
- }
260
- }
261
-
262
- /**
263
- * Check if cookie variable name or value suggests it's a session cookie
264
- */
265
- isSessionCookieLikely(varName, value, matchText) {
266
- const textToCheck = (varName + " " + value + " " + matchText).toLowerCase();
267
-
268
- // Check against session indicators
269
- const isSession = this.sessionIndicators.some((indicator) =>
270
- textToCheck.includes(indicator.toLowerCase())
271
- );
272
-
273
- // Also check for common patterns like ACCESS_TOKEN, REFRESH_TOKEN, etc.
274
- const tokenPatterns = [
275
- /access[_-]?token/i,
276
- /refresh[_-]?token/i,
277
- /auth[_-]?token/i,
278
- /id[_-]?token/i,
279
- /session/i,
280
- ];
281
-
282
- return isSession || tokenPatterns.some(pattern => pattern.test(textToCheck));
283
- }
284
-
285
- /**
286
- * Extract a friendly cookie name from variable reference
287
- * e.g., "STORAGE_KEY.ACCESS_TOKEN" -> "ACCESS_TOKEN"
288
- */
289
- extractFriendlyCookieName(varName) {
290
- // If it has a dot, take the last part
291
- const parts = varName.split(".");
292
- return parts[parts.length - 1] || varName;
293
- }
294
- }
295
-
296
- module.exports = S031RegexBasedAnalyzer;