eslint-plugin-express-security 1.2.3 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,402 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Ofri Peretz
4
+ * Licensed under the MIT License. Use of this source code is governed by the
5
+ * MIT license that can be found in the LICENSE file.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.noMissingCorsCheck = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ const eslint_devkit_2 = require("@interlace/eslint-devkit");
11
+ /**
12
+ * Check if a string matches any ignore pattern
13
+ */
14
+ function matchesIgnorePattern(text, ignorePatterns) {
15
+ return ignorePatterns.some(pattern => {
16
+ try {
17
+ const regex = new RegExp(pattern, 'i');
18
+ return regex.test(text);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ });
24
+ }
25
+ exports.noMissingCorsCheck = (0, eslint_devkit_2.createRule)({
26
+ name: 'no-missing-cors-check',
27
+ meta: {
28
+ type: 'problem',
29
+ deprecated: true,
30
+ replacedBy: ['@see eslint-plugin-express-security/no-permissive-cors'],
31
+ docs: {
32
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-cors-check.md',
33
+ description: 'Detects missing CORS validation (wildcard CORS, missing origin check)',
34
+ cwe: 'CWE-346',
35
+ cvss: 7.5,
36
+ },
37
+ hasSuggestions: true,
38
+ messages: {
39
+ missingCorsCheck: (0, eslint_devkit_1.formatLLMMessage)({
40
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
41
+ issueName: 'Missing CORS Validation',
42
+ cwe: 'CWE-346',
43
+ description: 'Missing CORS validation detected: {{issue}}',
44
+ severity: 'HIGH',
45
+ fix: '{{safeAlternative}}',
46
+ documentationLink: 'https://cwe.mitre.org/data/definitions/346.html',
47
+ }),
48
+ useOriginValidation: (0, eslint_devkit_1.formatLLMMessage)({
49
+ icon: eslint_devkit_1.MessageIcons.INFO,
50
+ issueName: 'Validate Origin',
51
+ description: 'Validate CORS origin',
52
+ severity: 'LOW',
53
+ fix: 'cors({ origin: (origin, cb) => allowedOrigins.includes(origin) ? cb(null, true) : cb(new Error()) })',
54
+ documentationLink: 'https://github.com/expressjs/cors#configuration-options',
55
+ }),
56
+ useCorsMiddleware: (0, eslint_devkit_1.formatLLMMessage)({
57
+ icon: eslint_devkit_1.MessageIcons.INFO,
58
+ issueName: 'Use CORS Middleware',
59
+ description: 'Use CORS middleware with origin validation',
60
+ severity: 'LOW',
61
+ fix: 'app.use(cors({ origin: allowedOrigins }))',
62
+ documentationLink: 'https://github.com/expressjs/cors',
63
+ }),
64
+ },
65
+ schema: [
66
+ {
67
+ type: 'object',
68
+ properties: {
69
+ allowInTests: {
70
+ type: 'boolean',
71
+ default: false,
72
+ description: 'Allow missing CORS checks in test files',
73
+ },
74
+ trustedLibraries: {
75
+ type: 'array',
76
+ items: { type: 'string' },
77
+ default: [],
78
+ description: 'Custom CORS libraries to trust (wildcard origins in these libraries will not be reported)',
79
+ },
80
+ ignorePatterns: {
81
+ type: 'array',
82
+ items: { type: 'string' },
83
+ default: [],
84
+ description: 'Additional safe patterns to ignore',
85
+ },
86
+ },
87
+ additionalProperties: false,
88
+ },
89
+ ],
90
+ },
91
+ defaultOptions: [
92
+ {
93
+ allowInTests: false,
94
+ trustedLibraries: [], // Empty by default - users can add custom CORS libraries they trust
95
+ ignorePatterns: [],
96
+ },
97
+ ],
98
+ create(context, [options = {}]) {
99
+ const { allowInTests = false, trustedLibraries: corsTrustedLibraries = [], ignorePatterns = [], } = options;
100
+ const trustedLibraries = corsTrustedLibraries;
101
+ const filename = context.filename;
102
+ const isTestFile = allowInTests && /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);
103
+ const sourceCode = context.sourceCode;
104
+ function checkLiteral(node) {
105
+ if (isTestFile) {
106
+ return;
107
+ }
108
+ // Check for wildcard CORS origin
109
+ if (node.value === '*' && typeof node.value === 'string') {
110
+ const text = sourceCode.getText(node);
111
+ // Check if it matches any ignore pattern
112
+ if (matchesIgnorePattern(text, ignorePatterns)) {
113
+ return;
114
+ }
115
+ // Check if it's in contexts handled by other checkers
116
+ // 1. setHeader/header calls - checkMemberExpression handles these
117
+ // 2. app.use(cors({ origin: "*" })) - checkCallExpression handles these with suggestions
118
+ let shouldSkip = false;
119
+ let current = node;
120
+ while (current && current.parent) {
121
+ current = current.parent;
122
+ if (current.type === 'CallExpression') {
123
+ const callText = sourceCode.getText(current);
124
+ // Check if it's a setHeader/header call with Access-Control-Allow-Origin
125
+ // Skip these - checkMemberExpression handles them
126
+ if (/\b(setHeader|header)\s*\(/i.test(callText) && /\bAccess-Control-Allow-Origin\b/i.test(callText)) {
127
+ shouldSkip = true;
128
+ break;
129
+ }
130
+ // Check if it's app.use(cors({ origin: "*" })) - checkCallExpression handles these with suggestions
131
+ if (/\buse\s*\(/i.test(callText) && /\bcors\s*\(/i.test(callText)) {
132
+ // Check if the literal is in an object property named "origin"
133
+ if (node.parent && node.parent.type === 'Property') {
134
+ const prop = node.parent;
135
+ if (prop.key.type === 'Identifier' && prop.key.name === 'origin') {
136
+ shouldSkip = true;
137
+ break;
138
+ }
139
+ }
140
+ }
141
+ }
142
+ }
143
+ // Skip if it's in a context handled by another checker
144
+ if (shouldSkip) {
145
+ return;
146
+ }
147
+ // Check if it's in a CORS-related context
148
+ // Only report if it's actually in a CORS configuration (app.use(cors(...)), etc.)
149
+ // Not just any object with origin: "*"
150
+ let isActualCorsContext = false;
151
+ // Check if it's in app.use(cors(...)) or similar
152
+ current = node;
153
+ while (current && current.parent) {
154
+ current = current.parent;
155
+ if (current.type === 'CallExpression') {
156
+ const callText = sourceCode.getText(current);
157
+ // Check if it's a CORS middleware call
158
+ if (/\b(use|cors)\s*\(/i.test(callText) && /\bcors\s*\(/i.test(callText)) {
159
+ isActualCorsContext = true;
160
+ break;
161
+ }
162
+ }
163
+ }
164
+ // Also check if it's in an object property with name "origin" or "allowedOrigins"
165
+ // but only if it's in a CORS-related call expression
166
+ if (node.parent && node.parent.type === 'Property') {
167
+ const prop = node.parent;
168
+ if (prop.key.type === 'Identifier') {
169
+ const keyName = prop.key.name.toLowerCase();
170
+ if (keyName === 'origin' || keyName === 'allowedorigins') {
171
+ // Check if this property is in a CORS call context
172
+ let inCorsCall = false;
173
+ let checkNode = prop;
174
+ while (checkNode && checkNode.parent) {
175
+ checkNode = checkNode.parent;
176
+ if (checkNode.type === 'CallExpression') {
177
+ const callText = sourceCode.getText(checkNode);
178
+ if (/\bcors\s*\(/i.test(callText) ||
179
+ (/\buse\s*\(/i.test(callText) && /\bcors/i.test(callText))) {
180
+ inCorsCall = true;
181
+ break;
182
+ }
183
+ }
184
+ }
185
+ if (inCorsCall) {
186
+ // Always report wildcard CORS origin - it's never safe
187
+ context.report({
188
+ node,
189
+ messageId: 'missingCorsCheck',
190
+ data: {
191
+ issue: 'Wildcard CORS origin (*) allows all origins',
192
+ safeAlternative: 'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));',
193
+ },
194
+ suggest: [
195
+ {
196
+ messageId: 'useOriginValidation',
197
+ fix: (_fixer) => null,
198
+ },
199
+ ],
200
+ });
201
+ return;
202
+ }
203
+ }
204
+ }
205
+ }
206
+ // Only report if it's in an actual CORS context
207
+ if (isActualCorsContext) {
208
+ // Always report wildcard CORS origin - it's never safe
209
+ context.report({
210
+ node,
211
+ messageId: 'missingCorsCheck',
212
+ data: {
213
+ issue: 'Wildcard CORS origin (*) allows all origins',
214
+ safeAlternative: 'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));',
215
+ },
216
+ suggest: [
217
+ {
218
+ messageId: 'useOriginValidation',
219
+ fix: (_fixer) => null,
220
+ },
221
+ ],
222
+ });
223
+ }
224
+ }
225
+ }
226
+ function checkCallExpression(node) {
227
+ if (isTestFile) {
228
+ return;
229
+ }
230
+ // Check for app.use(cors({ origin: "*" })) or similar
231
+ if (node.callee.type === 'MemberExpression') {
232
+ const property = node.callee.property;
233
+ if (property.type === 'Identifier' && property.name === 'use') {
234
+ // Check if CORS is being used
235
+ const text = sourceCode.getText(node);
236
+ // Check if it matches any ignore pattern
237
+ if (matchesIgnorePattern(text, ignorePatterns)) {
238
+ return;
239
+ }
240
+ // Check if it's a CORS middleware call
241
+ // Check for cors() or trusted library calls
242
+ const firstArg = node.arguments.length > 0 ? node.arguments[0] : null;
243
+ let isCorsCall = /\bcors\s*\(/i.test(text);
244
+ if (!isCorsCall && firstArg && firstArg.type === 'CallExpression' && firstArg.callee.type === 'Identifier') {
245
+ const callee = firstArg.callee;
246
+ const calleeName = callee.name.toLowerCase();
247
+ // Check if it's the standard 'cors' library or a trusted library
248
+ isCorsCall = calleeName === 'cors' || trustedLibraries.some(lib => {
249
+ return calleeName.includes(lib.toLowerCase());
250
+ });
251
+ }
252
+ // Check if it's a trusted library - skip if explicitly trusted
253
+ let isTrustedLibrary = false;
254
+ if (firstArg && firstArg.type === 'CallExpression' && firstArg.callee.type === 'Identifier') {
255
+ const calleeName = firstArg.callee.name.toLowerCase();
256
+ isTrustedLibrary = trustedLibraries.some(lib => calleeName.includes(lib.toLowerCase()));
257
+ }
258
+ if (isTrustedLibrary) {
259
+ return; // Trusted library, skip
260
+ }
261
+ // Check if it's a CORS call
262
+ if (/\bcors\s*\(/i.test(text) || isCorsCall) {
263
+ // Check arguments for wildcard origin
264
+ // For app.use(cors({ origin: "*" })), we need to check the arguments to cors(), not app.use()
265
+ const corsCallArg = firstArg && firstArg.type === 'CallExpression' ? firstArg : null;
266
+ const argsToCheck = corsCallArg ? corsCallArg.arguments : node.arguments;
267
+ for (const arg of argsToCheck) {
268
+ if (arg.type === 'ObjectExpression') {
269
+ // Check for origin property with wildcard value
270
+ for (const prop of arg.properties) {
271
+ if (prop.type === 'Property' &&
272
+ prop.key.type === 'Identifier' &&
273
+ prop.key.name === 'origin' &&
274
+ prop.value.type === 'Literal' &&
275
+ prop.value.value === '*') {
276
+ context.report({
277
+ node: prop.value,
278
+ messageId: 'missingCorsCheck',
279
+ data: {
280
+ issue: 'Wildcard CORS origin (*) allows all origins',
281
+ safeAlternative: 'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));',
282
+ },
283
+ suggest: [
284
+ {
285
+ messageId: 'useOriginValidation',
286
+ fix: (_fixer) => null,
287
+ },
288
+ ],
289
+ });
290
+ }
291
+ }
292
+ }
293
+ else if (arg.type === 'Identifier') {
294
+ // Check if this identifier was assigned an object literal with origin: "*"
295
+ // For cases like: const config = { origin: "*" }; app.use(cors(config));
296
+ const varName = arg.name;
297
+ // Traverse the AST to find the variable declaration
298
+ let current = node;
299
+ while (current) {
300
+ if (current.type === 'Program' || current.type === 'FunctionDeclaration' || current.type === 'FunctionExpression' || current.type === 'ArrowFunctionExpression') {
301
+ // Search for variable declarations in this scope
302
+ const scopeBody = current.type === 'Program' ? current.body :
303
+ (current.type === 'FunctionDeclaration' || current.type === 'FunctionExpression' || current.type === 'ArrowFunctionExpression') ?
304
+ (current.body.type === 'BlockStatement' ? current.body.body : []) : [];
305
+ for (const stmt of scopeBody) {
306
+ if (stmt.type === 'VariableDeclaration') {
307
+ for (const declarator of stmt.declarations) {
308
+ if (declarator.id.type === 'Identifier' && declarator.id.name === varName && declarator.init) {
309
+ // Check if init is an object literal with origin: "*"
310
+ if (declarator.init.type === 'ObjectExpression') {
311
+ for (const prop of declarator.init.properties) {
312
+ if (prop.type === 'Property' &&
313
+ prop.key.type === 'Identifier' &&
314
+ prop.key.name === 'origin' &&
315
+ prop.value.type === 'Literal' &&
316
+ prop.value.value === '*') {
317
+ context.report({
318
+ node: arg,
319
+ messageId: 'missingCorsCheck',
320
+ data: {
321
+ issue: 'Wildcard CORS origin (*) allows all origins',
322
+ safeAlternative: 'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));',
323
+ },
324
+ suggest: [
325
+ {
326
+ messageId: 'useOriginValidation',
327
+ fix: (_fixer) => null,
328
+ },
329
+ ],
330
+ });
331
+ return; // Found and reported, exit
332
+ }
333
+ }
334
+ }
335
+ }
336
+ }
337
+ }
338
+ }
339
+ break; // Only check the immediate scope
340
+ }
341
+ if (current.parent) {
342
+ current = current.parent;
343
+ }
344
+ else {
345
+ break;
346
+ }
347
+ }
348
+ }
349
+ }
350
+ }
351
+ }
352
+ }
353
+ }
354
+ function checkMemberExpression(node) {
355
+ if (isTestFile) {
356
+ return;
357
+ }
358
+ // Check for Access-Control-Allow-Origin header without validation
359
+ if (node.property.type === 'Identifier') {
360
+ const propertyName = node.property.name;
361
+ if (propertyName === 'setHeader' || propertyName === 'header') {
362
+ // Check if it matches any ignore pattern
363
+ const text = sourceCode.getText(node);
364
+ if (matchesIgnorePattern(text, ignorePatterns)) {
365
+ return;
366
+ }
367
+ // Check if it's setting CORS headers
368
+ // Need to check the full call expression, not just the member expression
369
+ const parent = node.parent;
370
+ if (parent && parent.type === 'CallExpression') {
371
+ const callText = sourceCode.getText(parent);
372
+ if (/\bAccess-Control-Allow-Origin\b/i.test(callText)) {
373
+ // Check if the value is a wildcard
374
+ const args = parent.arguments;
375
+ if (args.length >= 2 && args[1].type === 'Literal' && args[1].value === '*') {
376
+ context.report({
377
+ node: args[1],
378
+ messageId: 'missingCorsCheck',
379
+ data: {
380
+ issue: 'Wildcard CORS header allows all origins',
381
+ safeAlternative: 'Validate origin before setting header: res.setHeader("Access-Control-Allow-Origin", allowedOrigins.includes(origin) ? origin : "null");',
382
+ },
383
+ suggest: [
384
+ {
385
+ messageId: 'useOriginValidation',
386
+ fix: (_fixer) => null,
387
+ },
388
+ ],
389
+ });
390
+ }
391
+ }
392
+ }
393
+ }
394
+ }
395
+ }
396
+ return {
397
+ Literal: checkLiteral,
398
+ CallExpression: checkCallExpression,
399
+ MemberExpression: checkMemberExpression,
400
+ };
401
+ },
402
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+ /**
7
+ * ESLint Rule: no-missing-csrf-protection
8
+ * Detects missing CSRF token validation in POST/PUT/DELETE requests
9
+ * CWE-352: Cross-Site Request Forgery (CSRF)
10
+ *
11
+ * @see https://cwe.mitre.org/data/definitions/352.html
12
+ * @see https://owasp.org/www-community/attacks/csrf
13
+ */
14
+ import type { TSESLint } from '@interlace/eslint-devkit';
15
+ type MessageIds = 'missingCsrfProtection' | 'addCsrfValidation';
16
+ export interface Options {
17
+ /** Allow missing CSRF protection in test files. Default: false */
18
+ allowInTests?: boolean;
19
+ /** CSRF middleware patterns to recognize. Default: ['csrf', 'csurf', 'csrfProtection', 'verifyCsrfToken'] */
20
+ csrfMiddlewarePatterns?: string[];
21
+ /** HTTP methods that require CSRF protection. Default: ['post', 'put', 'delete', 'patch'] */
22
+ protectedMethods?: string[];
23
+ /** Additional safe patterns to ignore. Default: [] */
24
+ ignorePatterns?: string[];
25
+ }
26
+ type RuleOptions = [Options?];
27
+ export declare const noMissingCsrfProtection: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener> & {
28
+ name: string;
29
+ };
30
+ export {};
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Ofri Peretz
4
+ * Licensed under the MIT License. Use of this source code is governed by the
5
+ * MIT license that can be found in the LICENSE file.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.noMissingCsrfProtection = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ const eslint_devkit_2 = require("@interlace/eslint-devkit");
11
+ /**
12
+ * Default CSRF middleware patterns
13
+ */
14
+ const DEFAULT_CSRF_MIDDLEWARE_PATTERNS = [
15
+ 'csrf',
16
+ 'csurf',
17
+ 'csrfProtection',
18
+ 'verifyCsrfToken',
19
+ 'csrfToken',
20
+ 'validateCsrf',
21
+ 'checkCsrf',
22
+ 'csrfMiddleware',
23
+ ];
24
+ /**
25
+ * Default HTTP methods that require CSRF protection
26
+ */
27
+ const DEFAULT_PROTECTED_METHODS = ['post', 'put', 'delete', 'patch'];
28
+ /**
29
+ * Check if a string matches any ignore pattern
30
+ */
31
+ function matchesIgnorePattern(text, patterns) {
32
+ return patterns.some(pattern => {
33
+ try {
34
+ const regex = new RegExp(pattern, 'i');
35
+ return regex.test(text);
36
+ }
37
+ catch {
38
+ return text.toLowerCase().includes(pattern.toLowerCase());
39
+ }
40
+ });
41
+ }
42
+ exports.noMissingCsrfProtection = (0, eslint_devkit_2.createRule)({
43
+ name: 'no-missing-csrf-protection',
44
+ meta: {
45
+ type: 'problem',
46
+ deprecated: true,
47
+ replacedBy: ['@see eslint-plugin-express-security/require-csrf-protection'],
48
+ docs: {
49
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-csrf-protection.md',
50
+ description: 'Detects missing CSRF token validation in POST/PUT/DELETE requests',
51
+ cwe: 'CWE-352',
52
+ cvss: 8.8,
53
+ },
54
+ hasSuggestions: true,
55
+ messages: {
56
+ missingCsrfProtection: (0, eslint_devkit_1.formatLLMMessage)({
57
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
58
+ issueName: 'Missing CSRF Protection',
59
+ cwe: 'CWE-352',
60
+ description: 'Missing CSRF protection detected: {{issue}}',
61
+ severity: 'HIGH',
62
+ fix: '{{safeAlternative}}',
63
+ documentationLink: 'https://cwe.mitre.org/data/definitions/352.html',
64
+ }),
65
+ addCsrfValidation: (0, eslint_devkit_1.formatLLMMessage)({
66
+ icon: eslint_devkit_1.MessageIcons.INFO,
67
+ issueName: 'Add CSRF Validation',
68
+ description: 'Add CSRF middleware',
69
+ severity: 'LOW',
70
+ fix: 'app.use(csrf({ cookie: true }))',
71
+ documentationLink: 'https://github.com/expressjs/csurf',
72
+ }),
73
+ },
74
+ schema: [
75
+ {
76
+ type: 'object',
77
+ properties: {
78
+ allowInTests: {
79
+ type: 'boolean',
80
+ default: false,
81
+ description: 'Allow missing CSRF protection in test files',
82
+ },
83
+ csrfMiddlewarePatterns: {
84
+ type: 'array',
85
+ items: { type: 'string' },
86
+ default: [],
87
+ description: 'CSRF middleware patterns to recognize',
88
+ },
89
+ protectedMethods: {
90
+ type: 'array',
91
+ items: { type: 'string' },
92
+ default: [],
93
+ description: 'HTTP methods that require CSRF protection',
94
+ },
95
+ ignorePatterns: {
96
+ type: 'array',
97
+ items: { type: 'string' },
98
+ default: [],
99
+ description: 'Additional safe patterns to ignore',
100
+ },
101
+ },
102
+ additionalProperties: false,
103
+ },
104
+ ],
105
+ },
106
+ defaultOptions: [
107
+ {
108
+ allowInTests: false,
109
+ csrfMiddlewarePatterns: [],
110
+ protectedMethods: [],
111
+ ignorePatterns: [],
112
+ },
113
+ ],
114
+ create(context, [options = {}]) {
115
+ const { allowInTests = false, csrfMiddlewarePatterns, protectedMethods: customProtectedMethods, ignorePatterns = [], } = options;
116
+ const csrfPatterns = csrfMiddlewarePatterns && csrfMiddlewarePatterns.length > 0
117
+ ? csrfMiddlewarePatterns
118
+ : DEFAULT_CSRF_MIDDLEWARE_PATTERNS;
119
+ const protectedMethods = customProtectedMethods && customProtectedMethods.length > 0
120
+ ? customProtectedMethods
121
+ : DEFAULT_PROTECTED_METHODS;
122
+ // Pre-compute Set for O(1) lookups (performance optimization)
123
+ const protectedMethodsSet = new Set(protectedMethods.map(m => m.toLowerCase()));
124
+ const filename = context.filename;
125
+ const isTestFile = allowInTests && /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);
126
+ const sourceCode = context.sourceCode;
127
+ function checkCallExpression(node) {
128
+ if (isTestFile) {
129
+ return;
130
+ }
131
+ const callee = node.callee;
132
+ const callText = sourceCode.getText(node);
133
+ // Check if it matches any ignore pattern
134
+ if (matchesIgnorePattern(callText, ignorePatterns)) {
135
+ return;
136
+ }
137
+ // Check for route handler methods (app.post, router.put, etc.)
138
+ if (callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression && callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
139
+ const methodName = callee.property.name;
140
+ // Only check if it's a route handler that requires CSRF (O(1) Set lookup)
141
+ if (protectedMethodsSet.has(methodName.toLowerCase())) {
142
+ // Must have at least 2 arguments (path and handler)
143
+ if (node.arguments.length < 2) {
144
+ return;
145
+ }
146
+ // Check if CSRF middleware is in the route chain arguments
147
+ let hasCsrfInChain = false;
148
+ // Check if any argument (after the first path argument) is a CSRF middleware
149
+ // Skip the first argument (path) and check the rest
150
+ for (let i = 1; i < node.arguments.length; i++) {
151
+ const arg = node.arguments[i];
152
+ const argText = sourceCode.getText(arg);
153
+ if (csrfPatterns.some(pattern => argText.toLowerCase().includes(pattern.toLowerCase()))) {
154
+ hasCsrfInChain = true;
155
+ break;
156
+ }
157
+ }
158
+ if (!hasCsrfInChain) {
159
+ context.report({
160
+ node,
161
+ messageId: 'missingCsrfProtection',
162
+ data: {
163
+ issue: `${methodName.toUpperCase()} route handler missing CSRF protection`,
164
+ safeAlternative: `Add CSRF middleware: app.${methodName}("/path", csrf(), handler) or use app.use(csrf()) globally`,
165
+ },
166
+ suggest: [
167
+ {
168
+ messageId: 'addCsrfValidation',
169
+ fix(fixer) {
170
+ // Add CSRF middleware after the first argument (path)
171
+ const firstArg = node.arguments[0];
172
+ if (firstArg) {
173
+ return fixer.insertTextAfter(firstArg, ', csrf()');
174
+ }
175
+ return null;
176
+ },
177
+ },
178
+ ],
179
+ });
180
+ }
181
+ }
182
+ }
183
+ }
184
+ return {
185
+ CallExpression: checkCallExpression,
186
+ };
187
+ },
188
+ });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+ /**
7
+ * ESLint Rule: no-missing-security-headers
8
+ * Detects missing security headers in HTTP responses
9
+ * CWE-693: Protection Mechanism Failure
10
+ *
11
+ * @see https://cwe.mitre.org/data/definitions/693.html
12
+ * @see https://owasp.org/www-project-secure-headers/
13
+ */
14
+ import type { TSESLint } from '@interlace/eslint-devkit';
15
+ type MessageIds = 'missingSecurityHeader' | 'addSecurityHeaders' | 'useMiddleware' | 'setHeader';
16
+ export interface Options {
17
+ /** Required security headers. Default: ['Content-Security-Policy', 'X-Frame-Options', 'X-Content-Type-Options'] */
18
+ requiredHeaders?: string[];
19
+ /** Ignore in test files. Default: true */
20
+ ignoreInTests?: boolean;
21
+ }
22
+ type RuleOptions = [Options?];
23
+ export declare const noMissingSecurityHeaders: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener> & {
24
+ name: string;
25
+ };
26
+ export {};