eslint-plugin-browser-security 2.2.1 → 2.2.3

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 CHANGED
@@ -109,7 +109,7 @@ All rules include structured remediation guidance designed for AI assistants:
109
109
  By providing this structured context (CWE, OWASP, Fix), we enable AI tools to **reason** about the security flaw rather than hallucinating. This allows Copilot/Cursor to suggest the _exact_ correct fix immediately.
110
110
 
111
111
  ## 💡 What You Get
112
- - **21 security rules** targeting browser-specific vulnerabilities
112
+ - **46 security rules** targeting browser-specific vulnerabilities
113
113
  - **XSS prevention** via DOM manipulation and dynamic content detection
114
114
  - **Storage security** preventing sensitive data exposure in localStorage/sessionStorage/IndexedDB
115
115
  - **Cross-origin protection** with postMessage origin validation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-browser-security",
3
- "version": "2.2.1",
3
+ "version": "2.2.3",
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.21.0"
77
+ "@interlace/eslint-devkit": "^1.21.2"
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.2.1"},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
+ "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.2.3"},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 csp_directive_1=require("../../utils/csp-directive");const resolve_binding_1=require("../../utils/resolve-binding");const FRAME_REFS=new Set(["top","self","parent","window"]);function isPolicyPermittingFraming(text){const directives=(0,csp_directive_1.parsePolicy)(text);return directives.some(directive=>directive.name.endsWith("-src"))&&!directives.some(directive=>directive.name==="frame-ancestors"&&directive.sources.join(" ")!=="*")}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){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)||readsFrameLocation(node.right)}if(node.type==="UnaryExpression"){return readsFrameLocation(node.argument)}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))}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 foldToString(node,sourceCode,seen=new Set){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||!visit(seen,init)?null:foldToString(init,sourceCode,seen)}if(node.type==="MemberExpression"){const element=tableElement(node,sourceCode,seen);return element===null?null:foldToString(element,sourceCode,seen)}return null}function foldToArrayExpression(node,sourceCode,seen){if(node.type==="ArrayExpression")return node;if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0||!visit(seen,init)?null:foldToArrayExpression(init,sourceCode,seen)}if(node.type==="MemberExpression"){const element=tableElement(node,sourceCode,seen);return element===null?null:foldToArrayExpression(element,sourceCode,seen)}return null}function tableElement(node,sourceCode,seen){const index=node.property;if(index.type!=="Literal")return null;const array=foldToArrayExpression(node.object,sourceCode,seen);if(array===null)return null;const element=array.elements[String(index.value)];return isNode(element)?element:null}function isNode(value){return typeof value==="object"&&value!==null}function visit(seen,node){if(seen.has(node))return false;seen.add(node);return true}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")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:{interop:{runtimes:["eslint","oxlint"]},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"}),weakFrameProtection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Frame Protection Permits Framing",cwe:"CWE-1021",description:"This X-Frame-Options value or Content-Security-Policy does not forbid framing",severity:"MEDIUM",fix:"Use X-Frame-Options: DENY / SAMEORIGIN, or CSP frame-ancestors 'none' / 'self'",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:"Iframe src origins treated as safe (self / same-origin accept relative URLs)"},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}],createOnce(context){let trustedSources;let requireFrameBusting;let detectTransparentOverlays;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let hasFrameBusting;let buildsDocumentShell;let hasDeclaredFrameProtection;let DOCUMENT_SHELL_TAGS;let weakDeclarations;let HEADER_SETTERS;const declaresFrameProtection=(value,inFrameOptionsSlot=false)=>{const text=value.toLowerCase();const ancestors=/frame-ancestors\s+([^;]+)/.exec(text);if(ancestors&&ancestors[1].trim()!=="*")return true;if(text.includes("x-frame-options")){return/x-frame-options["']?\s*[:,=]\s*["']?\s*(deny|sameorigin)\b/.test(text)}return inFrameOptionsSlot&&/^\s*(deny|sameorigin)\s*$/.test(text)};const isFrameOptionsValue=node=>{const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node){const key=(0,eslint_devkit_1.objectKeyName)(parent)?.toLowerCase()??"";if(key==="x-frame-options")return true;if(key==="value"&&parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return parent.parent.properties.some(sibling=>sibling.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(sibling)?.toLowerCase()==="key"&&sibling.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof sibling.value.value==="string"&&sibling.value.value.toLowerCase()==="x-frame-options")}return false}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(parent.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(!HEADER_SETTERS.has((0,eslint_devkit_1.propertyName)(parent.callee)?.toLowerCase()??""))return false;const index=parent.arguments.indexOf(node);if(index<1)return false;const name=parent.arguments[index-1];return name.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof name.value==="string"&&name.value.toLowerCase()==="x-frame-options"}return false};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(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{before(){const options=context.options[0]||{};({trustedSources=["self","same-origin"],requireFrameBusting=true,detectTransparentOverlays=true,trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedAnnotations,trustedOrmPatterns:[],strictMode});hasFrameBusting=false;buildsDocumentShell=false;hasDeclaredFrameProtection=false;weakDeclarations=[];DOCUMENT_SHELL_TAGS=new Set(["html","head","body"]);HEADER_SETTERS=new Set(["setheader","setrequestheader","header","set","append"])},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 srcValue="";for(const attr of attributes){if(attr.type==="JSXAttribute"&&attr.name.type==="JSXIdentifier"&&attr.name.name==="src"&&attr.value){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)??""}}}if(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"){const isFrameManipulation=node.parent.type==="AssignmentExpression"&&node.parent.left===node;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"){const inFrameOptionsSlot=isFrameOptionsValue(node);if(declaresFrameProtection(node.value,inFrameOptionsSlot)){hasDeclaredFrameProtection=true}else if(inFrameOptionsSlot||isPolicyPermittingFraming(node.value)){weakDeclarations.push(node)}}if(typeof node.value==="string"&&detectTransparentOverlays){if(hasTransparentStyles(node.value)){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}else if(isPolicyPermittingFraming(node.quasis.map(q=>q.value.raw).join(" "))){weakDeclarations.push(node)}if(detectTransparentOverlays){const text=node.quasis.map(q=>q.value.raw).join(" ");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"});return}if(hasDeclaredFrameProtection)return;for(const node of weakDeclarations){context.report({node,messageId:"weakFrameProtection"})}}}}});
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 csp_directive_1=require("../../utils/csp-directive");const resolve_binding_1=require("../../utils/resolve-binding");const FRAME_REFS=new Set(["top","self","parent","window"]);function isPolicyPermittingFraming(text){const directives=(0,csp_directive_1.parsePolicy)(text);return directives.some(directive=>(0,csp_directive_1.isFetchDirectiveName)(directive.name))&&!directives.some(directive=>directive.name==="frame-ancestors"&&directive.sources.join(" ")!=="*")}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){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)||readsFrameLocation(node.right)}if(node.type==="UnaryExpression"){return readsFrameLocation(node.argument)}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))}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 foldToString(node,sourceCode,seen=new Set){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||!visit(seen,init)?null:foldToString(init,sourceCode,seen)}if(node.type==="MemberExpression"){const element=tableElement(node,sourceCode,seen);return element===null?null:foldToString(element,sourceCode,seen)}return null}function foldToArrayExpression(node,sourceCode,seen){if(node.type==="ArrayExpression")return node;if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0||!visit(seen,init)?null:foldToArrayExpression(init,sourceCode,seen)}if(node.type==="MemberExpression"){const element=tableElement(node,sourceCode,seen);return element===null?null:foldToArrayExpression(element,sourceCode,seen)}return null}function tableElement(node,sourceCode,seen){const index=node.property;if(index.type!=="Literal")return null;const array=foldToArrayExpression(node.object,sourceCode,seen);if(array===null)return null;const element=array.elements[String(index.value)];return isNode(element)?element:null}function isNode(value){return typeof value==="object"&&value!==null}function visit(seen,node){if(seen.has(node))return false;seen.add(node);return true}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")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:{interop:{runtimes:["eslint","oxlint"]},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"}),weakFrameProtection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Frame Protection Permits Framing",cwe:"CWE-1021",description:"This X-Frame-Options value or Content-Security-Policy does not forbid framing",severity:"MEDIUM",fix:"Use X-Frame-Options: DENY / SAMEORIGIN, or CSP frame-ancestors 'none' / 'self'",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:"Iframe src origins treated as safe (self / same-origin accept relative URLs)"},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}],createOnce(context){let trustedSources;let requireFrameBusting;let detectTransparentOverlays;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let hasFrameBusting;let buildsDocumentShell;let hasDeclaredFrameProtection;let DOCUMENT_SHELL_TAGS;let weakDeclarations;let HEADER_SETTERS;const declaresFrameProtection=(value,inFrameOptionsSlot=false)=>{const text=value.toLowerCase();const ancestors=/frame-ancestors\s+([^;]+)/.exec(text);if(ancestors&&ancestors[1].trim()!=="*")return true;if(text.includes("x-frame-options")){return/x-frame-options["']?\s*[:,=]\s*["']?\s*(deny|sameorigin)\b/.test(text)}return inFrameOptionsSlot&&/^\s*(deny|sameorigin)\s*$/.test(text)};const isFrameOptionsValue=node=>{const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node){const key=(0,eslint_devkit_1.objectKeyName)(parent)?.toLowerCase()??"";if(key==="x-frame-options")return true;if(key==="value"&&parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return parent.parent.properties.some(sibling=>sibling.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(sibling)?.toLowerCase()==="key"&&sibling.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof sibling.value.value==="string"&&sibling.value.value.toLowerCase()==="x-frame-options")}return false}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(parent.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(!HEADER_SETTERS.has((0,eslint_devkit_1.propertyName)(parent.callee)?.toLowerCase()??""))return false;const index=parent.arguments.indexOf(node);if(index<1)return false;const name=parent.arguments[index-1];return name.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof name.value==="string"&&name.value.toLowerCase()==="x-frame-options"}return false};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(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{before(){const options=context.options[0]||{};({trustedSources=["self","same-origin"],requireFrameBusting=true,detectTransparentOverlays=true,trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedAnnotations,trustedOrmPatterns:[],strictMode});hasFrameBusting=false;buildsDocumentShell=false;hasDeclaredFrameProtection=false;weakDeclarations=[];DOCUMENT_SHELL_TAGS=new Set(["html","head","body"]);HEADER_SETTERS=new Set(["setheader","setrequestheader","header","set","append"])},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 srcValue="";for(const attr of attributes){if(attr.type==="JSXAttribute"&&attr.name.type==="JSXIdentifier"&&attr.name.name==="src"&&attr.value){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)??""}}}if(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"){const isFrameManipulation=node.parent.type==="AssignmentExpression"&&node.parent.left===node;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"){const inFrameOptionsSlot=isFrameOptionsValue(node);if(declaresFrameProtection(node.value,inFrameOptionsSlot)){hasDeclaredFrameProtection=true}else if(inFrameOptionsSlot||isPolicyPermittingFraming(node.value)){weakDeclarations.push(node)}}if(typeof node.value==="string"&&detectTransparentOverlays){if(hasTransparentStyles(node.value)){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}else if(isPolicyPermittingFraming(node.quasis.map(q=>q.value.raw).join(" "))){weakDeclarations.push(node)}if(detectTransparentOverlays){const text=node.quasis.map(q=>q.value.raw).join(" ");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"});return}if(hasDeclaredFrameProtection)return;for(const node of weakDeclarations){context.report({node,messageId:"weakFrameProtection"})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isCspDirectiveName=isCspDirectiveName;exports.cspSourceKeyword=cspSourceKeyword;exports.parsePolicy=parsePolicy;exports.policyGrantsKeyword=policyGrantsKeyword;exports.isCspSourceListElement=isCspSourceListElement;const CSP_DIRECTIVE_NAMES_KEBAB=["child-src","connect-src","default-src","fenced-frame-src","font-src","frame-src","img-src","manifest-src","media-src","object-src","prefetch-src","script-src","script-src-elem","script-src-attr","style-src","style-src-elem","style-src-attr","worker-src","base-uri","sandbox","form-action","frame-ancestors","navigate-to","report-uri","report-to","require-trusted-types-for","trusted-types","upgrade-insecure-requests","block-all-mixed-content","require-sri-for"];function toCamelCase(kebab){return kebab.replace(/-([a-z])/g,(_,c)=>c.toUpperCase())}const CSP_DIRECTIVE_NAMES=new Set([...CSP_DIRECTIVE_NAMES_KEBAB,...CSP_DIRECTIVE_NAMES_KEBAB.map(toCamelCase)]);function isCspDirectiveName(name){return CSP_DIRECTIVE_NAMES.has(name.toLowerCase())||CSP_DIRECTIVE_NAMES.has(name)}const CSP_KEYWORDS=new Set(["self","none","unsafe-eval","wasm-unsafe-eval","unsafe-inline","unsafe-hashes","strict-dynamic","report-sample","inline-speculation-rules","unsafe-allow-redirects"]);function cspSourceKeyword(source){const trimmed=source.trim().toLowerCase();const unquoted=trimmed.length>1&&trimmed.startsWith("'")&&trimmed.endsWith("'")?trimmed.slice(1,-1):trimmed;return CSP_KEYWORDS.has(unquoted)?unquoted:null}function parsePolicy(text){const directives=[];for(const segment of text.split(";")){const tokens=segment.trim().split(/\s+/).filter(Boolean);if(tokens.length===0)continue;if(!isCspDirectiveName(tokens[0]))continue;directives.push({name:tokens[0].toLowerCase(),sources:tokens.slice(1)})}return directives}function policyGrantsKeyword(text,keyword){return parsePolicy(text).some(directive=>directive.sources.some(source=>cspSourceKeyword(source)===keyword))}function isCspSourceListElement(node,sourceCode){const array=node.parent;if(array==null||array.type!=="ArrayExpression")return false;const owner=array.parent;if(owner.type==="Property"&&!owner.computed&&owner.value===array){const key=owner.key;if(key.type==="Identifier")return isCspDirectiveName(key.name);if(key.type==="Literal"&&typeof key.value==="string"){return isCspDirectiveName(key.value)}return false}if(owner.type==="VariableDeclarator"&&owner.id.type==="Identifier"){return isSplicedAfterDirectiveName(owner,sourceCode)}return false}function isSplicedAfterDirectiveName(declarator,sourceCode){for(const variable of sourceCode.getDeclaredVariables(declarator)){for(const reference of variable.references){if(reference.identifier.range[0]<declarator.range[1])continue;if(precedingQuasiEndsWithDirective(reference.identifier))return true}}return false}function precedingQuasiEndsWithDirective(node){let current=node;for(let depth=0;current!=null&&depth<6;depth++){const parent=current.parent;if(parent!=null&&parent.type==="TemplateLiteral"){const slot=parent.expressions.indexOf(current);const before=parent.quasis[slot].value.raw;const tokens=before.trim().split(/[\s;]+/).filter(Boolean);const last=tokens[tokens.length-1];return last!==void 0&&isCspDirectiveName(last)}current=parent}return false}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isFetchDirectiveName=isFetchDirectiveName;exports.isCspDirectiveName=isCspDirectiveName;exports.cspSourceKeyword=cspSourceKeyword;exports.parsePolicy=parsePolicy;exports.policyGrantsKeyword=policyGrantsKeyword;exports.isCspSourceListElement=isCspSourceListElement;const FETCH_DIRECTIVE_NAMES_KEBAB=["child-src","connect-src","default-src","fenced-frame-src","font-src","frame-src","img-src","manifest-src","media-src","object-src","prefetch-src","script-src","script-src-elem","script-src-attr","style-src","style-src-elem","style-src-attr","worker-src"];const CSP_DIRECTIVE_NAMES_KEBAB=[...FETCH_DIRECTIVE_NAMES_KEBAB,"base-uri","sandbox","form-action","frame-ancestors","navigate-to","report-uri","report-to","require-trusted-types-for","trusted-types","upgrade-insecure-requests","block-all-mixed-content","require-sri-for"];function toCamelCase(kebab){return kebab.replace(/-([a-z])/g,(_,c)=>c.toUpperCase())}const CSP_DIRECTIVE_NAMES=new Set([...CSP_DIRECTIVE_NAMES_KEBAB,...CSP_DIRECTIVE_NAMES_KEBAB.map(toCamelCase)]);const FETCH_DIRECTIVE_NAMES=new Set(FETCH_DIRECTIVE_NAMES_KEBAB.flatMap(name=>[name,toCamelCase(name).toLowerCase()]));function isFetchDirectiveName(name){return FETCH_DIRECTIVE_NAMES.has(name.toLowerCase())}function isCspDirectiveName(name){return CSP_DIRECTIVE_NAMES.has(name.toLowerCase())||CSP_DIRECTIVE_NAMES.has(name)}const CSP_KEYWORDS=new Set(["self","none","unsafe-eval","wasm-unsafe-eval","unsafe-inline","unsafe-hashes","strict-dynamic","report-sample","inline-speculation-rules","unsafe-allow-redirects"]);function cspSourceKeyword(source){const trimmed=source.trim().toLowerCase();const unquoted=trimmed.length>1&&trimmed.startsWith("'")&&trimmed.endsWith("'")?trimmed.slice(1,-1):trimmed;return CSP_KEYWORDS.has(unquoted)?unquoted:null}function parsePolicy(text){const directives=[];for(const segment of text.split(";")){const tokens=segment.trim().split(/\s+/).filter(Boolean);if(tokens.length===0)continue;if(!isCspDirectiveName(tokens[0]))continue;directives.push({name:tokens[0].toLowerCase(),sources:tokens.slice(1)})}return directives}function policyGrantsKeyword(text,keyword){return parsePolicy(text).some(directive=>directive.sources.some(source=>cspSourceKeyword(source)===keyword))}function isCspSourceListElement(node,sourceCode){const array=node.parent;if(array==null||array.type!=="ArrayExpression")return false;const owner=array.parent;if(owner.type==="Property"&&!owner.computed&&owner.value===array){const key=owner.key;if(key.type==="Identifier")return isCspDirectiveName(key.name);if(key.type==="Literal"&&typeof key.value==="string"){return isCspDirectiveName(key.value)}return false}if(owner.type==="VariableDeclarator"&&owner.id.type==="Identifier"){return isSplicedAfterDirectiveName(owner,sourceCode)}return false}function isSplicedAfterDirectiveName(declarator,sourceCode){for(const variable of sourceCode.getDeclaredVariables(declarator)){for(const reference of variable.references){if(reference.identifier.range[0]<declarator.range[1])continue;if(precedingQuasiEndsWithDirective(reference.identifier))return true}}return false}function precedingQuasiEndsWithDirective(node){let current=node;for(let depth=0;current!=null&&depth<6;depth++){const parent=current.parent;if(parent!=null&&parent.type==="TemplateLiteral"){const slot=parent.expressions.indexOf(current);const before=parent.quasis[slot].value.raw;const tokens=before.trim().split(/[\s;]+/).filter(Boolean);const last=tokens[tokens.length-1];return last!==void 0&&isCspDirectiveName(last)}current=parent}return false}