eslint-plugin-browser-security 2.1.0 → 2.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/package.json +2 -2
- package/src/index.js +1 -1
- package/src/rules/no-clickjacking/index.js +1 -1
- package/src/rules/no-client-side-auth-logic/index.js +1 -1
- package/src/rules/no-disabled-certificate-validation/index.js +1 -1
- package/src/rules/no-dynamic-service-worker-url/index.js +1 -1
- package/src/rules/no-filereader-innerhtml/index.js +1 -1
- package/src/rules/no-incomplete-url-sanitization/index.js +1 -1
- package/src/rules/no-insecure-redirects/index.js +1 -1
- package/src/rules/no-missing-cors-check/index.js +1 -1
- package/src/rules/no-missing-csrf-protection/index.js +1 -1
- package/src/rules/no-missing-security-headers/index.js +1 -1
- package/src/rules/no-permissive-cors/index.js +1 -1
- package/src/rules/no-postmessage-innerhtml/index.js +1 -1
- package/src/rules/no-postmessage-wildcard-origin/index.js +1 -1
- package/src/rules/no-unencrypted-transmission/index.js +1 -1
- package/src/rules/no-unescaped-url-parameter/index.js +1 -1
- package/src/rules/no-unescaped-url-parameter/untrusted-text.js +1 -1
- package/src/rules/no-unvalidated-deeplinks/index.js +1 -1
- package/src/rules/no-websocket-innerhtml/index.js +1 -1
- package/src/rules/no-worker-message-innerhtml/index.js +1 -1
- package/src/rules/require-blob-url-revocation/index.js +1 -1
- package/src/rules/require-csp-headers/index.js +1 -1
- package/src/rules/require-mime-type-validation/index.js +1 -1
- package/src/rules/require-postmessage-origin-check/index.js +1 -1
- package/src/rules/require-url-validation/index.js +1 -1
- package/src/utils/analytics-sinks.js +1 -1
- package/src/utils/dynamic-code-sinks.js +1 -1
- package/src/utils/express-app.js +1 -1
- package/src/utils/global-object.js +1 -1
- package/src/utils/navigation-targets.js +1 -1
- package/src/utils/protocol-inspection.js +1 -1
- package/src/utils/sensitive-value-evidence.js +1 -1
- package/src/utils/transport-ownership.js +1 -1
- package/src/utils/url-taint.js +1 -1
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
<p align="center">
|
|
16
16
|
<a href="https://www.npmjs.com/package/eslint-plugin-browser-security" target="_blank"><img src="https://img.shields.io/npm/v/eslint-plugin-browser-security.svg" alt="NPM Version" /></a>
|
|
17
17
|
<a href="https://www.npmjs.com/package/eslint-plugin-browser-security" target="_blank"><img src="https://img.shields.io/npm/dm/eslint-plugin-browser-security.svg" alt="NPM Downloads" /></a>
|
|
18
|
+
<a href="https://packagephobia.com/result?p=eslint-plugin-browser-security" target="_blank"><img src="https://badgen.net/packagephobia/install/eslint-plugin-browser-security" alt="Install Size" /></a>
|
|
18
19
|
<a href="https://opensource.org/licenses/MIT" target="_blank"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="Package License" /></a>
|
|
19
20
|
<a href="https://app.codecov.io/gh/ofri-peretz/eslint/components?components%5B0%5D=eslint-plugin-browser-security" target="_blank"><img src="https://codecov.io/gh/ofri-peretz/eslint/graph/badge.svg?component=eslint-plugin-browser-security" alt="Codecov" /></a>
|
|
20
21
|
<a href="https://github.com/ofri-peretz/eslint" target="_blank"><img src="https://img.shields.io/badge/Since-Dec_2025-blue?logo=rocket&logoColor=white" alt="Since Dec 2025" /></a>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-browser-security",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.2",
|
|
4
4
|
"description": "ESLint plugin for browser security — detects DOM XSS, postMessage abuse, tokens in localStorage, insecure cookies, clickjacking, mixed content, and CSP gaps.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"node": ">=18.0.0"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@interlace/eslint-devkit": "^1.
|
|
77
|
+
"@interlace/eslint-devkit": "^1.19.0"
|
|
78
78
|
},
|
|
79
79
|
"peerDependencies": {
|
|
80
80
|
"eslint": "^8.40.0 || ^9.0.0 || ^10.0.0"
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-innerhtml"(){return require("./rules/no-innerhtml").noInnerhtml},get"no-eval"(){return require("./rules/no-eval").noEval},get"require-postmessage-origin-check"(){return require("./rules/require-postmessage-origin-check").requirePostmessageOriginCheck},get"no-postmessage-wildcard-origin"(){return require("./rules/no-postmessage-wildcard-origin").noPostmessageWildcardOrigin},get"no-postmessage-innerhtml"(){return require("./rules/no-postmessage-innerhtml").noPostmessageInnerhtml},get"no-sensitive-localstorage"(){return require("./rules/no-sensitive-localstorage").noSensitiveLocalstorage},get"no-jwt-in-storage"(){return require("./rules/no-jwt-in-storage").noJwtInStorage},get"no-sensitive-sessionstorage"(){return require("./rules/no-sensitive-sessionstorage").noSensitiveSessionstorage},get"no-sensitive-indexeddb"(){return require("./rules/no-sensitive-indexeddb").noSensitiveIndexeddb},get"no-sensitive-cookie-js"(){return require("./rules/no-sensitive-cookie-js").noSensitiveCookieJs},get"no-cookie-auth-tokens"(){return require("./rules/no-cookie-auth-tokens").noCookieAuthTokens},get"require-cookie-secure-attrs"(){return require("./rules/require-cookie-secure-attrs").requireCookieSecureAttrs},get"require-websocket-wss"(){return require("./rules/require-websocket-wss").requireWebsocketWss},get"no-websocket-innerhtml"(){return require("./rules/no-websocket-innerhtml").noWebsocketInnerhtml},get"no-websocket-eval"(){return require("./rules/no-websocket-eval").noWebsocketEval},get"no-filereader-innerhtml"(){return require("./rules/no-filereader-innerhtml").noFilereaderInnerhtml},get"require-blob-url-revocation"(){return require("./rules/require-blob-url-revocation").requireBlobUrlRevocation},get"no-dynamic-service-worker-url"(){return require("./rules/no-dynamic-service-worker-url").noDynamicServiceWorkerUrl},get"no-worker-message-innerhtml"(){return require("./rules/no-worker-message-innerhtml").noWorkerMessageInnerhtml},get"no-unsafe-inline-csp"(){return require("./rules/no-unsafe-inline-csp").noUnsafeInlineCsp},get"no-unsafe-eval-csp"(){return require("./rules/no-unsafe-eval-csp").noUnsafeEvalCsp},get"detect-mixed-content"(){return require("./rules/detect-mixed-content").detectMixedContent},get"no-allow-arbitrary-loads"(){return require("./rules/no-allow-arbitrary-loads").noAllowArbitraryLoads},get"no-clickjacking"(){return require("./rules/no-clickjacking").noClickjacking},get"no-credentials-in-query-params"(){return require("./rules/no-credentials-in-query-params").noCredentialsInQueryParams},get"no-http-urls"(){return require("./rules/no-http-urls").noHttpUrls},get"no-incomplete-url-sanitization"(){return require("./rules/no-incomplete-url-sanitization").noIncompleteUrlSanitization},get"no-insecure-redirects"(){return require("./rules/no-insecure-redirects").noInsecureRedirects},get"no-insecure-websocket"(){return require("./rules/no-insecure-websocket").noInsecureWebsocket},get"no-missing-cors-check"(){return require("./rules/no-missing-cors-check").noMissingCorsCheck},get"no-missing-csrf-protection"(){return require("./rules/no-missing-csrf-protection").noMissingCsrfProtection},get"no-missing-security-headers"(){return require("./rules/no-missing-security-headers").noMissingSecurityHeaders},get"no-password-in-url"(){return require("./rules/no-password-in-url").noPasswordInUrl},get"no-permissive-cors"(){return require("./rules/no-permissive-cors").noPermissiveCors},get"no-sensitive-data-in-analytics"(){return require("./rules/no-sensitive-data-in-analytics").noSensitiveDataInAnalytics},get"no-sensitive-data-in-cache"(){return require("./rules/no-sensitive-data-in-cache").noSensitiveDataInCache},get"no-tracking-without-consent"(){return require("./rules/no-tracking-without-consent").noTrackingWithoutConsent},get"no-unencrypted-transmission"(){return require("./rules/no-unencrypted-transmission").noUnencryptedTransmission},get"no-unescaped-url-parameter"(){return require("./rules/no-unescaped-url-parameter").noUnescapedUrlParameter},get"no-unvalidated-deeplinks"(){return require("./rules/no-unvalidated-deeplinks").noUnvalidatedDeeplinks},get"require-csp-headers"(){return require("./rules/require-csp-headers").requireCspHeaders},get"require-https-only"(){return require("./rules/require-https-only").requireHttpsOnly},get"require-url-validation"(){return require("./rules/require-url-validation").requireUrlValidation},get"require-mime-type-validation"(){return require("./rules/require-mime-type-validation").requireMimeTypeValidation},get"no-disabled-certificate-validation"(){return require("./rules/no-disabled-certificate-validation").noDisabledCertificateValidation},get"no-client-side-auth-logic"(){return require("./rules/no-client-side-auth-logic").noClientSideAuthLogic}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-browser-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-browser-security",version:"2.1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-innerhtml"(){return require("./rules/no-innerhtml").noInnerhtml},get"no-eval"(){return require("./rules/no-eval").noEval},get"require-postmessage-origin-check"(){return require("./rules/require-postmessage-origin-check").requirePostmessageOriginCheck},get"no-postmessage-wildcard-origin"(){return require("./rules/no-postmessage-wildcard-origin").noPostmessageWildcardOrigin},get"no-postmessage-innerhtml"(){return require("./rules/no-postmessage-innerhtml").noPostmessageInnerhtml},get"no-sensitive-localstorage"(){return require("./rules/no-sensitive-localstorage").noSensitiveLocalstorage},get"no-jwt-in-storage"(){return require("./rules/no-jwt-in-storage").noJwtInStorage},get"no-sensitive-sessionstorage"(){return require("./rules/no-sensitive-sessionstorage").noSensitiveSessionstorage},get"no-sensitive-indexeddb"(){return require("./rules/no-sensitive-indexeddb").noSensitiveIndexeddb},get"no-sensitive-cookie-js"(){return require("./rules/no-sensitive-cookie-js").noSensitiveCookieJs},get"no-cookie-auth-tokens"(){return require("./rules/no-cookie-auth-tokens").noCookieAuthTokens},get"require-cookie-secure-attrs"(){return require("./rules/require-cookie-secure-attrs").requireCookieSecureAttrs},get"require-websocket-wss"(){return require("./rules/require-websocket-wss").requireWebsocketWss},get"no-websocket-innerhtml"(){return require("./rules/no-websocket-innerhtml").noWebsocketInnerhtml},get"no-websocket-eval"(){return require("./rules/no-websocket-eval").noWebsocketEval},get"no-filereader-innerhtml"(){return require("./rules/no-filereader-innerhtml").noFilereaderInnerhtml},get"require-blob-url-revocation"(){return require("./rules/require-blob-url-revocation").requireBlobUrlRevocation},get"no-dynamic-service-worker-url"(){return require("./rules/no-dynamic-service-worker-url").noDynamicServiceWorkerUrl},get"no-worker-message-innerhtml"(){return require("./rules/no-worker-message-innerhtml").noWorkerMessageInnerhtml},get"no-unsafe-inline-csp"(){return require("./rules/no-unsafe-inline-csp").noUnsafeInlineCsp},get"no-unsafe-eval-csp"(){return require("./rules/no-unsafe-eval-csp").noUnsafeEvalCsp},get"detect-mixed-content"(){return require("./rules/detect-mixed-content").detectMixedContent},get"no-allow-arbitrary-loads"(){return require("./rules/no-allow-arbitrary-loads").noAllowArbitraryLoads},get"no-clickjacking"(){return require("./rules/no-clickjacking").noClickjacking},get"no-credentials-in-query-params"(){return require("./rules/no-credentials-in-query-params").noCredentialsInQueryParams},get"no-http-urls"(){return require("./rules/no-http-urls").noHttpUrls},get"no-incomplete-url-sanitization"(){return require("./rules/no-incomplete-url-sanitization").noIncompleteUrlSanitization},get"no-insecure-redirects"(){return require("./rules/no-insecure-redirects").noInsecureRedirects},get"no-insecure-websocket"(){return require("./rules/no-insecure-websocket").noInsecureWebsocket},get"no-missing-cors-check"(){return require("./rules/no-missing-cors-check").noMissingCorsCheck},get"no-missing-csrf-protection"(){return require("./rules/no-missing-csrf-protection").noMissingCsrfProtection},get"no-missing-security-headers"(){return require("./rules/no-missing-security-headers").noMissingSecurityHeaders},get"no-password-in-url"(){return require("./rules/no-password-in-url").noPasswordInUrl},get"no-permissive-cors"(){return require("./rules/no-permissive-cors").noPermissiveCors},get"no-sensitive-data-in-analytics"(){return require("./rules/no-sensitive-data-in-analytics").noSensitiveDataInAnalytics},get"no-sensitive-data-in-cache"(){return require("./rules/no-sensitive-data-in-cache").noSensitiveDataInCache},get"no-tracking-without-consent"(){return require("./rules/no-tracking-without-consent").noTrackingWithoutConsent},get"no-unencrypted-transmission"(){return require("./rules/no-unencrypted-transmission").noUnencryptedTransmission},get"no-unescaped-url-parameter"(){return require("./rules/no-unescaped-url-parameter").noUnescapedUrlParameter},get"no-unvalidated-deeplinks"(){return require("./rules/no-unvalidated-deeplinks").noUnvalidatedDeeplinks},get"require-csp-headers"(){return require("./rules/require-csp-headers").requireCspHeaders},get"require-https-only"(){return require("./rules/require-https-only").requireHttpsOnly},get"require-url-validation"(){return require("./rules/require-url-validation").requireUrlValidation},get"require-mime-type-validation"(){return require("./rules/require-mime-type-validation").requireMimeTypeValidation},get"no-disabled-certificate-validation"(){return require("./rules/no-disabled-certificate-validation").noDisabledCertificateValidation},get"no-client-side-auth-logic"(){return require("./rules/no-client-side-auth-logic").noClientSideAuthLogic}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-browser-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-browser-security",version:"2.1.2"},rules:exports.rules};const recommendedRules={"browser-security/no-innerhtml":"error","browser-security/no-eval":"error","browser-security/require-postmessage-origin-check":"error","browser-security/no-postmessage-wildcard-origin":"error","browser-security/no-postmessage-innerhtml":"error","browser-security/no-sensitive-localstorage":"error","browser-security/no-jwt-in-storage":"error","browser-security/no-sensitive-sessionstorage":"error","browser-security/no-sensitive-indexeddb":"error","browser-security/no-sensitive-cookie-js":"error","browser-security/no-cookie-auth-tokens":"error","browser-security/require-cookie-secure-attrs":"error","browser-security/require-websocket-wss":"error","browser-security/no-websocket-innerhtml":"error","browser-security/no-websocket-eval":"error","browser-security/no-filereader-innerhtml":"error","browser-security/require-blob-url-revocation":"warn","browser-security/no-dynamic-service-worker-url":"error","browser-security/no-worker-message-innerhtml":"error","browser-security/no-unsafe-inline-csp":"error","browser-security/no-unsafe-eval-csp":"error","browser-security/detect-mixed-content":"error","browser-security/no-unencrypted-transmission":"error","browser-security/no-allow-arbitrary-loads":"error","browser-security/no-credentials-in-query-params":"error","browser-security/no-http-urls":"error","browser-security/no-incomplete-url-sanitization":"error","browser-security/no-insecure-redirects":"error","browser-security/no-disabled-certificate-validation":"error","browser-security/require-https-only":"error","browser-security/no-insecure-websocket":"error","browser-security/no-unvalidated-deeplinks":"error","browser-security/no-client-side-auth-logic":"error"};exports.configs={flagship:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-postmessage-wildcard-origin":"error"}},recommended:{plugins:{"browser-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"browser-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`browser-security/${ruleName}`,"error"]))},xss:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-innerhtml":"error","browser-security/no-eval":"error"}},storage:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-sensitive-localstorage":"error"}},postmessage:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/require-postmessage-origin-check":"error","browser-security/no-postmessage-wildcard-origin":"error"}},websocket:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/require-websocket-wss":"error"}},cookies:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-sensitive-cookie-js":"error"}}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noClickjacking=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 resolve_binding_1=require("../../utils/resolve-binding");const FRAME_REFS=new Set(["top","self","parent","window"]);function isFrameRef(node){if(node.type==="Identifier")return FRAME_REFS.has(node.name);if(node.type==="MemberExpression"&&node.object.type==="Identifier"&&node.object.name==="window"){return node.property.type==="Identifier"&&FRAME_REFS.has(node.property.name)}return false}function isFrameBustingTest(test){return test.type==="BinaryExpression"&&["!=","!==","==","==="].includes(test.operator)&&isFrameRef(test.left)&&isFrameRef(test.right)}function readsFrameLocation(node,depth=0){if(depth>8)return false;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="location"&&isFrameRef(node.object)){return true}if(node.type==="BinaryExpression"||node.type==="LogicalExpression"){return readsFrameLocation(node.left,depth+1)||readsFrameLocation(node.right,depth+1)}if(node.type==="UnaryExpression"){return readsFrameLocation(node.argument,depth+1)}return false}const DECLARATION=/(?:^|[^a-z-])([a-z-]+)\s*:\s*([^;{}"'`\n]*)/g;function cssDeclarations(text){const declarations=[];for(const match of text.toLowerCase().matchAll(DECLARATION)){const value=match[2].trim().replace(/\s*!important$/,"").replace(/,$/,"").trim();declarations.push([match[1],value])}return declarations}function hasDeclaration(declarations,property,matches){return declarations.some(([prop,value])=>prop===property&&matches(value))}const CSS_PROPERTIES=new Set(["position","top","left","right","bottom","width","height","opacity","visibility","display","z-index","background","background-color","pointer-events","transform","margin","padding","border","overflow","content","transition","animation"]);function animatesProperty(declarations,property){return declarations.some(([prop,value])=>{if(prop==="animation")return true;if(prop!=="transition")return false;const tokens=value.split(/[\s,]+/);return tokens.includes(property)||tokens.includes("all")})}function looksLikeCss(declarations){return declarations.some(([prop])=>CSS_PROPERTIES.has(prop))}function foldToString(node,sourceCode,depth){if(depth>4)return null;if(node.type==="Literal"){return typeof node.value==="string"?node.value:null}if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToString(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const array=foldToArrayExpression(node.object,sourceCode,depth+1);const element=array?.elements[index.value];return element==null?null:foldToString(element,sourceCode,depth+1)}return null}function foldToArrayExpression(node,sourceCode,depth){if(depth>4)return null;if(node.type==="ArrayExpression")return node;if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToArrayExpression(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const outer=foldToArrayExpression(node.object,sourceCode,depth+1);const element=outer?.elements[index.value];return element==null?null:foldToArrayExpression(element,sourceCode,depth+1)}return null}function originOf(url){const match=/^([a-z][a-z0-9+.-]*:)?\/\/([^/?#]+)/i.exec(url);return match===null?null:`${(match[1]??"").toLowerCase()}//${match[2].toLowerCase()}`}const FUNCTION_TYPES=new Set(["FunctionDeclaration","FunctionExpression","ArrowFunctionExpression"]);function runsOnlyInsideGuard(fn,guard,sourceCode){const parent=fn.parent;if(parent?.type==="CallExpression"&&parent.arguments.includes(fn)){return true}if(parent?.type==="CallExpression"&&parent.callee===fn)return true;const declarator=fn.type==="FunctionDeclaration"?fn:parent?.type==="VariableDeclarator"?parent:void 0;if(declarator===void 0)return false;return sourceCode.getDeclaredVariables(declarator).every(variable=>variable.references.every(ref=>ref.identifier.range[0]>=guard.range[0]&&ref.identifier.range[1]<=guard.range[1]))}function insideFrameBustingGuard(node,sourceCode){const crossed=[];let current=node.parent;while(current){if(FUNCTION_TYPES.has(current.type))crossed.push(current);if(current.type==="IfStatement"&&(isFrameBustingTest(current.test)||readsFrameLocation(current.test))){const guard=current;return crossed.every(fn=>runsOnlyInsideGuard(fn,guard,sourceCode))}current=current.parent}return false}exports.noClickjacking=(0,eslint_devkit_1.createRule)({name:"no-clickjacking",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-helmet"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-clickjacking.md",description:"Detects clickjacking vulnerabilities and missing frame protections",cwe:"CWE-1021"},messages:{missingFrameBusting:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Frame Busting",cwe:"CWE-1021",description:"No frame-busting code to prevent clickjacking",severity:"HIGH",fix:"Add frame-busting JavaScript to prevent framing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"}),unsafeIframeUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe iframe Usage",cwe:"CWE-1021",description:"iframe may enable clickjacking attacks",severity:"MEDIUM",fix:"Add X-Frame-Options or CSP frame-ancestors protection",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"}),transparentFrameOverlay:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Transparent Frame Overlay",cwe:"CWE-1021",description:"Transparent elements may hide clickjacking attacks",severity:"MEDIUM",fix:"Use frame-busting or CSP protections",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"}),frameManipulation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Frame Manipulation",cwe:"CWE-1021",description:"Code attempts to manipulate parent frames",severity:"LOW",fix:"Implement proper frame communication or prevent framing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"})},schema:[{type:"object",properties:{trustedSources:{type:"array",items:{type:"string"},default:["self","same-origin"],description:"Frame-ancestor sources treated as safe"},requireFrameBusting:{type:"boolean",default:true,description:"Require frame-busting code in addition to headers"},detectTransparentOverlays:{type:"boolean",default:true,description:"Report transparent overlays positioned over clickable elements"},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:[{trustedSources:["self","same-origin"],requireFrameBusting:true,detectTransparentOverlays:true,trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{trustedSources=["self","same-origin"],requireFrameBusting=true,detectTransparentOverlays=true,trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedAnnotations,trustedOrmPatterns:[],strictMode});let hasFrameBusting=false;let buildsDocumentShell=false;let hasDeclaredFrameProtection=false;const DOCUMENT_SHELL_TAGS=new Set(["html","head","body"]);const declaresFrameProtection=value=>{const text=value.toLowerCase();const ancestors=/frame-ancestors\s+([^;]+)/.exec(text);if(ancestors&&ancestors[1].trim()!=="*")return true;return/^\s*(deny|sameorigin)\s*$/.test(text)||text.includes("x-frame-options")};const isTrustedSource=source=>trustedSources.some(trusted=>{if(trusted===source)return true;if(trusted==="self"||trusted==="same-origin"){return source.startsWith("/")&&!source.startsWith("//")}const trustedOrigin=originOf(trusted);return trustedOrigin!==null&&trustedOrigin===originOf(source)});const isFrameBustingCode=node=>isFrameBustingTest(node.test)||readsFrameLocation(node.test);const hasTransparentStyles=styleText=>{const declarations=cssDeclarations(styleText);if(!looksLikeCss(declarations))return false;if(hasDeclaration(declarations,"display",v=>v==="none")){return false}return hasDeclaration(declarations,"opacity",v=>/^0(?:\.0+)?%?$/.test(v))&&!animatesProperty(declarations,"opacity")||hasDeclaration(declarations,"visibility",v=>v==="hidden")&&!animatesProperty(declarations,"visibility")||hasDeclaration(declarations,"z-index",v=>/^-\d+$/.test(v))};return{IfStatement(node){if(isFrameBustingCode(node)){hasFrameBusting=true}},JSXElement(node){if(node.openingElement.name.type==="JSXIdentifier"){const tag=node.openingElement.name.name;if(DOCUMENT_SHELL_TAGS.has(tag)){buildsDocumentShell=true}}if(node.openingElement.name.type==="JSXIdentifier"&&node.openingElement.name.name==="iframe"){const attributes=node.openingElement.attributes;let hasSrc=false;let srcValue="";for(const attr of attributes){if(attr.type==="JSXAttribute"&&attr.name.type==="JSXIdentifier"&&attr.name.name==="src"&&attr.value){hasSrc=true;if(attr.value.type==="Literal"&&typeof attr.value.value==="string"){srcValue=attr.value.value}else if(attr.value.type==="JSXExpressionContainer"){srcValue=foldToString(attr.value.expression,sourceCode,0)??""}}}if(hasSrc&&srcValue&&!isTrustedSource(srcValue)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.openingElement,messageId:"unsafeIframeUsage",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},MemberExpression(node){if(isFrameRef(node.object)&&!(node.object.type==="Identifier"&&node.object.name==="self")){if(node.property.type==="Identifier"&&(node.property.name==="location"||node.property.name==="top")){let current=node;let isFrameManipulation=false;while(current){if(current.type==="AssignmentExpression"&¤t.left===node){isFrameManipulation=true;break}if(current.type==="BinaryExpression"&&(current.left===node||current.right===node)){const operator=current.operator;if(operator==="!="||operator==="!=="||operator==="=="||operator==="==="){break}isFrameManipulation=true;break}current=current.parent}if(isFrameManipulation){if(safetyChecker.isSafe(node,context)){return}if(insideFrameBustingGuard(node,sourceCode)){return}context.report({node,messageId:"frameManipulation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},Literal(node){if(typeof node.value==="string"&&declaresFrameProtection(node.value)){hasDeclaredFrameProtection=true}if(typeof node.value==="string"&&detectTransparentOverlays){const text=node.value.toLowerCase();if(hasTransparentStyles(text)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"transparentFrameOverlay",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},TemplateLiteral(node){if(node.quasis.some(q=>declaresFrameProtection(q.value.raw))){hasDeclaredFrameProtection=true}if(detectTransparentOverlays){const text=node.quasis.map(q=>q.value.raw).join(" ").toLowerCase();if(hasTransparentStyles(text)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"transparentFrameOverlay",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},"Program:exit"(){if(requireFrameBusting&&buildsDocumentShell&&!hasFrameBusting&&!hasDeclaredFrameProtection){context.report({node:context.sourceCode.ast,messageId:"missingFrameBusting",data:{filePath:filename,line:"1"}})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noClickjacking=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 resolve_binding_1=require("../../utils/resolve-binding");const FRAME_REFS=new Set(["top","self","parent","window"]);function isFrameRef(node){if(node.type==="Identifier")return FRAME_REFS.has(node.name);if(node.type==="MemberExpression"&&node.object.type==="Identifier"&&node.object.name==="window"){return node.property.type==="Identifier"&&FRAME_REFS.has(node.property.name)}return false}function isFrameBustingTest(test){return test.type==="BinaryExpression"&&["!=","!==","==","==="].includes(test.operator)&&isFrameRef(test.left)&&isFrameRef(test.right)}function readsFrameLocation(node,depth=0){if(depth>8)return false;if(node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="location"&&isFrameRef(node.object)){return true}if(node.type==="BinaryExpression"||node.type==="LogicalExpression"){return readsFrameLocation(node.left,depth+1)||readsFrameLocation(node.right,depth+1)}if(node.type==="UnaryExpression"){return readsFrameLocation(node.argument,depth+1)}return false}const DECLARATION=/(?:^|[^a-z-])([a-z-]+)\s*:\s*([^;{}"'`\n]*)/g;function cssDeclarations(text){const declarations=[];for(const match of text.toLowerCase().matchAll(DECLARATION)){const value=match[2].trim().replace(/\s*!important$/,"").replace(/,$/,"").trim();declarations.push([match[1],value])}return declarations}function hasDeclaration(declarations,property,matches){return declarations.some(([prop,value])=>prop===property&&matches(value))}const CSS_PROPERTIES=new Set(["position","top","left","right","bottom","width","height","opacity","visibility","display","z-index","background","background-color","pointer-events","transform","margin","padding","border","overflow","content","transition","animation"]);function animatesProperty(declarations,property){return declarations.some(([prop,value])=>{if(prop==="animation")return true;if(prop!=="transition")return false;const tokens=value.split(/[\s,]+/);return tokens.includes(property)||tokens.includes("all")})}function looksLikeCss(declarations){return declarations.some(([prop])=>CSS_PROPERTIES.has(prop))}function foldToString(node,sourceCode,depth){if(depth>4)return null;if(node.type==="Literal"){return typeof node.value==="string"?node.value:null}if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToString(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const array=foldToArrayExpression(node.object,sourceCode,depth+1);const element=array?.elements[index.value];return element==null?null:foldToString(element,sourceCode,depth+1)}return null}function foldToArrayExpression(node,sourceCode,depth){if(depth>4)return null;if(node.type==="ArrayExpression")return node;if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToArrayExpression(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const outer=foldToArrayExpression(node.object,sourceCode,depth+1);const element=outer?.elements[index.value];return element==null?null:foldToArrayExpression(element,sourceCode,depth+1)}return null}function originOf(url){const match=/^([a-z][a-z0-9+.-]*:)?\/\/([^/?#]+)/i.exec(url);return match===null?null:`${(match[1]??"").toLowerCase()}//${match[2].toLowerCase()}`}const FUNCTION_TYPES=new Set(["FunctionDeclaration","FunctionExpression","ArrowFunctionExpression"]);function runsOnlyInsideGuard(fn,guard,sourceCode){const parent=fn.parent;if(parent?.type==="CallExpression"&&parent.arguments.includes(fn)){return true}if(parent?.type==="CallExpression"&&parent.callee===fn)return true;const declarator=fn.type==="FunctionDeclaration"?fn:parent?.type==="VariableDeclarator"?parent:void 0;if(declarator===void 0)return false;return sourceCode.getDeclaredVariables(declarator).every(variable=>variable.references.every(ref=>ref.identifier.range[0]>=guard.range[0]&&ref.identifier.range[1]<=guard.range[1]))}function insideFrameBustingGuard(node,sourceCode){const crossed=[];let current=node.parent;while(current){if(FUNCTION_TYPES.has(current.type))crossed.push(current);if(current.type==="IfStatement"&&(isFrameBustingTest(current.test)||readsFrameLocation(current.test))){const guard=current;return crossed.every(fn=>runsOnlyInsideGuard(fn,guard,sourceCode))}current=current.parent}return false}exports.noClickjacking=(0,eslint_devkit_1.createRule)({name:"no-clickjacking",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-helmet"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-clickjacking.md",description:"Detects clickjacking vulnerabilities and missing frame protections",cwe:"CWE-1021"},messages:{missingFrameBusting:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Frame Busting",cwe:"CWE-1021",description:"No frame-busting code to prevent clickjacking",severity:"HIGH",fix:"Add frame-busting JavaScript to prevent framing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"}),unsafeIframeUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe iframe Usage",cwe:"CWE-1021",description:"iframe may enable clickjacking attacks",severity:"MEDIUM",fix:"Add X-Frame-Options or CSP frame-ancestors protection",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"}),transparentFrameOverlay:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Transparent Frame Overlay",cwe:"CWE-1021",description:"Transparent elements may hide clickjacking attacks",severity:"MEDIUM",fix:"Use frame-busting or CSP protections",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"}),frameManipulation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Frame Manipulation",cwe:"CWE-1021",description:"Code attempts to manipulate parent frames",severity:"LOW",fix:"Implement proper frame communication or prevent framing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html"})},schema:[{type:"object",properties:{trustedSources:{type:"array",items:{type:"string"},default:["self","same-origin"],description:"Frame-ancestor sources treated as safe"},requireFrameBusting:{type:"boolean",default:true,description:"Require frame-busting code in addition to headers"},detectTransparentOverlays:{type:"boolean",default:true,description:"Report transparent overlays positioned over clickable elements"},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:[{trustedSources:["self","same-origin"],requireFrameBusting:true,detectTransparentOverlays:true,trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{trustedSources=["self","same-origin"],requireFrameBusting=true,detectTransparentOverlays=true,trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedAnnotations,trustedOrmPatterns:[],strictMode});let hasFrameBusting=false;let buildsDocumentShell=false;let hasDeclaredFrameProtection=false;const DOCUMENT_SHELL_TAGS=new Set(["html","head","body"]);const declaresFrameProtection=value=>{const text=value.toLowerCase();const ancestors=/frame-ancestors\s+([^;]+)/.exec(text);if(ancestors&&ancestors[1].trim()!=="*")return true;return/^\s*(deny|sameorigin)\s*$/.test(text)||text.includes("x-frame-options")};const isTrustedSource=source=>trustedSources.some(trusted=>{if(trusted===source)return true;if(trusted==="self"||trusted==="same-origin"){return source.startsWith("/")&&!source.startsWith("//")}const trustedOrigin=originOf(trusted);return trustedOrigin!==null&&trustedOrigin===originOf(source)});const isFrameBustingCode=node=>isFrameBustingTest(node.test)||readsFrameLocation(node.test);const hasTransparentStyles=styleText=>{const declarations=cssDeclarations(styleText);if(!looksLikeCss(declarations))return false;if(hasDeclaration(declarations,"display",v=>v==="none")){return false}return hasDeclaration(declarations,"opacity",v=>/^0(?:\.0+)?%?$/.test(v))&&!animatesProperty(declarations,"opacity")||hasDeclaration(declarations,"visibility",v=>v==="hidden")&&!animatesProperty(declarations,"visibility")||hasDeclaration(declarations,"z-index",v=>/^-\d+$/.test(v))};return{IfStatement(node){if(isFrameBustingCode(node)){hasFrameBusting=true}},JSXElement(node){if(node.openingElement.name.type==="JSXIdentifier"){const tag=node.openingElement.name.name;if(DOCUMENT_SHELL_TAGS.has(tag)){buildsDocumentShell=true}}if(node.openingElement.name.type==="JSXIdentifier"&&node.openingElement.name.name==="iframe"){const attributes=node.openingElement.attributes;let hasSrc=false;let srcValue="";for(const attr of attributes){if(attr.type==="JSXAttribute"&&attr.name.type==="JSXIdentifier"&&attr.name.name==="src"&&attr.value){hasSrc=true;if(attr.value.type==="Literal"&&typeof attr.value.value==="string"){srcValue=attr.value.value}else if(attr.value.type==="JSXExpressionContainer"){srcValue=foldToString(attr.value.expression,sourceCode,0)??""}}}if(hasSrc&&srcValue&&!isTrustedSource(srcValue)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.openingElement,messageId:"unsafeIframeUsage",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},MemberExpression(node){if(isFrameRef(node.object)&&!(node.object.type==="Identifier"&&node.object.name==="self")){if((0,eslint_devkit_1.propertyName)(node)==="location"||(0,eslint_devkit_1.propertyName)(node)==="top"){let current=node;let isFrameManipulation=false;while(current){if(current.type==="AssignmentExpression"&¤t.left===node){isFrameManipulation=true;break}if(current.type==="BinaryExpression"&&(current.left===node||current.right===node)){const operator=current.operator;if(operator==="!="||operator==="!=="||operator==="=="||operator==="==="){break}isFrameManipulation=true;break}current=current.parent}if(isFrameManipulation){if(safetyChecker.isSafe(node,context)){return}if(insideFrameBustingGuard(node,sourceCode)){return}context.report({node,messageId:"frameManipulation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},Literal(node){if(typeof node.value==="string"&&declaresFrameProtection(node.value)){hasDeclaredFrameProtection=true}if(typeof node.value==="string"&&detectTransparentOverlays){const text=node.value.toLowerCase();if(hasTransparentStyles(text)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"transparentFrameOverlay",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},TemplateLiteral(node){if(node.quasis.some(q=>declaresFrameProtection(q.value.raw))){hasDeclaredFrameProtection=true}if(detectTransparentOverlays){const text=node.quasis.map(q=>q.value.raw).join(" ").toLowerCase();if(hasTransparentStyles(text)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"transparentFrameOverlay",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},"Program:exit"(){if(requireFrameBusting&&buildsDocumentShell&&!hasFrameBusting&&!hasDeclaredFrameProtection){context.report({node:context.sourceCode.ast,messageId:"missingFrameBusting",data:{filePath:filename,line:"1"}})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noClientSideAuthLogic=exports.DEFAULT_CREDENTIAL_PROPERTIES=exports.DEFAULT_AUTH_KEYWORDS=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const global_object_1=require("../../utils/global-object");const resolve_binding_1=require("../../utils/resolve-binding");function isFlagComparand(node){if(node.type==="Literal"){return typeof node.value==="boolean"||node.value===null}return node.type==="Identifier"&&node.name==="undefined"}exports.DEFAULT_AUTH_KEYWORDS=["admin","authenticated","authorized","isAdmin","isAuthenticated","role"];exports.DEFAULT_CREDENTIAL_PROPERTIES=["password","secret","token"];exports.noClientSideAuthLogic=(0,eslint_devkit_1.createRule)({name:"no-client-side-auth-logic",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-client-side-auth-logic.md",description:"Prevent authentication logic in client code",cwe:"CWE-602",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Client-Side Auth Logic",cwe:"CWE-602",description:"Authentication logic in client code - easily bypassed",severity:"CRITICAL",fix:"Move authentication checks to the server",documentationLink:"https://cwe.mitre.org/data/definitions/602.html"})},schema:[{type:"object",properties:{authKeywords:{type:"array",items:{type:"string"},default:[...exports.DEFAULT_AUTH_KEYWORDS],description:"Storage keys indicating a client-side authorization decision, matched whole-word against the key segments."},credentialProperties:{type:"array",items:{type:"string"},default:[...exports.DEFAULT_CREDENTIAL_PROPERTIES],description:"Property names treated as credentials in an equality comparison."}},additionalProperties:false}]},defaultOptions:[{authKeywords:[...exports.DEFAULT_AUTH_KEYWORDS],credentialProperties:[...exports.DEFAULT_CREDENTIAL_PROPERTIES]}],create(context,[options={}]){function report(node){context.report({node,messageId:"violationDetected"})}const{authKeywords=[...exports.DEFAULT_AUTH_KEYWORDS],credentialProperties=[...exports.DEFAULT_CREDENTIAL_PROPERTIES]}=options;const{sourceCode}=context;const STORAGES=new Set(["localStorage","sessionStorage"]);function isAuthStorageRead(node){if(node.type!=="CallExpression")return false;const callee=node.callee;if(callee.type!=="MemberExpression"||
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noClientSideAuthLogic=exports.DEFAULT_CREDENTIAL_PROPERTIES=exports.DEFAULT_AUTH_KEYWORDS=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const global_object_1=require("../../utils/global-object");const resolve_binding_1=require("../../utils/resolve-binding");function isFlagComparand(node){if(node.type==="Literal"){return typeof node.value==="boolean"||node.value===null}return node.type==="Identifier"&&node.name==="undefined"}exports.DEFAULT_AUTH_KEYWORDS=["admin","authenticated","authorized","isAdmin","isAuthenticated","role"];exports.DEFAULT_CREDENTIAL_PROPERTIES=["password","secret","token"];exports.noClientSideAuthLogic=(0,eslint_devkit_1.createRule)({name:"no-client-side-auth-logic",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-client-side-auth-logic.md",description:"Prevent authentication logic in client code",cwe:"CWE-602",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Client-Side Auth Logic",cwe:"CWE-602",description:"Authentication logic in client code - easily bypassed",severity:"CRITICAL",fix:"Move authentication checks to the server",documentationLink:"https://cwe.mitre.org/data/definitions/602.html"})},schema:[{type:"object",properties:{authKeywords:{type:"array",items:{type:"string"},default:[...exports.DEFAULT_AUTH_KEYWORDS],description:"Storage keys indicating a client-side authorization decision, matched whole-word against the key segments."},credentialProperties:{type:"array",items:{type:"string"},default:[...exports.DEFAULT_CREDENTIAL_PROPERTIES],description:"Property names treated as credentials in an equality comparison."}},additionalProperties:false}]},defaultOptions:[{authKeywords:[...exports.DEFAULT_AUTH_KEYWORDS],credentialProperties:[...exports.DEFAULT_CREDENTIAL_PROPERTIES]}],create(context,[options={}]){function report(node){context.report({node,messageId:"violationDetected"})}const{authKeywords=[...exports.DEFAULT_AUTH_KEYWORDS],credentialProperties=[...exports.DEFAULT_CREDENTIAL_PROPERTIES]}=options;const{sourceCode}=context;const STORAGES=new Set(["localStorage","sessionStorage"]);function isAuthStorageRead(node){if(node.type!=="CallExpression")return false;const callee=node.callee;if(callee.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(callee)!=="getItem"||!(0,global_object_1.isGlobalObject)(callee.object,STORAGES)){return false}const keyArg=node.arguments[0];if(keyArg===void 0||keyArg.type==="SpreadElement")return false;const key=(0,resolve_binding_1.resolveStringKey)(keyArg,sourceCode);if(key===null)return false;return(0,eslint_devkit_1.nameHasAnyWord)(key,authKeywords)}function testReadsAuthStorage(node,depth=0){if(depth>6)return false;if(isAuthStorageRead(node))return true;switch(node.type){case"UnaryExpression":return testReadsAuthStorage(node.argument,depth+1);case"BinaryExpression":case"LogicalExpression":return testReadsAuthStorage(node.left,depth+1)||testReadsAuthStorage(node.right,depth+1);case"Identifier":{const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&testReadsAuthStorage(init,depth+1)}default:return false}}function isCredentialComparison(test){if(test.type!=="BinaryExpression")return false;const isCredentialRead=expr=>expr.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(expr),credentialProperties);const left=test.left;const right=test.right;const leftIsCredential=isCredentialRead(left);if(!leftIsCredential&&!isCredentialRead(right))return false;return!isFlagComparand(leftIsCredential?right:left)}function checkBranch(node,test){if(testReadsAuthStorage(test)||isCredentialComparison(test)){report(node)}}return{IfStatement(node){checkBranch(node,node.test)},ConditionalExpression(node){checkBranch(node,node.test)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDisabledCertificateValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NON_ERROR_UNARY="void";function isDefinitelyNotError(node){if(node.type==="Literal")return true;if(node.type==="Identifier")return node.name==="undefined";if(node.type==="UnaryExpression")return node.operator===NON_ERROR_UNARY;return false}exports.noDisabledCertificateValidation=(0,eslint_devkit_1.createRule)({name:"no-disabled-certificate-validation",skipTestFiles:true,meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-disabled-certificate-validation.md",description:"Prevent disabled SSL/TLS certificate validation",cwe:"CWE-295",cvss:7.4},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Disabled Certificate Validation",cwe:"CWE-295",description:"SSL/TLS certificate validation is disabled - man-in-the-middle attack possible",severity:"CRITICAL",fix:"Remove rejectUnauthorized: false or verify: false, fix certificate issues properly",documentationLink:"https://cwe.mitre.org/data/definitions/295.html"}),noopHostnameVerification:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hostname verification stubbed out",cwe:"CWE-295",description:"checkServerIdentity can never return an Error, so a certificate validly issued for ANY domain is accepted for this host \u2014 the exact MITM that hostname verification prevents.",severity:"CRITICAL",fix:"Delete the override, or delegate: const err = tls.checkServerIdentity(host, cert); if (err) return err;",documentationLink:"https://cwe.mitre.org/data/definitions/295.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}const dangerousProperties=new Set(["rejectUnauthorized","strictSSL","verify"]);const identityChecks=[];return{Property(node){if(node.key.type==="Identifier"&&dangerousProperties.has(node.key.name)&&node.value.type==="Literal"&&node.value.value===false){report(node)}if(node.key.type!=="Identifier"||node.key.name!=="checkServerIdentity"){return}const implementation=node.value;if(implementation.type!=="FunctionExpression"&&implementation.type!=="ArrowFunctionExpression"){return}if(implementation.type==="ArrowFunctionExpression"&&implementation.body.type!=="BlockStatement"){if(isDefinitelyNotError(implementation.body)){context.report({node,messageId:"noopHostnameVerification"})}return}identityChecks.push({property:node,canReportMismatch:false})},"Property:exit"(node){const open=identityChecks[identityChecks.length-1];if(open===void 0||open.property!==node)return;identityChecks.pop();if(!open.canReportMismatch){context.report({node,messageId:"noopHostnameVerification"})}},ReturnStatement(node){const open=identityChecks[identityChecks.length-1];if(open===void 0)return;if(node.argument!==null&&!isDefinitelyNotError(node.argument)){open.canReportMismatch=true}},ThrowStatement(){const open=identityChecks[identityChecks.length-1];if(open!==void 0){open.canReportMismatch=true}},AssignmentExpression(node){if(node.left.type==="MemberExpression"&&node.left.object.type==="MemberExpression"&&node.left.object.object.type==="Identifier"&&node.left.object.object.name==="process"&&
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDisabledCertificateValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NON_ERROR_UNARY="void";function isDefinitelyNotError(node){if(node.type==="Literal")return true;if(node.type==="Identifier")return node.name==="undefined";if(node.type==="UnaryExpression")return node.operator===NON_ERROR_UNARY;return false}exports.noDisabledCertificateValidation=(0,eslint_devkit_1.createRule)({name:"no-disabled-certificate-validation",skipTestFiles:true,meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-disabled-certificate-validation.md",description:"Prevent disabled SSL/TLS certificate validation",cwe:"CWE-295",cvss:7.4},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Disabled Certificate Validation",cwe:"CWE-295",description:"SSL/TLS certificate validation is disabled - man-in-the-middle attack possible",severity:"CRITICAL",fix:"Remove rejectUnauthorized: false or verify: false, fix certificate issues properly",documentationLink:"https://cwe.mitre.org/data/definitions/295.html"}),noopHostnameVerification:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hostname verification stubbed out",cwe:"CWE-295",description:"checkServerIdentity can never return an Error, so a certificate validly issued for ANY domain is accepted for this host \u2014 the exact MITM that hostname verification prevents.",severity:"CRITICAL",fix:"Delete the override, or delegate: const err = tls.checkServerIdentity(host, cert); if (err) return err;",documentationLink:"https://cwe.mitre.org/data/definitions/295.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}const dangerousProperties=new Set(["rejectUnauthorized","strictSSL","verify"]);const identityChecks=[];return{Property(node){if(node.key.type==="Identifier"&&dangerousProperties.has(node.key.name)&&node.value.type==="Literal"&&node.value.value===false){report(node)}if(node.key.type!=="Identifier"||node.key.name!=="checkServerIdentity"){return}const implementation=node.value;if(implementation.type!=="FunctionExpression"&&implementation.type!=="ArrowFunctionExpression"){return}if(implementation.type==="ArrowFunctionExpression"&&implementation.body.type!=="BlockStatement"){if(isDefinitelyNotError(implementation.body)){context.report({node,messageId:"noopHostnameVerification"})}return}identityChecks.push({property:node,canReportMismatch:false})},"Property:exit"(node){const open=identityChecks[identityChecks.length-1];if(open===void 0||open.property!==node)return;identityChecks.pop();if(!open.canReportMismatch){context.report({node,messageId:"noopHostnameVerification"})}},ReturnStatement(node){const open=identityChecks[identityChecks.length-1];if(open===void 0)return;if(node.argument!==null&&!isDefinitelyNotError(node.argument)){open.canReportMismatch=true}},ThrowStatement(){const open=identityChecks[identityChecks.length-1];if(open!==void 0){open.canReportMismatch=true}},AssignmentExpression(node){if(node.left.type==="MemberExpression"&&node.left.object.type==="MemberExpression"&&node.left.object.object.type==="Identifier"&&node.left.object.object.name==="process"&&(0,eslint_devkit_1.propertyName)(node.left.object)==="env"&&(0,eslint_devkit_1.propertyName)(node.left)==="NODE_TLS_REJECT_UNAUTHORIZED"){if(node.right.type==="Literal"&&node.right.value==="0"){report(node)}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicServiceWorkerUrl=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const GLOBAL_RECEIVERS=new Set(["window","self","globalThis"]);function isNavigator(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="navigator";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicServiceWorkerUrl=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const GLOBAL_RECEIVERS=new Set(["window","self","globalThis"]);function isNavigator(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="navigator";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&GLOBAL_RECEIVERS.has(node.object.name)&&(0,eslint_devkit_1.propertyName)(node)==="navigator"}function isServiceWorkerContainer(node,sourceCode){if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node)==="serviceWorker"){return isNavigator(node.object)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return containerFromBinding(node,sourceCode)}return false}function containerFromBinding(node,sourceCode){for(let scope=sourceCode.getScope(node);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(variable===void 0)continue;if(variable.defs.length!==1)return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const def=variable.defs[0];if(def.type!=="Variable")return false;const declarator=def.node;if(declarator.init==null)return false;if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isServiceWorkerContainer(declarator.init,sourceCode)}if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){const picked=declarator.id.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name==="serviceWorker"&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===node.name);return picked&&isNavigator(declarator.init)}return false}return false}function isStaticUrlConstruction(node,scope){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression)return false;if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.name!=="URL"){return false}const[pathArg,baseArg]=node.arguments;if(pathArg===void 0)return false;if(!(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope}))return false;if(baseArg===void 0)return true;if(baseArg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(baseArg)==="url"&&baseArg.object.type===eslint_devkit_1.AST_NODE_TYPES.MetaProperty){return true}return(0,eslint_devkit_1.isStaticExpression)({node:baseArg,scope})}exports.noDynamicServiceWorkerUrl=(0,eslint_devkit_1.createRule)({name:"no-dynamic-service-worker-url",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-dynamic-service-worker-url.md",description:"Disallow dynamic URLs in service worker registration",cwe:"CWE-829",cvss:8.1},messages:{dynamicSwUrl:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic Service Worker URL",cwe:"CWE-829",owasp:"A08:2021",cvss:8.1,description:"Using dynamic URL for service worker registration. A compromised URL could give attacker persistent control over the page.",severity:"HIGH",fix:"Use a static, hardcoded path for service worker registration.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||(0,eslint_devkit_1.propertyName)(node.callee)!=="register"){return}if(!isServiceWorkerContainer(node.callee.object,context.sourceCode)){return}const urlArg=node.arguments[0];if(!urlArg)return;const scope=context.sourceCode.getScope(node);if((0,eslint_devkit_1.isStaticExpression)({node:urlArg,scope}))return;if(isStaticUrlConstruction(urlArg,scope))return;context.report({node,messageId:"dynamicSwUrl"})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFilereaderInnerhtml=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DANGEROUS_PROPERTIES=new Set(["innerHTML","outerHTML"]);const DANGEROUS_METHODS=new Set(["insertAdjacentHTML","write","writeln"]);function readsFileReaderResult(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFilereaderInnerhtml=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DANGEROUS_PROPERTIES=new Set(["innerHTML","outerHTML"]);const DANGEROUS_METHODS=new Set(["insertAdjacentHTML","write","writeln"]);function readsFileReaderResult(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_1.propertyName)(current)==="result"){const owner=current.object;if(owner.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;return owner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(owner)==="target"&&owner.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier}current=current.object}return false}exports.noFilereaderInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-filereader-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-filereader-innerhtml.md",description:"Disallow using innerHTML or similar methods with FileReader data",cwe:"CWE-79",cvss:8.1},messages:{unsafeInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via File Upload",cwe:"CWE-79",owasp:"A03:2021",cvss:8.1,description:"Using {{method}} with FileReader result enables XSS attacks. Malicious files can contain scripts that execute when rendered.",severity:"HIGH",fix:"Sanitize file content with DOMPurify before rendering, or use textContent for plain text.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/FileReader"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.left),DANGEROUS_PROPERTIES)){if(payloadSource(node.right)==="filereader"&&readsFileReaderResult(node.right)){context.report({node,messageId:"unsafeInnerhtml",data:{method:(0,eslint_devkit_1.propertyName)(node.left)}})}}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),DANGEROUS_METHODS)){for(const arg of node.arguments){if(payloadSource(arg)==="filereader"&&readsFileReaderResult(arg)){context.report({node,messageId:"unsafeInnerhtml",data:{method:(0,eslint_devkit_1.propertyName)(node.callee)}});break}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noIncompleteUrlSanitization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const url_taint_1=require("../../utils/url-taint");const HOST_TLDS=new Set(["com","net","org","io","dev","co","app","ai","edu","gov","mil","info","biz","me","us","uk","ca","de","fr","jp","cn","au","eu","xyz","cloud","tv","online","site","store","link","tech","local"]);function isHostLikeLiteral(raw){let value=raw.trim().toLowerCase();value=value.replace(/^https?:/,"");value=value.replace(/^\/\//,"");value=value.replace(/^\./,"");const withoutPort=value.replace(/:\d{1,5}$/,"");if(/[/?#@\s:]/.test(withoutPort))return false;const labels=withoutPort.split(".");if(labels.length<2)return false;if(!labels.every(label=>/^[a-z0-9-]+$/.test(label)))return false;return HOST_TLDS.has(labels[labels.length-1])}const PASSTHROUGH_METHODS=new Set(["trim","trimStart","trimEnd","toLowerCase","toUpperCase","toString","normalize","valueOf"]);const DEFAULT_URL_NAME_WORDS=["url","uri","href","host","origin","domain","referer","referrer","endpoint","link"];function receiverName(node){if(node.type===
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noIncompleteUrlSanitization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const url_taint_1=require("../../utils/url-taint");const HOST_TLDS=new Set(["com","net","org","io","dev","co","app","ai","edu","gov","mil","info","biz","me","us","uk","ca","de","fr","jp","cn","au","eu","xyz","cloud","tv","online","site","store","link","tech","local"]);function isHostLikeLiteral(raw){let value=raw.trim().toLowerCase();value=value.replace(/^https?:/,"");value=value.replace(/^\/\//,"");value=value.replace(/^\./,"");const withoutPort=value.replace(/:\d{1,5}$/,"");if(/[/?#@\s:]/.test(withoutPort))return false;const labels=withoutPort.split(".");if(labels.length<2)return false;if(!labels.every(label=>/^[a-z0-9-]+$/.test(label)))return false;return HOST_TLDS.has(labels[labels.length-1])}const PASSTHROUGH_METHODS=new Set(["trim","trimStart","trimEnd","toLowerCase","toUpperCase","toString","normalize","valueOf"]);const DEFAULT_URL_NAME_WORDS=["url","uri","href","host","origin","domain","referer","referrer","endpoint","link"];function receiverName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){return null}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const passthrough=(0,eslint_devkit_1.propertyName)(callee);if(passthrough!==null&&PASSTHROUGH_METHODS.has(passthrough)){return receiverName(callee.object)}}if(callee.type==="Identifier"&&callee.name==="String"&&node.arguments.length>0){return receiverName(node.arguments[0])}return null}function isUrlBearingReceiver(node,sourceCode,urlNameTest){const name=receiverName(node);if(name!==null&&urlNameTest(name))return true;return(0,url_taint_1.isAttackerSteerableUrl)(node,sourceCode)}function literalNumber(node){if(node.type==="Literal"&&typeof node.value==="number"){return node.value}if(node.type==="UnaryExpression"&&node.operator==="-"&&node.argument.type==="Literal"&&typeof node.argument.value==="number"){return-node.argument.value}return null}const FLIPPED={">":"<","<":">",">=":"<=","<=":">="};function isContainmentComparison(call){const parent=call.parent;if(parent.type!=="BinaryExpression")return false;const callIsLeft=parent.left===call;const bound=literalNumber(callIsLeft?parent.right:parent.left);if(bound===null)return false;const operator=callIsLeft?parent.operator:FLIPPED[parent.operator]??parent.operator;if((operator==="!=="||operator==="!=")&&bound===-1)return true;if(operator===">"&&bound===-1)return true;return operator===">="&&bound===0}function isGuardPosition(node){const parent=node.parent;switch(parent.type){case"IfStatement":case"WhileStatement":case"DoWhileStatement":case"LogicalExpression":case"ReturnStatement":case"VariableDeclarator":case"ArrowFunctionExpression":return true;case"ConditionalExpression":case"ForStatement":return parent.test===node;case"UnaryExpression":return parent.operator==="!";default:return false}}const SCRIPTABLE_SCHEMES=["javascript:","data:","vbscript:"];function schemeOf(text){const value=text.trim().toLowerCase();return SCRIPTABLE_SCHEMES.find(scheme=>value.startsWith(scheme))??null}function schemeOfPattern(pattern){const value=pattern.toLowerCase().replace(/\\/g,"");return SCRIPTABLE_SCHEMES.find(scheme=>value.includes(scheme))??null}const NEEDLE_METHODS=new Set(["startsWith","endsWith","includes","indexOf","lastIndexOf","search","match"]);function enclosingScopeNode(node){let current=node;while(current.type!=="FunctionDeclaration"&¤t.type!=="FunctionExpression"&¤t.type!=="ArrowFunctionExpression"&¤t.type!=="Program"){current=current.parent}return current}exports.noIncompleteUrlSanitization=(0,eslint_devkit_1.createRule)({name:"no-incomplete-url-sanitization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-incomplete-url-sanitization.md",description:"Disallow URL substring tests and partial scheme denylists as security decisions",cwe:"CWE-020",cvss:7.5},messages:{substringHostCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"URL substring check used as a host allowlist",cwe:"CWE-020",description:'A substring test cannot decide the host of a URL \u2014 "https://evil.io/?r=trusted.com" and "https://trusted.com.evil.io/" both contain the string.',severity:"HIGH",fix:"Parse the URL and compare the host: const { hostname } = new URL(url); hostname === 'trusted.com' || hostname.endsWith('.trusted.com')",documentationLink:"https://cwe.mitre.org/data/definitions/20.html"}),incompleteSchemeDenylist:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Incomplete URL scheme denylist",cwe:"CWE-020",description:'Only "javascript:" is denied, so "data:text/html;base64,\u2026" still reaches the sink and still executes script.',severity:"HIGH",fix:"Allowlist instead of denylist: ['http:', 'https:'].includes(new URL(raw, location.origin).protocol)",documentationLink:"https://cwe.mitre.org/data/definitions/20.html"})},schema:[{type:"object",properties:{urlNameWords:{type:"array",items:{type:"string"},default:[...DEFAULT_URL_NAME_WORDS],description:"Substrings that say a value is a URL, host or origin, matched case-insensitively. Replaces the default."}},additionalProperties:false}]},defaultOptions:[],create(context){const sourceCode=context.sourceCode;const urlNameWords=(context.options[0]?.urlNameWords??DEFAULT_URL_NAME_WORDS).map(word=>word.toLowerCase());const urlNameTest=name=>{const lower=name.toLowerCase();return urlNameWords.some(word=>lower.includes(word))};const schemeTests=new Map;function collectSchemeTest(at,needle){if(!isGuardPosition(at))return;if(needle.type!=="Literal")return;const scheme=typeof needle.value==="string"?schemeOf(needle.value):"regex"in needle?schemeOfPattern(needle.regex.pattern):null;if(scheme===null)return;const scope=enclosingScopeNode(at);let entry=schemeTests.get(scope);if(entry===void 0){entry={tested:new Set,firstJavascript:null};schemeTests.set(scope,entry)}entry.tested.add(scheme);if(scheme==="javascript:"&&entry.firstJavascript===null){entry.firstJavascript=at}}function checkSubstringHostCheck(node,method,receiver){if(method!=="includes"&&method!=="indexOf"&&method!=="lastIndexOf"){return}const needle=node.arguments[0];if(node.arguments.length!==1||needle.type!=="Literal"||typeof needle.value!=="string"||!isHostLikeLiteral(needle.value)){return}if(method==="includes"){if(!isGuardPosition(node))return;if(!isUrlBearingReceiver(receiver,sourceCode,urlNameTest))return;context.report({node,messageId:"substringHostCheck"});return}if(!isContainmentComparison(node))return;const decision=node.parent;if(!isGuardPosition(decision))return;if(!isUrlBearingReceiver(receiver,sourceCode,urlNameTest))return;context.report({node:decision,messageId:"substringHostCheck"})}return{CallExpression(node){const callee=node.callee;if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(node.arguments.length>0){checkSubstringHostCheck(node,method,callee.object)}if(NEEDLE_METHODS.has(method)&&node.arguments.length>0){const at=method==="indexOf"||method==="lastIndexOf"?node.parent:node;collectSchemeTest(at,node.arguments[0])}if(method==="test"&&callee.object.type==="Literal"){collectSchemeTest(node,callee.object)}},BinaryExpression(node){if(node.operator!=="==="&&node.operator!=="!==")return;const literal=node.left.type==="Literal"?node.left:node.right;collectSchemeTest(node,literal)},"Program:exit"(){for(const entry of schemeTests.values()){if(entry.firstJavascript===null)continue;if(entry.tested.has("data:"))continue;context.report({node:entry.firstJavascript,messageId:"incompleteSchemeDenylist"})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureRedirects=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const navigation_targets_1=require("../../utils/navigation-targets");const regexp_anchoring_1=require("../../utils/regexp-anchoring");function isNavigationSink(node){const callee=node.callee;if(callee.type==="MemberExpression"
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureRedirects=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const navigation_targets_1=require("../../utils/navigation-targets");const regexp_anchoring_1=require("../../utils/regexp-anchoring");function isNavigationSink(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="redirect"){return true}return(0,navigation_targets_1.isLocationNavigationCall)(node)}function provesSafeDestination(test,sourceCode){return(0,regexp_anchoring_1.isAnchoredHostGuard)(test,sourceCode)||(0,navigation_targets_1.isRelativePathGuard)(test,sourceCode)||(0,navigation_targets_1.isOriginEqualityGuard)(test,sourceCode)}function isSelfReload(target,sinkLocation,sourceCode){if(!target||target.type!=="MemberExpression")return false;if((0,eslint_devkit_1.propertyName)(target)!=="href")return false;const normalise=n=>sourceCode.getText(n).replace(/\s+/g,"");return normalise(target.object)===normalise(sinkLocation)}function isRedirectValidated(node,target,sourceCode){const hasUserInput=target!==void 0&&(0,navigation_targets_1.isSteerableUrlValue)(target,sourceCode);if(!hasUserInput){return true}if(target.type==="ConditionalExpression"&&provesSafeDestination(target.test,sourceCode)){return true}if(!node.loc?.start||!node.loc?.end){return false}return(0,navigation_targets_1.isGuardedDestination)(node,target,sourceCode,test=>provesSafeDestination(test,sourceCode))}exports.noInsecureRedirects=(0,eslint_devkit_2.createRule)({name:"no-insecure-redirects",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-insecure-redirects.md",description:"Detects open redirect vulnerabilities",cwe:"CWE-601",cvss:6.1},messages:{insecureRedirect:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Open redirect",cwe:"CWE-601",description:"Unvalidated redirect detected - user-controlled URL",severity:"HIGH",fix:"Whitelist allowed domains or validate redirect target",documentationLink:"https://owasp.org/www-community/vulnerabilities/Unvalidated_Redirects_and_Forwards"})},schema:[{type:"object",properties:{ignoreInTests:{type:"boolean",default:true},allowedDomains:{type:"array",items:{type:"string"},default:[],description:"Redirect target domains treated as safe"}},additionalProperties:false}]},defaultOptions:[{ignoreInTests:true,allowedDomains:[]}],create(context,[options={}]){const{ignoreInTests=true}=options||{};const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;function checkCallExpression(node){if(!isNavigationSink(node)){return}if(node.callee.type==="MemberExpression"&&isSelfReload(node.arguments[0],node.callee.object,sourceCode)){return}if(!isRedirectValidated(node,node.arguments[0],sourceCode)){context.report({node,messageId:"insecureRedirect"})}}function checkAssignmentExpression(node){if(!(0,navigation_targets_1.isLocationNavigationWrite)(node.left)){return}if(node.left.type==="MemberExpression"&&isSelfReload(node.right,node.left.object,sourceCode)){return}if(!isRedirectValidated(node,node.right,sourceCode)){context.report({node,messageId:"insecureRedirect"})}}return{CallExpression:checkCallExpression,AssignmentExpression:checkAssignmentExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCorsCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function describePermissiveOrigin(value){if(value==="*"){return"Wildcard CORS origin (*) allows all origins"}if(value===true){return'origin: true reflects the request Origin header, allowing every origin \u2014 and unlike "*" it still works with credentials'}return null}function matchesIgnorePattern(text,ignorePatterns){return ignorePatterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}exports.noMissingCorsCheck=(0,eslint_devkit_2.createRule)({name:"no-missing-cors-check",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/no-permissive-cors"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-cors-check.md",description:"Detects missing CORS validation (wildcard CORS, missing origin check)",cwe:"CWE-346",cvss:7.5},messages:{missingCorsCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CORS Validation",cwe:"CWE-346",description:"Missing CORS validation detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/346.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CORS checks in test files"},trustedLibraries:{type:"array",items:{type:"string"},default:[],description:"Custom CORS libraries to trust (wildcard origins in these libraries will not be reported)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,trustedLibraries:[],ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,trustedLibraries:corsTrustedLibraries=[],ignorePatterns=[]}=options;const trustedLibraries=corsTrustedLibraries;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;function checkLiteral(node){if(isTestFile){return}if(node.value==="*"&&typeof node.value==="string"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}let shouldSkip=false;let current=node;while(current&¤t.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCorsCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function describePermissiveOrigin(value){if(value==="*"){return"Wildcard CORS origin (*) allows all origins"}if(value===true){return'origin: true reflects the request Origin header, allowing every origin \u2014 and unlike "*" it still works with credentials'}return null}function matchesIgnorePattern(text,ignorePatterns){return ignorePatterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}exports.noMissingCorsCheck=(0,eslint_devkit_2.createRule)({name:"no-missing-cors-check",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/no-permissive-cors"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-cors-check.md",description:"Detects missing CORS validation (wildcard CORS, missing origin check)",cwe:"CWE-346",cvss:7.5},messages:{missingCorsCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CORS Validation",cwe:"CWE-346",description:"Missing CORS validation detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/346.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CORS checks in test files"},trustedLibraries:{type:"array",items:{type:"string"},default:[],description:"Custom CORS libraries to trust (wildcard origins in these libraries will not be reported)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,trustedLibraries:[],ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,trustedLibraries:corsTrustedLibraries=[],ignorePatterns=[]}=options;const trustedLibraries=corsTrustedLibraries;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;const CALLS_USE=/(?:\.\s*use|\[\s*['"]use['"]\s*\])\s*\(/i;const CALLS_USE_OR_CORS=/(?:\.\s*use|\[\s*['"]use['"]\s*\]|\bcors)\s*\(/i;const CALLS_HEADER_SETTER=/(?:\.\s*(?:setHeader|header)|\[\s*['"](?:setHeader|header)['"]\s*\])\s*\(/i;function checkLiteral(node){if(isTestFile){return}if(node.value==="*"&&typeof node.value==="string"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}let shouldSkip=false;let current=node;while(current&¤t.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(CALLS_HEADER_SETTER.test(callText)&&/\bAccess-Control-Allow-Origin\b/i.test(callText)){shouldSkip=true;break}if(CALLS_USE.test(callText)&&/\bcors\s*\(/i.test(callText)){if(node.parent&&node.parent.type==="Property"){const prop=node.parent;if((0,eslint_devkit_1.objectKeyName)(prop)==="origin"){shouldSkip=true;break}}}}}if(shouldSkip){return}let isActualCorsContext=false;current=node;while(current&¤t.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(CALLS_USE_OR_CORS.test(callText)&&/\bcors\s*\(/i.test(callText)){isActualCorsContext=true;break}}}if(node.parent&&node.parent.type==="Property"){const prop=node.parent;const key=(0,eslint_devkit_1.objectKeyName)(prop);if(key!==null){const keyName=key.toLowerCase();if(keyName==="origin"||keyName==="allowedorigins"){let inCorsCall=false;let checkNode=prop;while(checkNode&&checkNode.parent){checkNode=checkNode.parent;if(checkNode.type==="CallExpression"){const callText=sourceCode.getText(checkNode);if(/\bcors\s*\(/i.test(callText)||CALLS_USE.test(callText)&&/\bcors/i.test(callText)){inCorsCall=true;break}}}if(inCorsCall){context.report({node,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'}});return}}}}if(isActualCorsContext){context.report({node,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'}})}}}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node.callee)==="use"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}const firstArg=node.arguments.length>0?node.arguments[0]:null;let isCorsCall=/\bcors\s*\(/i.test(text);if(!isCorsCall&&firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"){const callee=firstArg.callee;const calleeName=callee.name.toLowerCase();isCorsCall=calleeName==="cors"||trustedLibraries.some(lib=>{return calleeName.includes(lib.toLowerCase())})}let isTrustedLibrary=false;if(firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"){const calleeName=firstArg.callee.name.toLowerCase();isTrustedLibrary=trustedLibraries.some(lib=>calleeName.includes(lib.toLowerCase()))}if(isTrustedLibrary){return}if(/\bcors\s*\(/i.test(text)||isCorsCall){const corsCallArg=firstArg&&firstArg.type==="CallExpression"?firstArg:null;const argsToCheck=corsCallArg?corsCallArg.arguments:node.arguments;for(const arg of argsToCheck){if(arg.type==="ObjectExpression"){for(const prop of arg.properties){if(prop.type==="Property"&&(0,eslint_devkit_1.objectKeyName)(prop)==="origin"&&prop.value.type==="Literal"){const issue=describePermissiveOrigin(prop.value.value);if(issue!==null){context.report({node:prop.value,messageId:"missingCorsCheck",data:{issue,safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'}})}}}}else if(arg.type==="Identifier"){const varName=arg.name;let current=node;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName&&declarator.init){if(declarator.init.type==="ObjectExpression"){for(const prop of declarator.init.properties){if(prop.type==="Property"&&(0,eslint_devkit_1.objectKeyName)(prop)==="origin"&&prop.value.type==="Literal"){const issue=describePermissiveOrigin(prop.value.value);if(issue!==null){context.report({node:arg,messageId:"missingCorsCheck",data:{issue,safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'}});return}}}}}}}}break}if(current.parent){current=current.parent}else{break}}}}}}}}function checkMemberExpression(node){if(isTestFile){return}const headerMethod=(0,eslint_devkit_1.propertyName)(node);if(headerMethod!==null){if(headerMethod==="setHeader"||headerMethod==="header"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}const parent=node.parent;if(parent&&parent.type==="CallExpression"){const callText=sourceCode.getText(parent);if(/\bAccess-Control-Allow-Origin\b/i.test(callText)){const args=parent.arguments;if(args.length>=2&&args[1].type==="Literal"&&args[1].value==="*"){context.report({node:args[1],messageId:"missingCorsCheck",data:{issue:"Wildcard CORS header allows all origins",safeAlternative:'Validate origin before setting header: res.setHeader("Access-Control-Allow-Origin", allowedOrigins.includes(origin) ? origin : "null");'}})}}}}}}return{Literal:checkLiteral,CallExpression:checkCallExpression,MemberExpression:checkMemberExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCsrfProtection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const express_app_1=require("../../utils/express-app");const ROUTE_VERBS=new Set(["all","get","post","put","delete","patch","head","options"]);function asChainedRouteRegistration(node,scope,methods){const callee=node.callee;if(callee.type!=="MemberExpression"
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCsrfProtection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const express_app_1=require("../../utils/express-app");const ROUTE_VERBS=new Set(["all","get","post","put","delete","patch","head","options"]);function asChainedRouteRegistration(node,scope,methods){const callee=node.callee;if(callee.type!=="MemberExpression"){return null}const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(!methods.has(method.toLowerCase()))return null;let receiver=callee.object;while(receiver.type==="CallExpression"&&receiver.callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(receiver.callee),ROUTE_VERBS)){receiver=receiver.callee.object}if(receiver.type!=="CallExpression"||receiver.callee.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(receiver.callee)!=="route"){return null}if(!(0,express_app_1.isExpressAppOrRouter)(receiver,scope))return null;return node.arguments.length>0?{method,pathArg:null}:null}const DEFAULT_CSRF_MIDDLEWARE_PATTERNS=["csrf","csurf","csrfProtection","verifyCsrfToken","csrfToken","validateCsrf","checkCsrf","csrfMiddleware"];const DEFAULT_PROTECTED_METHODS=["post","put","delete","patch"];const CSRF_MODULES=["csurf","csrf","tiny-csrf","edge-csrf","csrf-csrf","@dr.pogodin/csurf"];const CSRF_NAMESPACED=[["lusca","csrf"]];function suppliesCsrfProtection(node,scope,sourceCode,names,depth=0){if(depth>3)return false;const callee=node.type==="CallExpression"?node.callee:node;for(const pkg of CSRF_MODULES){if((0,eslint_devkit_2.isModuleBinding)(callee,scope,pkg,[]))return true}for(const[pkg,member]of CSRF_NAMESPACED){if((0,eslint_devkit_2.isModuleBinding)(callee,scope,pkg,[member]))return true}if(callee.type==="Identifier"&&names.has(callee.name))return true;if(callee.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(callee,sourceCode);if(init!==void 0){return suppliesCsrfProtection(init,scope,sourceCode,names,depth+1)}}return false}function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}exports.noMissingCsrfProtection=(0,eslint_devkit_2.createRule)({name:"no-missing-csrf-protection",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-csrf-protection"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-csrf-protection.md",description:"Detects missing CSRF token validation in POST/PUT/DELETE requests",cwe:"CWE-352",cvss:8.8},hasSuggestions:true,messages:{missingCsrfProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSRF Protection",cwe:"CWE-352",description:"Missing CSRF protection detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/352.html"}),addCsrfValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add CSRF Validation",description:"Add CSRF middleware",severity:"LOW",fix:"app.use(csrf({ cookie: true }))",documentationLink:"https://github.com/expressjs/csurf"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CSRF protection in test files"},csrfMiddlewarePatterns:{type:"array",items:{type:"string"},default:[],description:"CSRF middleware patterns to recognize"},protectedMethods:{type:"array",items:{type:"string"},default:[],description:"HTTP methods that require CSRF protection"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,csrfMiddlewarePatterns:[],protectedMethods:[],ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,csrfMiddlewarePatterns,protectedMethods:customProtectedMethods,ignorePatterns=[]}=options;const csrfPatterns=csrfMiddlewarePatterns&&csrfMiddlewarePatterns.length>0?csrfMiddlewarePatterns:DEFAULT_CSRF_MIDDLEWARE_PATTERNS;const csrfNames=new Set(csrfPatterns);const protectedMethods=customProtectedMethods&&customProtectedMethods.length>0?customProtectedMethods:DEFAULT_PROTECTED_METHODS;const protectedMethodsSet=new Set(protectedMethods.map(m=>m.toLowerCase()));const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;function checkCallExpression(node){if(isTestFile){return}const callText=sourceCode.getText(node);if(matchesIgnorePattern(callText,ignorePatterns)){return}const scope=sourceCode.getScope(node);const registration=(0,express_app_1.asExpressRouteRegistration)(node,scope,protectedMethodsSet)??asChainedRouteRegistration(node,scope,protectedMethodsSet);if(registration===null){return}const methodName=registration.method;const{pathArg}=registration;let hasCsrfInChain=false;for(let i=pathArg===null?0:1;i<node.arguments.length;i++){const arg=node.arguments[i];const candidates=arg.type==="ArrayExpression"?arg.elements.filter(el=>el!==null):[arg];if(candidates.some(candidate=>suppliesCsrfProtection(candidate,scope,sourceCode,csrfNames))){hasCsrfInChain=true;break}}if(!hasCsrfInChain&&!hasGlobalCsrfMiddleware()){context.report({node,messageId:"missingCsrfProtection",data:{issue:`${methodName.toUpperCase()} route handler missing CSRF protection`,safeAlternative:`Add CSRF middleware: app.${methodName}("/path", csrf(), handler) or use app.use(csrf()) globally`},suggest:[{messageId:"addCsrfValidation",fix(fixer){return pathArg===null?fixer.insertTextBefore(node.arguments[0],"csrf(), "):fixer.insertTextAfter(pathArg,", csrf()")}}]})}}let globalCsrf;function hasGlobalCsrfMiddleware(){if(globalCsrf!==void 0)return globalCsrf;globalCsrf=false;for(const statement of sourceCode.ast.body){if(statement.type!=="ExpressionStatement")continue;const call=statement.expression;if(call.type!=="CallExpression"||call.callee.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(call.callee)!=="use"){continue}const mountScope=sourceCode.getScope(call);if(call.arguments.some(arg=>suppliesCsrfProtection(arg,mountScope,sourceCode,csrfNames))){globalCsrf=true;break}}return globalCsrf}return{CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingSecurityHeaders=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const DEFAULT_REQUIRED_HEADERS=["Content-Security-Policy","X-Frame-Options","X-Content-Type-Options"];const NON_DOCUMENT_HEADERS=new Set(["Set-Cookie","Cache-Control","Location","Content-Disposition","ETag","Last-Modified","Expires","Vary"].map(h=>h.toLowerCase()));const KNOWN_RESPONSE_HEADERS=new Set(["Content-Security-Policy","Content-Security-Policy-Report-Only","X-Frame-Options","X-Content-Type-Options","X-XSS-Protection","Strict-Transport-Security","Referrer-Policy","Permissions-Policy","Feature-Policy","Cross-Origin-Opener-Policy","Cross-Origin-Embedder-Policy","Cross-Origin-Resource-Policy","X-Permitted-Cross-Domain-Policies","X-DNS-Prefetch-Control","X-Download-Options","Origin-Agent-Cluster","Report-To","Reporting-Endpoints","Clear-Site-Data","Access-Control-Allow-Origin","Access-Control-Allow-Credentials","Access-Control-Allow-Methods","Access-Control-Allow-Headers","Access-Control-Expose-Headers","Access-Control-Max-Age","Timing-Allow-Origin","Content-Type","Content-Length","Content-Encoding","Content-Language","Content-Disposition","Content-Range","Cache-Control","Pragma","Expires","ETag","Last-Modified","Age","Vary","Location","Set-Cookie","Server","Retry-After","Link","Accept-Ranges","Transfer-Encoding","WWW-Authenticate"].map(h=>h.toLowerCase()));const UNAMBIGUOUS_HEADER_METHODS=new Set(["setHeader","header"]);const DYNAMIC_HEADER_NAME=Symbol("dynamic header name");function extractHeaderName(node,sourceCode){const arg=node.arguments[0];if(arg===void 0)return null;const folded=staticStringValue(arg,sourceCode,0);if(folded!==null)return folded;const viaParameter=parameterLiterals(arg,sourceCode);if(viaParameter.length===1)return viaParameter[0];return DYNAMIC_HEADER_NAME}function staticStringValue(node,sourceCode,depth){if(depth>4)return null;if(node.type==="Literal"){return typeof node.value==="string"?node.value:null}if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:staticStringValue(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const container=foldToArray(node.object,sourceCode,depth+1);const element=container?.elements[index.value];return element==null?null:staticStringValue(element,sourceCode,depth+1)}return null}function foldToArray(node,sourceCode,depth){if(depth>4)return null;if(node.type==="ArrayExpression")return node;if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToArray(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const outer=foldToArray(node.object,sourceCode,depth+1);const element=outer?.elements[index.value];return element==null?null:foldToArray(element,sourceCode,depth+1)}return null}function parameterLiterals(arg,sourceCode){if(arg.type!=="Identifier")return[];const variable=sourceCode.getScope(arg).references.find(ref=>ref.identifier===arg)?.resolved;const def=variable?.defs[0];if(def===void 0||def.type!=="Parameter")return[];const fn=def.node;const position=fn.params.indexOf(def.name);if(position===-1)return[];const declarator=fn.type==="FunctionDeclaration"?fn:fn.parent?.type==="VariableDeclarator"?fn.parent:void 0;if(declarator===void 0)return[];const names=new Set;for(const declared of sourceCode.getDeclaredVariables(declarator)){for(const reference of declared.references){const call=reference.identifier.parent;if(call?.type!=="CallExpression"||call.callee!==reference.identifier){continue}const passed=call.arguments[position];if(passed===void 0)return[];const value=staticStringValue(passed,sourceCode,0);if(value===null)return[];names.add(value)}}return[...names]}function isHeaderSet(node,requiredHeaders,sourceCode){if(node.callee.type!=="MemberExpression"||node.callee.computed||node.callee.property.type!=="Identifier"){return false}const method=node.callee.property.name;if(UNAMBIGUOUS_HEADER_METHODS.has(method))return true;if(method!=="set")return false;const extracted=extractHeaderName(node,sourceCode);if(extracted===null||extracted===DYNAMIC_HEADER_NAME)return false;const name=extracted.toLowerCase();return KNOWN_RESPONSE_HEADERS.has(name)||requiredHeaders.some(h=>h.toLowerCase()===name)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}const DOCUMENT_MEDIA_TYPES=new Set(["text/html","application/xhtml+xml","image/svg+xml"]);function isDocumentMediaType(contentType){const mediaType=contentType.split(";")[0].trim().toLowerCase();return DOCUMENT_MEDIA_TYPES.has(mediaType)}function checkFunctionForSecurityHeaders(node,requiredHeaders,context){const setHeaders=new Set;let scopeIsOpaque=false;let declaredContentType=null;let current=node;let scopeNode=null;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){scopeNode=current;break}current=current.parent??null}if(!scopeNode){scopeNode=context.sourceCode.ast}function collectHeaders(astNode){if(astNode.type==="CallExpression"&&isHeaderSet(astNode,requiredHeaders,context.sourceCode)){const headerName=extractHeaderName(astNode,context.sourceCode);if(headerName===DYNAMIC_HEADER_NAME){scopeIsOpaque=true}else if(headerName!==null){setHeaders.add(headerName.toLowerCase());if(headerName.toLowerCase()==="content-type"){const value=astNode.arguments[1];declaredContentType=value===void 0?null:staticStringValue(value,context.sourceCode,0)}}}for(const key of Object.keys(astNode)){if(key==="parent")continue;const child=astNode[key];if(Array.isArray(child)){for(const item of child){if(isNode(item))collectHeaders(item)}}else if(isNode(child)){collectHeaders(child)}}}collectHeaders(scopeNode);if(scopeIsOpaque){return[]}if(setHeaders.size>0&&[...setHeaders].every(h=>NON_DOCUMENT_HEADERS.has(h))){return[]}if(declaredContentType!==null&&!isDocumentMediaType(declaredContentType)){return[]}return requiredHeaders.filter(header=>!setHeaders.has(header.toLowerCase()))}function declaredResponseHeaders(property){if(property.computed)return null;const key=property.key;const keyName=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):null;if(keyName!=="headers")return null;const value=property.value;if(value.type==="ArrayExpression"){const names=[];let contentType=null;for(const element of value.elements){if(element===null||element.type!=="ObjectExpression")continue;for(const entry of element.properties){if(entry.type!=="Property"||entry.computed)continue;const entryKey=entry.key.type==="Identifier"?entry.key.name:null;if(entryKey!=="key")continue;const staticText=(0,eslint_devkit_1.staticString)(entry.value);if(staticText!==null){names.push(staticText);if(staticText.toLowerCase()==="content-type"){contentType=element.properties.find(p=>p.type==="Property"&&!p.computed&&p.key.type==="Identifier"&&p.key.name==="value")?.value??null}}}}return names.length>0?{names,contentType}:null}if(value.type!=="ObjectExpression")return null;const init=property.parent;if(init.type!=="ObjectExpression"||!isResponseInit(init))return null;return objectHeaderNames(value)}function objectHeaderNames(object){const names=[];let contentType=null;for(const entry of object.properties){if(entry.type==="SpreadElement")return null;if(entry.computed)return null;const name=(0,eslint_devkit_1.staticString)(entry.key)!==null?(0,eslint_devkit_1.staticString)(entry.key):entry.key.type==="Identifier"?entry.key.name:null;if(name===null)continue;names.push(name);if(name.toLowerCase()==="content-type")contentType=entry.value}return names.length>0?{names,contentType}:null}function writeHeadHeaders(node){if(node.callee.type!=="MemberExpression"||node.callee.computed||node.callee.property.type!=="Identifier"||node.callee.property.name!=="writeHead"){return null}const block=node.arguments.find(arg=>arg.type==="ObjectExpression");return block??null}const RESPONSE_FACTORIES=new Set(["json","next","redirect","rewrite","error"]);function isResponseInit(init){const hasResponseOnlyField=init.properties.some(p=>p.type==="Property"&&!p.computed&&p.key.type==="Identifier"&&(p.key.name==="status"||p.key.name==="statusText"));if(hasResponseOnlyField)return true;const call=init.parent;if(call.type!=="NewExpression"&&call.type!=="CallExpression"){return false}const callee=call.callee;if(callee.type==="Identifier")return callee.name==="Response";if(callee.type==="MemberExpression"&&!callee.computed&&callee.property.type==="Identifier"&&callee.object.type==="Identifier"){return RESPONSE_FACTORIES.has(callee.property.name)&&(callee.object.name==="Response"||callee.object.name==="NextResponse")}return false}exports.noMissingSecurityHeaders=(0,eslint_devkit_2.createRule)({name:"no-missing-security-headers",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-helmet"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-security-headers.md",description:"Detects missing security headers in HTTP responses",cwe:"CWE-693",cvss:7.5},messages:{missingSecurityHeader:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing security headers",cwe:"CWE-693",description:"Missing security headers: {{headers}}",severity:"HIGH",fix:"Set security headers: Content-Security-Policy, X-Frame-Options, X-Content-Type-Options",documentationLink:"https://owasp.org/www-project-secure-headers/"})},schema:[{type:"object",properties:{requiredHeaders:{type:"array",items:{type:"string"},default:DEFAULT_REQUIRED_HEADERS,description:"Security headers a response must set"},ignoreInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{requiredHeaders:DEFAULT_REQUIRED_HEADERS,ignoreInTests:true}],create(context,[options={}]){const{requiredHeaders=DEFAULT_REQUIRED_HEADERS,ignoreInTests=true}=options||{};const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const reportedScopes=new Set;function getScopeKey(node){let current=node;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return`${current.range?.[0]}-${current.range?.[1]}`}current=current.parent??null}return"program"}function checkCallExpression(node){if(!isHeaderSet(node,requiredHeaders,context.sourceCode)){return}const scopeKey=getScopeKey(node);if(reportedScopes.has(scopeKey)){return}const missing=checkFunctionForSecurityHeaders(node,requiredHeaders,context);reportedScopes.add(scopeKey);if(missing.length>0){context.report({node,messageId:"missingSecurityHeader",data:{headers:missing.join(", ")}})}}function reportDeclaredBlock(node,block){const contentType=block.contentType===null?null:staticStringValue(block.contentType,context.sourceCode,0);const present=new Set(block.names.map(h=>h.toLowerCase()));if([...present].every(h=>NON_DOCUMENT_HEADERS.has(h)))return;if(contentType!==null&&!isDocumentMediaType(contentType))return;const missing=requiredHeaders.filter(header=>!present.has(header.toLowerCase()));if(missing.length>0){context.report({node,messageId:"missingSecurityHeader",data:{headers:missing.join(", ")}})}}function checkDeclaredHeaders(node){const declared=declaredResponseHeaders(node);if(declared===null)return;reportDeclaredBlock(node,declared)}return{CallExpression(node){const block=writeHeadHeaders(node);if(block!==null){const declared=objectHeaderNames(block);if(declared!==null)reportDeclaredBlock(node,declared);return}checkCallExpression(node)},Property:checkDeclaredHeaders}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingSecurityHeaders=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const DEFAULT_REQUIRED_HEADERS=["Content-Security-Policy","X-Frame-Options","X-Content-Type-Options"];const NON_DOCUMENT_HEADERS=new Set(["Set-Cookie","Cache-Control","Location","Content-Disposition","ETag","Last-Modified","Expires","Vary"].map(h=>h.toLowerCase()));const KNOWN_RESPONSE_HEADERS=new Set(["Content-Security-Policy","Content-Security-Policy-Report-Only","X-Frame-Options","X-Content-Type-Options","X-XSS-Protection","Strict-Transport-Security","Referrer-Policy","Permissions-Policy","Feature-Policy","Cross-Origin-Opener-Policy","Cross-Origin-Embedder-Policy","Cross-Origin-Resource-Policy","X-Permitted-Cross-Domain-Policies","X-DNS-Prefetch-Control","X-Download-Options","Origin-Agent-Cluster","Report-To","Reporting-Endpoints","Clear-Site-Data","Access-Control-Allow-Origin","Access-Control-Allow-Credentials","Access-Control-Allow-Methods","Access-Control-Allow-Headers","Access-Control-Expose-Headers","Access-Control-Max-Age","Timing-Allow-Origin","Content-Type","Content-Length","Content-Encoding","Content-Language","Content-Disposition","Content-Range","Cache-Control","Pragma","Expires","ETag","Last-Modified","Age","Vary","Location","Set-Cookie","Server","Retry-After","Link","Accept-Ranges","Transfer-Encoding","WWW-Authenticate"].map(h=>h.toLowerCase()));const UNAMBIGUOUS_HEADER_METHODS=new Set(["setHeader","header"]);const DYNAMIC_HEADER_NAME=Symbol("dynamic header name");function extractHeaderName(node,sourceCode){const arg=node.arguments[0];if(arg===void 0)return null;const folded=staticStringValue(arg,sourceCode,0);if(folded!==null)return folded;const viaParameter=parameterLiterals(arg,sourceCode);if(viaParameter.length===1)return viaParameter[0];return DYNAMIC_HEADER_NAME}function staticStringValue(node,sourceCode,depth){if(depth>4)return null;if(node.type==="Literal"){return typeof node.value==="string"?node.value:null}if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:staticStringValue(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const container=foldToArray(node.object,sourceCode,depth+1);const element=container?.elements[index.value];return element==null?null:staticStringValue(element,sourceCode,depth+1)}return null}function foldToArray(node,sourceCode,depth){if(depth>4)return null;if(node.type==="ArrayExpression")return node;if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToArray(init,sourceCode,depth+1)}if(node.type==="MemberExpression"&&node.computed){const index=node.property;if(index.type!=="Literal"||typeof index.value!=="number")return null;const outer=foldToArray(node.object,sourceCode,depth+1);const element=outer?.elements[index.value];return element==null?null:foldToArray(element,sourceCode,depth+1)}return null}function parameterLiterals(arg,sourceCode){if(arg.type!=="Identifier")return[];const variable=sourceCode.getScope(arg).references.find(ref=>ref.identifier===arg)?.resolved;const def=variable?.defs[0];if(def===void 0||def.type!=="Parameter")return[];const fn=def.node;const position=fn.params.indexOf(def.name);if(position===-1)return[];const declarator=fn.type==="FunctionDeclaration"?fn:fn.parent?.type==="VariableDeclarator"?fn.parent:void 0;if(declarator===void 0)return[];const names=new Set;for(const declared of sourceCode.getDeclaredVariables(declarator)){for(const reference of declared.references){const call=reference.identifier.parent;if(call?.type!=="CallExpression"||call.callee!==reference.identifier){continue}const passed=call.arguments[position];if(passed===void 0)return[];const value=staticStringValue(passed,sourceCode,0);if(value===null)return[];names.add(value)}}return[...names]}function isHeaderSet(node,requiredHeaders,sourceCode){if(node.callee.type!=="MemberExpression")return false;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null)return false;if(UNAMBIGUOUS_HEADER_METHODS.has(method))return true;if(method!=="set")return false;const extracted=extractHeaderName(node,sourceCode);if(extracted===null||extracted===DYNAMIC_HEADER_NAME)return false;const name=extracted.toLowerCase();return KNOWN_RESPONSE_HEADERS.has(name)||requiredHeaders.some(h=>h.toLowerCase()===name)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}const DOCUMENT_MEDIA_TYPES=new Set(["text/html","application/xhtml+xml","image/svg+xml"]);function isDocumentMediaType(contentType){const mediaType=contentType.split(";")[0].trim().toLowerCase();return DOCUMENT_MEDIA_TYPES.has(mediaType)}function checkFunctionForSecurityHeaders(node,requiredHeaders,context){const setHeaders=new Set;let scopeIsOpaque=false;let declaredContentType=null;let current=node;let scopeNode=null;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){scopeNode=current;break}current=current.parent??null}if(!scopeNode){scopeNode=context.sourceCode.ast}function collectHeaders(astNode){if(astNode.type==="CallExpression"&&isHeaderSet(astNode,requiredHeaders,context.sourceCode)){const headerName=extractHeaderName(astNode,context.sourceCode);if(headerName===DYNAMIC_HEADER_NAME){scopeIsOpaque=true}else if(headerName!==null){setHeaders.add(headerName.toLowerCase());if(headerName.toLowerCase()==="content-type"){const value=astNode.arguments[1];declaredContentType=value===void 0?null:staticStringValue(value,context.sourceCode,0)}}}for(const key of Object.keys(astNode)){if(key==="parent")continue;const child=astNode[key];if(Array.isArray(child)){for(const item of child){if(isNode(item))collectHeaders(item)}}else if(isNode(child)){collectHeaders(child)}}}collectHeaders(scopeNode);if(scopeIsOpaque){return[]}if(setHeaders.size>0&&[...setHeaders].every(h=>NON_DOCUMENT_HEADERS.has(h))){return[]}if(declaredContentType!==null&&!isDocumentMediaType(declaredContentType)){return[]}return requiredHeaders.filter(header=>!setHeaders.has(header.toLowerCase()))}function declaredResponseHeaders(property){if(property.computed)return null;const key=property.key;const keyName=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):null;if(keyName!=="headers")return null;const value=property.value;if(value.type==="ArrayExpression"){const names=[];let contentType=null;for(const element of value.elements){if(element===null||element.type!=="ObjectExpression")continue;for(const entry of element.properties){if(entry.type!=="Property"||entry.computed)continue;const entryKey=entry.key.type==="Identifier"?entry.key.name:null;if(entryKey!=="key")continue;const staticText=(0,eslint_devkit_1.staticString)(entry.value);if(staticText!==null){names.push(staticText);if(staticText.toLowerCase()==="content-type"){contentType=element.properties.find(p=>p.type==="Property"&&!p.computed&&p.key.type==="Identifier"&&p.key.name==="value")?.value??null}}}}return names.length>0?{names,contentType}:null}if(value.type!=="ObjectExpression")return null;const init=property.parent;if(init.type!=="ObjectExpression"||!isResponseInit(init))return null;return objectHeaderNames(value)}function objectHeaderNames(object){const names=[];let contentType=null;for(const entry of object.properties){if(entry.type==="SpreadElement")return null;if(entry.computed)return null;const name=(0,eslint_devkit_1.staticString)(entry.key)!==null?(0,eslint_devkit_1.staticString)(entry.key):entry.key.type==="Identifier"?entry.key.name:null;if(name===null)continue;names.push(name);if(name.toLowerCase()==="content-type")contentType=entry.value}return names.length>0?{names,contentType}:null}function writeHeadHeaders(node){if(node.callee.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(node.callee)!=="writeHead"){return null}const block=node.arguments.find(arg=>arg.type==="ObjectExpression");return block??null}const RESPONSE_FACTORIES=new Set(["json","next","redirect","rewrite","error"]);function isResponseInit(init){const hasResponseOnlyField=init.properties.some(p=>p.type==="Property"&&!p.computed&&p.key.type==="Identifier"&&(p.key.name==="status"||p.key.name==="statusText"));if(hasResponseOnlyField)return true;const call=init.parent;if(call.type!=="NewExpression"&&call.type!=="CallExpression"){return false}const callee=call.callee;if(callee.type==="Identifier")return callee.name==="Response";if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),RESPONSE_FACTORIES)&&(callee.object.name==="Response"||callee.object.name==="NextResponse")}return false}exports.noMissingSecurityHeaders=(0,eslint_devkit_2.createRule)({name:"no-missing-security-headers",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-helmet"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-security-headers.md",description:"Detects missing security headers in HTTP responses",cwe:"CWE-693",cvss:7.5},messages:{missingSecurityHeader:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing security headers",cwe:"CWE-693",description:"Missing security headers: {{headers}}",severity:"HIGH",fix:"Set security headers: Content-Security-Policy, X-Frame-Options, X-Content-Type-Options",documentationLink:"https://owasp.org/www-project-secure-headers/"})},schema:[{type:"object",properties:{requiredHeaders:{type:"array",items:{type:"string"},default:DEFAULT_REQUIRED_HEADERS,description:"Security headers a response must set"},ignoreInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{requiredHeaders:DEFAULT_REQUIRED_HEADERS,ignoreInTests:true}],create(context,[options={}]){const{requiredHeaders=DEFAULT_REQUIRED_HEADERS,ignoreInTests=true}=options||{};const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const reportedScopes=new Set;function getScopeKey(node){let current=node;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return`${current.range?.[0]}-${current.range?.[1]}`}current=current.parent??null}return"program"}function checkCallExpression(node){if(!isHeaderSet(node,requiredHeaders,context.sourceCode)){return}const scopeKey=getScopeKey(node);if(reportedScopes.has(scopeKey)){return}const missing=checkFunctionForSecurityHeaders(node,requiredHeaders,context);reportedScopes.add(scopeKey);if(missing.length>0){context.report({node,messageId:"missingSecurityHeader",data:{headers:missing.join(", ")}})}}function reportDeclaredBlock(node,block){const contentType=block.contentType===null?null:staticStringValue(block.contentType,context.sourceCode,0);const present=new Set(block.names.map(h=>h.toLowerCase()));if([...present].every(h=>NON_DOCUMENT_HEADERS.has(h)))return;if(contentType!==null&&!isDocumentMediaType(contentType))return;const missing=requiredHeaders.filter(header=>!present.has(header.toLowerCase()));if(missing.length>0){context.report({node,messageId:"missingSecurityHeader",data:{headers:missing.join(", ")}})}}function checkDeclaredHeaders(node){const declared=declaredResponseHeaders(node);if(declared===null)return;reportDeclaredBlock(node,declared)}return{CallExpression(node){const block=writeHeadHeaders(node);if(block!==null){const declared=objectHeaderNames(block);if(declared!==null)reportDeclaredBlock(node,declared);return}checkCallExpression(node)},Property:checkDeclaredHeaders}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCors=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const ALLOW_ORIGIN="access-control-allow-origin";const HEADER_METHODS=new Set(["setHeader","header","set"]);function foldToString(node,sourceCode,depth=0){if(depth>4)return null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?node.value:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToString(init,sourceCode,depth+1)}return null}function foldToObject(node,sourceCode,depth=0){if(depth>4)return null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToObject(init,sourceCode,depth+1)}return null}function keyName(property){if(property.computed)return null;if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return property.key.name;if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"){return property.key.value}return null}function readsRequestOrigin(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const property=node.property;const name=node.computed?property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.value==="string"?property.value:null:property.name;if(name?.toLowerCase()!=="origin")return false;const receiver=node.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCors=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const ALLOW_ORIGIN="access-control-allow-origin";const HEADER_METHODS=new Set(["setHeader","header","set"]);function foldToString(node,sourceCode,depth=0){if(depth>4)return null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?node.value:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToString(init,sourceCode,depth+1)}return null}function foldToObject(node,sourceCode,depth=0){if(depth>4)return null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:foldToObject(init,sourceCode,depth+1)}return null}function keyName(property){if(property.computed)return null;if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return property.key.name;if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"){return property.key.value}return null}function readsRequestOrigin(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const property=node.property;const name=node.computed?property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.value==="string"?property.value:null:property.name;if(name?.toLowerCase()!=="origin")return false;const receiver=node.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(receiver)==="headers"}exports.noPermissiveCors=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/no-permissive-cors"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-permissive-cors.md",description:"Prevent overly permissive CORS configuration",cwe:"CWE-942",cvss:7.5,confidence:"high"},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-942",description:"Prevent overly permissive CORS configuration detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/942.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}const sourceCode=context.sourceCode;return{Property(node){const name=keyName(node);if(name?.toLowerCase()===ALLOW_ORIGIN&&foldToString(node.value,sourceCode)==="*"){report(node);return}if(name!=="key"||foldToString(node.value,sourceCode)?.toLowerCase()!==ALLOW_ORIGIN){return}const entry=node.parent;const valueProperty=entry.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&keyName(p)==="value");if(valueProperty!==void 0&&foldToString(valueProperty.value,sourceCode)==="*"){report(entry)}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),HEADER_METHODS)&&node.arguments[0]!==void 0&&foldToString(node.arguments[0],sourceCode)?.toLowerCase()===ALLOW_ORIGIN&&node.arguments[1]!==void 0){const value=node.arguments[1];if(foldToString(value,sourceCode)==="*"||readsRequestOrigin(value)){report(node)}}const corsOptions=node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="cors"&&node.arguments[0]!==void 0?foldToObject(node.arguments[0],sourceCode):null;if(corsOptions!==null){const originProp=corsOptions.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.key.name==="origin");if(originProp&&originProp.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(originProp.value.value==="*"||originProp.value.value===true)){report(node)}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPostmessageInnerhtml=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DANGEROUS_PROPERTIES=new Set(["innerHTML","outerHTML"]);const DANGEROUS_METHODS=new Set(["insertAdjacentHTML","write","writeln"]);exports.noPostmessageInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-postmessage-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-postmessage-innerhtml.md",description:"Disallow using innerHTML or similar methods with postMessage data",cwe:"CWE-79",cvss:8.8},messages:{unsafeInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via postMessage",cwe:"CWE-79",owasp:"A03:2021",cvss:8.8,description:"Using {{method}} with postMessage data allows XSS attacks. Any window can send malicious HTML that will be executed.",severity:"HIGH",fix:"Use textContent for plain text, or sanitize with DOMPurify before using innerHTML.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPostmessageInnerhtml=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DANGEROUS_PROPERTIES=new Set(["innerHTML","outerHTML"]);const DANGEROUS_METHODS=new Set(["insertAdjacentHTML","write","writeln"]);exports.noPostmessageInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-postmessage-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-postmessage-innerhtml.md",description:"Disallow using innerHTML or similar methods with postMessage data",cwe:"CWE-79",cvss:8.8},messages:{unsafeInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via postMessage",cwe:"CWE-79",owasp:"A03:2021",cvss:8.8,description:"Using {{method}} with postMessage data allows XSS attacks. Any window can send malicious HTML that will be executed.",severity:"HIGH",fix:"Use textContent for plain text, or sanitize with DOMPurify before using innerHTML.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),DANGEROUS_METHODS)){for(const arg of node.arguments){if(payloadSource(arg)==="postmessage"){context.report({node,messageId:"unsafeInnerhtml",data:{method:(0,eslint_devkit_1.propertyName)(node.callee)}});break}}}},AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.left),DANGEROUS_PROPERTIES)){if(payloadSource(node.right)==="postmessage"){context.report({node,messageId:"unsafeInnerhtml",data:{method:(0,eslint_devkit_1.propertyName)(node.left)}})}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPostmessageWildcardOrigin=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noPostmessageWildcardOrigin=(0,eslint_devkit_1.createRule)({name:"no-postmessage-wildcard-origin",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-postmessage-wildcard-origin.md",description:"Disallow using wildcard (*) as targetOrigin in postMessage calls",cwe:"CWE-346",cvss:7.5},hasSuggestions:true,messages:{wildcardOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Wildcard postMessage Origin",cwe:"CWE-346",owasp:"A01:2021",cvss:7.5,description:'postMessage with "*" targetOrigin allows any window to receive the message, potentially leaking sensitive data to malicious sites.',severity:"HIGH",fix:'Specify the exact origin of the target window instead of "*".',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"}),specifyOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Specify Target Origin",description:"Replace wildcard with specific origin",severity:"LOW",fix:"Use the exact target origin, e.g., 'https://trusted-domain.com'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPostmessageWildcardOrigin=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noPostmessageWildcardOrigin=(0,eslint_devkit_1.createRule)({name:"no-postmessage-wildcard-origin",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-postmessage-wildcard-origin.md",description:"Disallow using wildcard (*) as targetOrigin in postMessage calls",cwe:"CWE-346",cvss:7.5},hasSuggestions:true,messages:{wildcardOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Wildcard postMessage Origin",cwe:"CWE-346",owasp:"A01:2021",cvss:7.5,description:'postMessage with "*" targetOrigin allows any window to receive the message, potentially leaking sensitive data to malicious sites.',severity:"HIGH",fix:'Specify the exact origin of the target window instead of "*".',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"}),specifyOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Specify Target Origin",description:"Replace wildcard with specific origin",severity:"LOW",fix:"Use the exact target origin, e.g., 'https://trusted-domain.com'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return}if((0,eslint_devkit_1.propertyName)(node.callee)!=="postMessage"){return}const args=node.arguments;if(args.length<2){return}const targetOriginArg=args[1];if(targetOriginArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&targetOriginArg.value==="*"){context.report({node:targetOriginArg,messageId:"wildcardOrigin",suggest:[{messageId:"specifyOrigin",fix:fixer=>fixer.replaceText(targetOriginArg,"'https://your-domain.com'")}]});return}if(targetOriginArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of targetOriginArg.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const key=prop.key;if(key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&key.name==="targetOrigin"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value==="*"){context.report({node:prop.value,messageId:"wildcardOrigin",suggest:[{messageId:"specifyOrigin",fix:fixer=>fixer.replaceText(prop.value,"'https://your-domain.com'")}]})}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnencryptedTransmission=void 0;const loopback_hosts_1=require("../../utils/loopback-hosts");const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_INSECURE_PROTOCOLS=["ftp://","tcp://","mongodb://","redis://","mysql://"];const SECURE_ALTERNATIVES={"http://":"https://","ws://":"wss://","ftp://":"ftps://","tcp://":"tls://","mongodb://":"mongodb+srv://","redis://":"rediss://","mysql://":"mysqls://"};function containsInsecureProtocol(value,insecureProtocols){const lowerValue=value.toLowerCase().trimStart();for(const protocol of insecureProtocols){const lowerProtocol=protocol.toLowerCase();if(lowerValue.startsWith(lowerProtocol)){return{isInsecure:true,protocol}}}return{isInsecure:false,protocol:""}}function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}const NAMESPACE_URI_PREFIXES=["http://www.w3.org/","http://schemas.xmlsoap.org/","http://purl.org/","http://xmlns.com/","http://ns.adobe.com/","http://sodipodi.sourceforge.net/","http://www.inkscape.org/"];function isNamespaceUri(value){return NAMESPACE_URI_PREFIXES.some(prefix=>value.startsWith(prefix))}const WRITES_SECOND_ARGUMENT=new Set(["replace","replaceAll"]);const INSPECTION_METHODS=new Set(["startsWith","endsWith","includes","indexOf","lastIndexOf","search","match","matchAll","test","split","replace","replaceAll"]);function isProtocolInspection(node,parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnencryptedTransmission=void 0;const loopback_hosts_1=require("../../utils/loopback-hosts");const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_INSECURE_PROTOCOLS=["ftp://","tcp://","mongodb://","redis://","mysql://"];const SECURE_ALTERNATIVES={"http://":"https://","ws://":"wss://","ftp://":"ftps://","tcp://":"tls://","mongodb://":"mongodb+srv://","redis://":"rediss://","mysql://":"mysqls://"};function containsInsecureProtocol(value,insecureProtocols){const lowerValue=value.toLowerCase().trimStart();for(const protocol of insecureProtocols){const lowerProtocol=protocol.toLowerCase();if(lowerValue.startsWith(lowerProtocol)){return{isInsecure:true,protocol}}}return{isInsecure:false,protocol:""}}function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}const NAMESPACE_URI_PREFIXES=["http://www.w3.org/","http://schemas.xmlsoap.org/","http://purl.org/","http://xmlns.com/","http://ns.adobe.com/","http://sodipodi.sourceforge.net/","http://www.inkscape.org/"];function isNamespaceUri(value){return NAMESPACE_URI_PREFIXES.some(prefix=>value.startsWith(prefix))}const WRITES_SECOND_ARGUMENT=new Set(["replace","replaceAll"]);const INSPECTION_METHODS=new Set(["startsWith","endsWith","includes","indexOf","lastIndexOf","search","match","matchAll","test","split","replace","replaceAll"]);function isProtocolInspection(node,parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(parent.callee),INSPECTION_METHODS)){if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(parent.callee),WRITES_SECOND_ARGUMENT)){return parent.arguments[0]===node}return true}return parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&COMPARISON_OPERATORS.has(parent.operator)}const COMPARISON_OPERATORS=new Set(["===","!==","==","!="]);exports.noUnencryptedTransmission=(0,eslint_devkit_2.createRule)({name:"no-unencrypted-transmission",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unencrypted-transmission.md",description:"Detects unencrypted data transmission (HTTP vs HTTPS, plain text protocols)",cwe:"CWE-319",cvss:7.5},hasSuggestions:true,messages:{unencryptedTransmission:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unencrypted Transmission",cwe:"CWE-319",description:"Unencrypted transmission detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"}),useHttps:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use HTTPS",description:"Use secure protocol",severity:"LOW",fix:"Replace http:// with https://",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unencrypted transmission in test files"},insecureProtocols:{type:"array",items:{type:"string"},default:[],description:"Insecure protocol patterns to detect"},secureAlternatives:{type:"object",additionalProperties:{type:"string"},default:{},description:"Mapping of insecure protocols to their secure alternatives"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,insecureProtocols:[],secureAlternatives:{},ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,insecureProtocols,secureAlternatives,ignorePatterns=[]}=options;const protocolsToCheck=insecureProtocols&&insecureProtocols.length>0?insecureProtocols:DEFAULT_INSECURE_PROTOCOLS;const secureAlternativesToUse=secureAlternatives&&Object.keys(secureAlternatives).length>0?{...SECURE_ALTERNATIVES,...secureAlternatives}:SECURE_ALTERNATIVES;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;function checkLiteral(node){if(typeof node.value!=="string"){return}const value=node.value;const text=sourceCode.getText(node);if(isProtocolInspection(node,node.parent)){return}if(isNamespaceUri(value)){return}if((0,loopback_hosts_1.isNonTransmittingUrl)(value)){return}if(isTestFile&&(0,loopback_hosts_1.isLoopbackHost)(value)){return}if(matchesIgnorePattern(text,ignorePatterns)){return}const{isInsecure,protocol}=containsInsecureProtocol(value,protocolsToCheck);if(isInsecure){const secureProtocol=secureAlternativesToUse[protocol.toLowerCase()]||"secure protocol";const safeAlternative=`Use ${secureProtocol} instead of ${protocol}`;context.report({node,messageId:"unencryptedTransmission",data:{issue:`using insecure protocol ${protocol}`,safeAlternative},suggest:[{messageId:"useHttps",data:{protocol,secureProtocol},fix(fixer){if(secureProtocol&&secureProtocol!=="secure protocol"){const newValue=value.replace(new RegExp(protocol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),secureProtocol);return fixer.replaceText(node,JSON.stringify(newValue))}return null}}]})}}function checkTemplateLiteral(node){if(isTestFile){return}const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const quasi of node.quasis){const value=quasi.value.raw;const{isInsecure,protocol}=containsInsecureProtocol(value,protocolsToCheck);if(isInsecure){const secureProtocol=secureAlternativesToUse[protocol.toLowerCase()]||"secure protocol";const safeAlternative=`Use ${secureProtocol} instead of ${protocol}`;context.report({node:quasi,messageId:"unencryptedTransmission",data:{issue:`using insecure protocol ${protocol} in template literal`,safeAlternative}})}}}return{Literal:checkLiteral,TemplateLiteral:checkTemplateLiteral}}});
|