eslint-plugin-browser-security 3.0.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-browser-security",
|
|
3
|
-
"version": "3.0
|
|
4
|
-
"description": "ESLint
|
|
3
|
+
"version": "3.1.0",
|
|
4
|
+
"description": "ESLint browser security and XSS rules — detects DOM XSS, postMessage abuse, tokens in localStorage, insecure cookies, clickjacking, mixed content, and CSP gaps.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"main": "./src/index.js",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"node": ">=22.13.0"
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"@interlace/eslint-devkit": "^2.0.
|
|
78
|
+
"@interlace/eslint-devkit": "^2.0.4"
|
|
79
79
|
},
|
|
80
80
|
"peerDependencies": {
|
|
81
81
|
"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:"3.0
|
|
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:"3.1.0"},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.noCredentialsInQueryParams=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const WHOLE_NAME_CREDENTIALS=new Set(["token","auth"]);const DEFAULT_CREDENTIAL_SUFFIXES=["password","passwd","pwd","passphrase","secret","apikey","api key","access token","refresh token","id token","auth token","session token","bearer token","private token"];function isCredentialParam(name,suffixes){const words=(0,eslint_devkit_1.identifierWords)(name);if(WHOLE_NAME_CREDENTIALS.has(words.join(" ")))return true;return suffixes.some(suffix=>suffix.length<=words.length&&suffix.every((word,i)=>words[words.length-suffix.length+i]===word))}const QUERY_PARAMETER=/[?&]([^=&?#\s\u0001]+)=/g;const DEFAULT_BODY_PROPERTIES=["body","data","form","formData"];exports.noCredentialsInQueryParams=(0,eslint_devkit_1.createRule)({name:"no-credentials-in-query-params",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-credentials-in-query-params.md",description:"Disallow credentials in URL query parameters",cwe:"CWE-598",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Credentials in Query Parameters",cwe:"CWE-598",description:"Credentials detected in URL query
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCredentialsInQueryParams=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const WHOLE_NAME_CREDENTIALS=new Set(["token","auth"]);const DEFAULT_CREDENTIAL_SUFFIXES=["password","passwd","pwd","passphrase","secret","apikey","api key","access token","refresh token","id token","auth token","session token","bearer token","private token"];function isCredentialParam(name,suffixes){const words=(0,eslint_devkit_1.identifierWords)(name);if(WHOLE_NAME_CREDENTIALS.has(words.join(" ")))return true;return suffixes.some(suffix=>suffix.length<=words.length&&suffix.every((word,i)=>words[words.length-suffix.length+i]===word))}const QUERY_PARAMETER=/[?&]([^=&?#\s\u0001]+)=/g;const DEFAULT_BODY_PROPERTIES=["body","data","form","formData"];exports.noCredentialsInQueryParams=(0,eslint_devkit_1.createRule)({name:"no-credentials-in-query-params",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-credentials-in-query-params.md",description:"Disallow credentials in URL query parameters",cwe:"CWE-598",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Credentials in Query Parameters",cwe:"CWE-598",description:"Credentials detected in URL query parameter `{{param}}` - this is a security risk",severity:"CRITICAL",fix:"Use secure methods: POST body, headers (Authorization), or secure cookies",documentationLink:"https://cwe.mitre.org/data/definitions/598.html"})},schema:[{type:"object",properties:{bodyProperties:{type:"array",items:{type:"string"},default:DEFAULT_BODY_PROPERTIES,description:"Property names whose value is a request body rather than a URL"},credentialSuffixes:{type:"array",items:{type:"string"},default:[...DEFAULT_CREDENTIAL_SUFFIXES],description:"Credential words a query-parameter name ends in (replaces the default)"}},additionalProperties:false}]},defaultOptions:[{bodyProperties:DEFAULT_BODY_PROPERTIES,credentialSuffixes:[...DEFAULT_CREDENTIAL_SUFFIXES]}],createOnce(context){let bodyPropertyNames;let credentialSuffixWords;const OUT_OF_BAND_FLOWS=/\/(reset|reset-password|forgot|verify|verify-email|confirm|activate|unsubscribe|magic-?link)\b/;function reportableCredential(url){const match=[...url.matchAll(QUERY_PARAMETER)].find(([,name])=>isCredentialParam(name,credentialSuffixWords)&&!(name.toLowerCase()==="token"&&OUT_OF_BAND_FLOWS.test(url)));return match===void 0?null:match[1]}function isRequestBody(node){const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node&&!parent.computed){const key=(0,eslint_devkit_1.objectKeyName)(parent);if(key!==null&&bodyPropertyNames.has(key))return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.callee.name==="URLSearchParams"){return true}return false}function report(node,param){context.report({node,messageId:"violationDetected",data:{param}})}return{before(){const{bodyProperties=DEFAULT_BODY_PROPERTIES,credentialSuffixes=DEFAULT_CREDENTIAL_SUFFIXES}=context.options[0]??{};bodyPropertyNames=new Set(bodyProperties);credentialSuffixWords=credentialSuffixes.map(eslint_devkit_1.identifierWords)},Literal(node){if(typeof node.value==="string"){const param=reportableCredential(node.value);if(param!==null&&!isRequestBody(node))report(node,param)}},TemplateLiteral(node){const INTERPOLATION="";const text=node.quasis.map(q=>q.value.raw).join(INTERPOLATION);const param=reportableCredential(text);if(param!==null&&!isRequestBody(node))report(node,param)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeInlineCsp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noUnsafeInlineCsp=(0,eslint_devkit_1.createRule)({name:"no-unsafe-inline-csp",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unsafe-inline-csp.md",description:"Disallow 'unsafe-inline' in Content Security Policy",cwe:"CWE-79",cvss:7.5},messages:{unsafeInline:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-inline' Detected",cwe:"CWE-79",owasp:"A03:2021",cvss:7.5,description:"'unsafe-inline' in CSP allows inline scripts
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeInlineCsp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DIRECTIVE_NAME=/^(?:default|script|style|img|connect|font|frame|media|object|worker|child|manifest|prefetch|base|form)-(?:src|uri|action)(?:-elem|-attr)?$/i;const SCRIPT_DIRECTIVES=new Set(["script-src","script-src-elem","script-src-attr"]);const STYLE_DIRECTIVES=new Set(["style-src","style-src-elem","style-src-attr"]);function inlineEnables(value){const policies=value.split(",").map(policyEnables);return{named:policies.some(policy=>policy.named),script:policies.some(policy=>policy.script),style:policies.some(policy=>policy.style)}}function policyEnables(policy){const directives=policy.split(";").flatMap(segment=>{const tokens=segment.split(/[\s"<>=]+/).filter(Boolean);const at=tokens.findIndex(token=>DIRECTIVE_NAME.test(token));if(at===-1)return[];return[{name:tokens[at].toLowerCase(),inline:tokens.slice(at+1).some(token=>token.toLowerCase()==="'unsafe-inline'")}]});const names=new Set(directives.map(directive=>directive.name));const enables=(governing,own)=>directives.some(directive=>directive.inline&&(governing.has(directive.name)||directive.name==="default-src"&&!names.has(own)));return{named:directives.length>0,script:enables(SCRIPT_DIRECTIVES,"script-src"),style:enables(STYLE_DIRECTIVES,"style-src")}}exports.noUnsafeInlineCsp=(0,eslint_devkit_1.createRule)({name:"no-unsafe-inline-csp",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unsafe-inline-csp.md",description:"Disallow 'unsafe-inline' in Content Security Policy",cwe:"CWE-79",cvss:7.5},messages:{unsafeInline:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-inline' Detected",cwe:"CWE-79",owasp:"A03:2021",cvss:7.5,description:"'unsafe-inline' in a script-governing CSP directive allows inline scripts to execute, defeating XSS protection.",severity:"HIGH",fix:"Use nonces or hashes instead: script-src 'nonce-abc123' or script-src 'sha256-...'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"}),unsafeInlineStyle:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-inline' for Styles",cwe:"CWE-79",owasp:"A03:2021",cvss:4.3,description:"'unsafe-inline' in style-src allows inline styles, which an injected <style> or style attribute can use for CSS injection (data exfiltration through selectors, UI redressing).",severity:"MEDIUM",fix:"Move styles to stylesheets, or allow them by nonce or hash: style-src 'nonce-abc123'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},checkStyleSrc:{type:"boolean",default:false,description:"Also report 'unsafe-inline' that permits inline styles, under a MEDIUM-severity message."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,checkStyleSrc:false}],createOnce(context,currentOptions){const UNSAFE_INLINE_PATTERN=/'unsafe-inline'/i;let checkStyleSrc;const isCspName=name=>/^content-security-policy(-report-only)?$/i.test(name)||/^contentsecuritypolicy(reportonly)?$/i.test(name)||name.toLowerCase()==="csp";function atCspSink(node){const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[1]===node){const first=parent.arguments[0];return first.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof first.value==="string"&&isCspName(first.value)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node){const keyText=(0,eslint_devkit_1.objectKeyName)(parent);return keyText!==null&&isCspName(keyText)}const attribute=parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute?parent:parent.parent;if(attribute?.type!==eslint_devkit_1.AST_NODE_TYPES.JSXAttribute||attribute.name.type!==eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier||attribute.name.name!=="content"){return false}const element=attribute.parent;return element.attributes.some(other=>other.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute&&other.name.type===eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier&&/^http-?equiv$/i.test(other.name.name)&&other.value?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof other.value.value==="string"&&isCspName(other.value.value))}const SOURCE_EXPRESSION=/^(?:'[^'\s]+'|[a-z][a-z0-9+.-]*:|[a-z][a-z0-9+.-]*:\/\/\S+|\*(?:\.\S+)?)$/i;const grants=value=>value.trim().split(/\s+/).every(token=>SOURCE_EXPRESSION.test(token));function checkForUnsafeInline(node,value){if(!UNSAFE_INLINE_PATTERN.test(value))return;const enabled=inlineEnables(value);if(enabled.named){if(enabled.script){context.report({node,messageId:"unsafeInline"})}else if(checkStyleSrc&&enabled.style){context.report({node,messageId:"unsafeInlineStyle"})}return}if(atCspSink(node)&&grants(value)){context.report({node,messageId:"unsafeInline"})}}return{before(){const[options={}]=currentOptions();const{allowInTests}=options;({checkStyleSrc=false}=options);const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return false}return true},Literal(node){if(typeof node.value==="string"){checkForUnsafeInline(node,node.value)}},TemplateLiteral(node){const value=node.quasis.map(q=>q.value.raw).join("");checkForUnsafeInline(node,value)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requirePostmessageOriginCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const regexp_anchoring_1=require("../../utils/regexp-anchoring");const resolve_binding_1=require("../../utils/resolve-binding");const NON_WINDOW_RECEIVERS=new Set(["WebSocket","EventSource","Worker","SharedWorker","BroadcastChannel","MessagePort","MessageChannel"]);function receiverKey(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"){const name=node.property.type==="PrivateIdentifier"?`#${node.property.name}`:(0,eslint_devkit_1.propertyName)(node);if(name===null)return void 0;if(node.object.type==="ThisExpression"){return`this.${name}`}if(node.object.type==="Identifier"){return`${node.object.name}.${name}`}}return void 0}const GLOBAL_RECEIVERS=new Set(["window","self","globalThis"]);function isMembershipReceiver(node,sourceCode){if((0,eslint_devkit_1.staticString)(node)!==null)return false;if(node.type==="Identifier"){return(0,eslint_devkit_1.staticString)((0,resolve_binding_1.resolveInitializer)(node,sourceCode))===null}return true}function fieldKey(node){if(node.key.type==="PrivateIdentifier")return`this.#${node.key.name}`;const name=(0,eslint_devkit_1.objectKeyName)(node);return name===null?void 0:`this.${name}`}function annotatedTypeName(annotation){const type=annotation?.typeAnnotation;if(type?.type==="TSTypeReference"&&type.typeName.type==="Identifier"){return type.typeName.name}return void 0}function hasOriginCheck(node,sourceCode){const text=sourceCode.getText(node);const originPatterns=[/origin\s*[!=]==?/,/checkOrigin/i,/validateOrigin/i,/isAllowedOrigin/i,/trustedOrigins/i,/allowedOrigins/i];return originPatterns.some(pattern=>pattern.test(text))}function isMessageEvent(node){return(0,eslint_devkit_1.staticString)(node.arguments[0])==="message"}exports.requirePostmessageOriginCheck=(0,eslint_devkit_1.createRule)({name:"require-postmessage-origin-check",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-postmessage-origin-check.md",description:"Require origin validation in postMessage event listeners",cwe:"CWE-346",cvss:7.5},messages:{missingOriginCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing postMessage Origin Validation",cwe:"CWE-346",description:"postMessage listener lacks origin check. Malicious sites can send messages that will be processed.",severity:"HIGH",fix:"Add origin validation: if (event.origin !== 'https://trusted-domain.com') return;",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let sourceCode;let unverified;let nonWindowReceivers;let anchoredOriginTests;function rememberIfNonWindow(key,typeName){if(key===void 0||typeName===void 0)return;if(NON_WINDOW_RECEIVERS.has(typeName))nonWindowReceivers.add(key)}function isOriginRead(node){return node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="origin"}return{before(){const[options={}]=currentOptions();const{allowInTests}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;unverified=[];nonWindowReceivers=new Set;anchoredOriginTests=[];return true},PropertyDefinition(node){rememberIfNonWindow(fieldKey(node),annotatedTypeName(node.typeAnnotation))},VariableDeclarator(node){if(node.id.type!=="Identifier")return;rememberIfNonWindow(node.id.name,annotatedTypeName(node.id.typeAnnotation))},NewExpression(node){if(node.callee.type!=="Identifier")return;const typeName=node.callee.name;const parent=node.parent;if(parent.type==="VariableDeclarator"){rememberIfNonWindow(receiverKey(parent.id),typeName);return}if(parent.type==="AssignmentExpression"){rememberIfNonWindow(receiverKey(parent.left),typeName);return}if(parent.type==="PropertyDefinition"){rememberIfNonWindow(fieldKey(parent),typeName)}},CallExpression(node){const callee=node.callee;if(node.arguments.length===1&&isOriginRead(node.arguments[0])&&((0,regexp_anchoring_1.isAnchoredRegexpTest)(node,sourceCode)||callee.type==="MemberExpression"&&((0,eslint_devkit_1.propertyName)(callee)==="includes"||(0,eslint_devkit_1.propertyName)(callee)==="has")&&isMembershipReceiver(callee.object,sourceCode))){anchoredOriginTests.push([node.range[0],node.range[1]])}let isMessageListener=false;let receiver;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="addEventListener"){if(isMessageEvent(node)){isMessageListener=true;receiver=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requirePostmessageOriginCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const regexp_anchoring_1=require("../../utils/regexp-anchoring");const resolve_binding_1=require("../../utils/resolve-binding");const NON_WINDOW_RECEIVERS=new Set(["WebSocket","EventSource","Worker","SharedWorker","BroadcastChannel","MessagePort","MessageChannel"]);function receiverKey(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"){const name=node.property.type==="PrivateIdentifier"?`#${node.property.name}`:(0,eslint_devkit_1.propertyName)(node);if(name===null)return void 0;if(node.object.type==="ThisExpression"){return`this.${name}`}if(node.object.type==="Identifier"){return`${node.object.name}.${name}`}}return void 0}const GLOBAL_RECEIVERS=new Set(["window","self","globalThis"]);const GLOBAL_KEY="<global>";const WORKER_ENTRY=/\.worker\.[cm]?[jt]sx?$/;const SERVICE_WORKER_EVENTS=new Set(["install","activate","fetch","push","pushsubscriptionchange","sync","notificationclick","notificationclose"]);function declaredVariable(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length>0?variable:void 0}return void 0}function globalAwareKey(node,sourceCode){if(node.type==="Identifier"&&(node.name==="self"||node.name==="globalThis")&&declaredVariable(node,sourceCode)===void 0){return GLOBAL_KEY}return receiverKey(node)}function isMembershipReceiver(node,sourceCode){if((0,eslint_devkit_1.staticString)(node)!==null)return false;if(node.type==="Identifier"){return(0,eslint_devkit_1.staticString)((0,resolve_binding_1.resolveInitializer)(node,sourceCode))===null}return true}function fieldKey(node){if(node.key.type==="PrivateIdentifier")return`this.#${node.key.name}`;const name=(0,eslint_devkit_1.objectKeyName)(node);return name===null?void 0:`this.${name}`}function annotatedTypeName(annotation){const type=annotation?.typeAnnotation;if(type?.type==="TSTypeReference"&&type.typeName.type==="Identifier"){return type.typeName.name}return void 0}function hasOriginCheck(node,sourceCode){const text=sourceCode.getText(node);const originPatterns=[/origin\s*[!=]==?/,/checkOrigin/i,/validateOrigin/i,/isAllowedOrigin/i,/trustedOrigins/i,/allowedOrigins/i];return originPatterns.some(pattern=>pattern.test(text))}function isMessageEvent(node){return(0,eslint_devkit_1.staticString)(node.arguments[0])==="message"}exports.requirePostmessageOriginCheck=(0,eslint_devkit_1.createRule)({name:"require-postmessage-origin-check",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-postmessage-origin-check.md",description:"Require origin validation in postMessage event listeners",cwe:"CWE-346",cvss:7.5},messages:{missingOriginCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing postMessage Origin Validation",cwe:"CWE-346",description:"postMessage listener lacks origin check. Malicious sites can send messages that will be processed.",severity:"HIGH",fix:"Add origin validation: if (event.origin !== 'https://trusted-domain.com') return;",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let sourceCode;let unverified;let nonWindowReceivers;let serviceWorkerScopes;let anchoredOriginTests;function rememberIfNonWindow(key,typeName){if(key===void 0||typeName===void 0)return;if(NON_WINDOW_RECEIVERS.has(typeName))nonWindowReceivers.add(key)}function aliasesWindow(identifier){const init=(0,resolve_binding_1.resolveInitializer)(identifier,sourceCode);return init?.type==="Identifier"&&init.name==="window"}function isOriginRead(node){return node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="origin"}return{before(){const[options={}]=currentOptions();const{allowInTests}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;unverified=[];nonWindowReceivers=new Set;serviceWorkerScopes=new Set;anchoredOriginTests=[];if(WORKER_ENTRY.test(filename))nonWindowReceivers.add(GLOBAL_KEY);return true},PropertyDefinition(node){rememberIfNonWindow(fieldKey(node),annotatedTypeName(node.typeAnnotation))},VariableDeclarator(node){if(node.id.type!=="Identifier")return;rememberIfNonWindow(node.id.name,annotatedTypeName(node.id.typeAnnotation))},NewExpression(node){if(node.callee.type!=="Identifier")return;const typeName=node.callee.name;const parent=node.parent;if(parent.type==="VariableDeclarator"){rememberIfNonWindow(receiverKey(parent.id),typeName);return}if(parent.type==="AssignmentExpression"){rememberIfNonWindow(receiverKey(parent.left),typeName);return}if(parent.type==="PropertyDefinition"){rememberIfNonWindow(fieldKey(parent),typeName)}},CallExpression(node){const callee=node.callee;if(node.arguments.length===1&&isOriginRead(node.arguments[0])&&((0,regexp_anchoring_1.isAnchoredRegexpTest)(node,sourceCode)||callee.type==="MemberExpression"&&((0,eslint_devkit_1.propertyName)(callee)==="includes"||(0,eslint_devkit_1.propertyName)(callee)==="has")&&isMembershipReceiver(callee.object,sourceCode))){anchoredOriginTests.push([node.range[0],node.range[1]])}let isMessageListener=false;let receiver;let receiverBinding;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="addEventListener"){const eventName=(0,eslint_devkit_1.staticString)(node.arguments[0]);const key=globalAwareKey(callee.object,sourceCode);const binding=callee.object.type==="Identifier"?declaredVariable(callee.object,sourceCode):void 0;if(eventName!==null&&SERVICE_WORKER_EVENTS.has(eventName)){if(key===GLOBAL_KEY)nonWindowReceivers.add(GLOBAL_KEY);else if(binding!==void 0&&!aliasesWindow(callee.object))serviceWorkerScopes.add(binding)}if(isMessageEvent(node)){isMessageListener=true;receiver=key;receiverBinding=binding;if(callee.object.type==="NewExpression"&&callee.object.callee.type==="Identifier"&&NON_WINDOW_RECEIVERS.has(callee.object.callee.name)){return}}}if(callee.type==="Identifier"&&callee.name==="addEventListener"){const eventName=(0,eslint_devkit_1.staticString)(node.arguments[0]);if(eventName!==null&&SERVICE_WORKER_EVENTS.has(eventName)){nonWindowReceivers.add(GLOBAL_KEY)}if(eventName==="message"){isMessageListener=true;receiver=GLOBAL_KEY}}if(!isMessageListener){return}const handlerArg=node.arguments[1];if(!handlerArg){return}if(handlerArg.type==="FunctionExpression"||handlerArg.type==="ArrowFunctionExpression"){if(!hasOriginCheck(handlerArg,sourceCode)){unverified.push({handler:handlerArg,receiver,binding:receiverBinding})}}},AssignmentExpression(node){const target=node.left;const onGlobal=target.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(target)==="onmessage"&&target.object.type==="Identifier"&&GLOBAL_RECEIVERS.has(target.object.name):target.type==="Identifier"&&target.name==="onmessage";const handler=node.right;if(onGlobal&&(handler.type==="FunctionExpression"||handler.type==="ArrowFunctionExpression")&&!hasOriginCheck(handler,sourceCode)){unverified.push({handler,receiver:target.type==="MemberExpression"?globalAwareKey(target.object,sourceCode):GLOBAL_KEY})}},"Program:exit"(){for(const{handler,receiver,binding}of unverified){if(nonWindowReceivers.has(receiver)){continue}if(binding!==void 0&&serviceWorkerScopes.has(binding)){continue}const guarded=anchoredOriginTests.some(([start,end])=>start>=handler.range[0]&&end<=handler.range[1]);if(guarded)continue;context.report({node:handler,messageId:"missingOriginCheck"})}}}}});
|