eslint-plugin-browser-security 1.4.1 → 2.0.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.
Files changed (56) hide show
  1. package/package.json +2 -2
  2. package/src/index.js +1 -1
  3. package/src/rules/detect-mixed-content/index.js +1 -1
  4. package/src/rules/no-allow-arbitrary-loads/index.js +1 -1
  5. package/src/rules/no-clickjacking/index.js +1 -1
  6. package/src/rules/no-client-side-auth-logic/index.js +1 -1
  7. package/src/rules/no-cookie-auth-tokens/index.js +1 -1
  8. package/src/rules/no-dynamic-service-worker-url/index.js +1 -1
  9. package/src/rules/no-eval/index.js +1 -1
  10. package/src/rules/no-filereader-innerhtml/index.js +1 -1
  11. package/src/rules/no-http-urls/index.js +1 -1
  12. package/src/rules/no-innerhtml/index.js +1 -1
  13. package/src/rules/no-insecure-redirects/index.js +1 -1
  14. package/src/rules/no-insecure-websocket/index.js +1 -1
  15. package/src/rules/no-jwt-in-storage/index.js +1 -1
  16. package/src/rules/no-missing-cors-check/index.js +1 -1
  17. package/src/rules/no-missing-csrf-protection/index.js +1 -1
  18. package/src/rules/no-missing-security-headers/index.js +1 -1
  19. package/src/rules/no-password-in-url/index.js +1 -1
  20. package/src/rules/no-permissive-cors/index.js +1 -1
  21. package/src/rules/no-postmessage-innerhtml/index.js +1 -1
  22. package/src/rules/no-postmessage-wildcard-origin/index.js +1 -1
  23. package/src/rules/no-sensitive-cookie-js/index.js +1 -1
  24. package/src/rules/no-sensitive-data-in-analytics/index.js +1 -1
  25. package/src/rules/no-sensitive-data-in-cache/index.js +1 -1
  26. package/src/rules/no-sensitive-indexeddb/index.js +1 -1
  27. package/src/rules/no-sensitive-localstorage/index.js +1 -1
  28. package/src/rules/no-sensitive-sessionstorage/index.js +1 -1
  29. package/src/rules/no-tracking-without-consent/index.js +1 -1
  30. package/src/rules/no-unencrypted-transmission/index.js +1 -1
  31. package/src/rules/no-unescaped-url-parameter/index.js +1 -1
  32. package/src/rules/no-unescaped-url-parameter/untrusted-text.js +1 -0
  33. package/src/rules/no-unescaped-url-parameter/url-shape.js +1 -0
  34. package/src/rules/no-unsafe-eval-csp/index.js +1 -1
  35. package/src/rules/no-unsafe-inline-csp/index.js +1 -1
  36. package/src/rules/no-unvalidated-deeplinks/index.js +1 -1
  37. package/src/rules/no-websocket-eval/index.js +1 -1
  38. package/src/rules/no-websocket-innerhtml/index.js +1 -1
  39. package/src/rules/no-worker-message-innerhtml/index.js +1 -1
  40. package/src/rules/require-blob-url-revocation/index.js +1 -1
  41. package/src/rules/require-cookie-secure-attrs/index.js +1 -1
  42. package/src/rules/require-csp-headers/index.js +1 -1
  43. package/src/rules/require-https-only/index.js +1 -1
  44. package/src/rules/require-mime-type-validation/index.js +1 -1
  45. package/src/rules/require-postmessage-origin-check/index.js +1 -1
  46. package/src/rules/require-url-validation/index.js +1 -1
  47. package/src/rules/require-websocket-wss/index.js +1 -1
  48. package/src/utils/analytics-sinks.js +1 -0
  49. package/src/utils/csp-directive.js +1 -0
  50. package/src/utils/dynamic-code-sinks.js +1 -0
  51. package/src/utils/express-app.js +1 -0
  52. package/src/utils/global-object.js +1 -0
  53. package/src/utils/navigation-targets.js +1 -0
  54. package/src/utils/sensitive-value-evidence.js +1 -0
  55. package/src/utils/transport-ownership.js +1 -0
  56. package/src/utils/url-taint.js +1 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCors=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");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"})}return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="setHeader"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&node.arguments[0].value==="Access-Control-Allow-Origin"&&node.arguments[1]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&node.arguments[1].value==="*"){report(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="cors"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const originProp=node.arguments[0].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==="*"){report(node)}}}}}});
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&&!receiver.computed&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&receiver.property.name==="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&&!node.callee.computed&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HEADER_METHODS.has(node.callee.property.name)&&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},hasSuggestions:true,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"}),useTextContent:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Safe DOM Methods",description:"Use textContent or sanitize input with DOMPurify",severity:"LOW",fix:"element.textContent = event.data; // For plain text\nelement.innerHTML = DOMPurify.sanitize(event.data); // For HTML",documentationLink:"https://github.com/cure53/DOMPurify"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(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&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_METHODS.has(node.callee.property.name)){for(const arg of node.arguments){if(payloadSource(arg)==="postmessage"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.callee.property.name},suggest:[{messageId:"useTextContent",fix:()=>null}]});break}}}},AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_PROPERTIES.has(node.left.property.name)){if(payloadSource(node.right)==="postmessage"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.left.property.name},suggest:[{messageId:"useTextContent",fix:()=>null}]})}}}}}});
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&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_METHODS.has(node.callee.property.name)){for(const arg of node.arguments){if(payloadSource(arg)==="postmessage"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.callee.property.name}});break}}}},AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_PROPERTIES.has(node.left.property.name)){if(payloadSource(node.right)==="postmessage"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.left.property.name}})}}}}}});
@@ -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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return}const property=node.callee.property;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||property.name!=="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
+ "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}const property=node.callee.property;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||property.name!=="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.noSensitiveCookieJs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_SENSITIVE_PATTERNS=["token","jwt","access_token","accessToken","refresh_token","refreshToken","id_token","idToken","auth","session","sessionId","session_id","password","passwd","secret","api_key","apiKey","private_key","privateKey","credential","bearer"];function isSensitiveKey(key,patterns){const lowerKey=key.toLowerCase();return patterns.some(pattern=>lowerKey.includes(pattern.toLowerCase()))}function extractCookieKey(cookieString){const match=cookieString.match(/^([^=]+)=/);return match?match[1].trim():null}exports.noSensitiveCookieJs=(0,eslint_devkit_1.createRule)({name:"no-sensitive-cookie-js",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-cookie-js.md",description:"Disallow storing sensitive data (tokens, passwords) in cookies via JavaScript",cwe:"CWE-1004",cvss:8.1},hasSuggestions:true,messages:{sensitiveCookieJs:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Cookie via JavaScript",cwe:"CWE-1004",owasp:"A02:2021",cvss:8.1,description:'Setting "{{key}}" cookie via document.cookie makes it accessible to XSS attacks. Sensitive cookies should be set server-side with HttpOnly flag.',severity:"HIGH",fix:"Set authentication cookies server-side with HttpOnly, Secure, and SameSite flags.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"}),useHttpOnlyCookie:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use HttpOnly Cookie",description:"Set cookies via server response with Set-Cookie header and HttpOnly flag",severity:"LOW",fix:'Server: res.cookie(name, value, { httpOnly: true, secure: true, sameSite: "strict" })',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},sensitivePatterns:{type:"array",items:{type:"string"},default:DEFAULT_SENSITIVE_PATTERNS}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,sensitivePatterns:DEFAULT_SENSITIVE_PATTERNS}],create(context,[options={}]){const{allowInTests=true,sensitivePatterns=DEFAULT_SENSITIVE_PATTERNS}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}return{AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return}const obj=node.left.object;const prop=node.left.property;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||obj.name!=="document"){return}if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||prop.name!=="cookie"){return}const value=node.right;let cookieKey=null;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"){cookieKey=extractCookieKey(value.value)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const firstQuasi=value.quasis[0];if(firstQuasi){cookieKey=extractCookieKey(firstQuasi.value.raw)}}if(value.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const left=value.left;if(left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof left.value==="string"){cookieKey=extractCookieKey(left.value)}}if(cookieKey&&isSensitiveKey(cookieKey,sensitivePatterns)){context.report({node,messageId:"sensitiveCookieJs",data:{key:cookieKey},suggest:[{messageId:"useHttpOnlyCookie",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveCookieJs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const sensitive_value_evidence_1=require("../../utils/sensitive-value-evidence");exports.noSensitiveCookieJs=(0,eslint_devkit_1.createRule)({name:"no-sensitive-cookie-js",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-cookie-js.md",description:"Disallow storing sensitive data (passwords, keys, regulated identifiers) in cookies via JavaScript",cwe:"CWE-1004",cvss:8.1},messages:{sensitiveCookieJs:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Cookie via JavaScript",cwe:"CWE-1004",owasp:"A02:2021",cvss:8.1,description:'Setting "{{key}}" cookie via document.cookie makes it accessible to XSS attacks. Sensitive cookies should be set server-side with HttpOnly flag.',severity:"HIGH",fix:"Set the value server-side with HttpOnly, Secure and SameSite flags \u2014 or do not put it in a cookie at all.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},sensitivePatterns:{type:"array",items:{type:"string"},default:[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS]}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,sensitivePatterns:[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS]}],create(context,[options={}]){const{allowInTests=true,sensitivePatterns=[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS]}=options;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(context.filename);if(allowInTests&&isTestFile){return{}}return{AssignmentExpression(node){if(!(0,sensitive_value_evidence_1.isDocumentCookieTarget)(node.left))return;const text=(0,sensitive_value_evidence_1.staticCookieText)(node.right,context.sourceCode);if(text===null||(0,sensitive_value_evidence_1.isCookieDeletion)(text))return;const name=(0,sensitive_value_evidence_1.cookieNameFrom)(text);if(name===null)return;if((0,sensitive_value_evidence_1.namesBearerCredential)(name))return;if(!(0,sensitive_value_evidence_1.namesNonBearerSecret)(name,sensitivePatterns))return;context.report({node,messageId:"sensitiveCookieJs",data:{key:name}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataInAnalytics=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noSensitiveDataInAnalytics=(0,eslint_devkit_1.createRule)({name:"no-sensitive-data-in-analytics",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-data-in-analytics.md",description:"Prevent PII being sent to analytics services",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in Analytics",cwe:"CWE-359",description:"Sensitive field sent to analytics - this is a privacy violation",severity:"HIGH",fix:"Remove PII from analytics tracking data",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[]},defaultOptions:[],create(context){const sensitiveFields=["email","ssn","creditcard","password","phone","address"];function report(node,field){context.report({node,messageId:"violationDetected",data:{field}})}return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="analytics"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="track"){const dataArg=node.arguments[1];if(dataArg?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){dataArg.properties.forEach(prop=>{if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const key=prop.key.name.toLowerCase();const matchedField=sensitiveFields.find(f=>key.includes(f));if(matchedField){report(prop,matchedField)}}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataInAnalytics=exports.DEFAULT_SENSITIVE_FIELDS=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const analytics_sinks_1=require("../../utils/analytics-sinks");const resolve_binding_1=require("../../utils/resolve-binding");exports.DEFAULT_SENSITIVE_FIELDS=["email","ssn","credit card","card number","creditcard","cardnumber","password","passwd","phone","address","dob","birthdate","passport","national id"];function propertyKeyName(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}exports.noSensitiveDataInAnalytics=(0,eslint_devkit_1.createRule)({name:"no-sensitive-data-in-analytics",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-data-in-analytics.md",description:"Prevent PII being sent to analytics services",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in Analytics",cwe:"CWE-359",description:"Sensitive field sent to analytics - this is a privacy violation",severity:"HIGH",fix:"Remove PII from analytics tracking data",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{sensitiveFields:{type:"array",items:{type:"string"},default:[...exports.DEFAULT_SENSITIVE_FIELDS],description:"Field names treated as PII, matched whole-word against the payload key segments"}},additionalProperties:false}]},defaultOptions:[{sensitiveFields:[...exports.DEFAULT_SENSITIVE_FIELDS]}],create(context,[options={}]){const{sensitiveFields=[...exports.DEFAULT_SENSITIVE_FIELDS]}=options;function report(node,field){context.report({node,messageId:"violationDetected",data:{field}})}function scanPayload(node,depth=0){if(depth>4)return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,context.sourceCode);if(init!==void 0)scanPayload(init,depth+1);return}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const key=propertyKeyName(property);if(key!==null&&(0,eslint_devkit_1.nameHasAnyWord)(key,sensitiveFields)){report(property,key);continue}scanPayload(property.value,depth+1)}}return{CallExpression(node){if(!(0,analytics_sinks_1.isAnalyticsTransmission)(node))return;for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;scanPayload(argument)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataInCache=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noSensitiveDataInCache=(0,eslint_devkit_1.createRule)({name:"no-sensitive-data-in-cache",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-data-in-cache.md",description:"Prevent caching sensitive data without encryption",cwe:"CWE-200",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-200",description:"Prevent caching sensitive data without encryption detected - Sensitive data in cache",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/200.html"})},schema:[]},defaultOptions:[],create(context){return{CallExpression(node){if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&["set","put","store"].includes(node.callee.property.name)){const keyArg=node.arguments[0];if(keyArg&&keyArg.type==="Literal"){const rawValue=keyArg?.value;const key=rawValue===void 0||rawValue===null?"":String(rawValue).toLowerCase();if(["password","token","credit","ssn"].some(k=>key.includes(k))){context.report({node,messageId:"violationDetected"})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataInCache=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const sensitive_value_evidence_1=require("../../utils/sensitive-value-evidence");const CACHE_WRITE_METHODS=new Set(["put","add","addAll"]);exports.noSensitiveDataInCache=(0,eslint_devkit_1.createRule)({name:"no-sensitive-data-in-cache",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-data-in-cache.md",description:"Prevent caching credential-bearing responses in the Cache Storage API",cwe:"CWE-524",cvss:5.3},messages:{sensitiveInCache:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Credential-Bearing Response in Cache Storage",cwe:"CWE-524",owasp:"A01:2021",cvss:5.3,description:'Caching "{{resource}}" in the Cache Storage API writes its response to disk, where it outlives the session and is readable by any script on the origin.',severity:"MEDIUM",fix:"Do not precache authenticated endpoints. Serve them network-only and let the server send Cache-Control: no-store.",documentationLink:"https://cwe.mitre.org/data/definitions/524.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(context.filename);if(allowInTests&&isTestFile){return{}}function resourceUrl(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Request"){const first=node.arguments[0];return first===void 0?null:(0,sensitive_value_evidence_1.resolveKeyText)(first,context.sourceCode)}return(0,sensitive_value_evidence_1.resolveKeyText)(node,context.sourceCode)}function report(node,url){if(url===null)return;const normalized=(0,sensitive_value_evidence_1.normalizeResourceKey)(url);if(!(0,sensitive_value_evidence_1.namesBearerCredential)(normalized)&&!(0,sensitive_value_evidence_1.namesNonBearerSecret)(normalized)){return}context.report({node,messageId:"sensitiveInCache",data:{resource:url}})}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const method=(0,sensitive_value_evidence_1.memberName)(node.callee,context.sourceCode);if(method===null||!CACHE_WRITE_METHODS.has(method))return;if(!(0,sensitive_value_evidence_1.isCacheStorageReceiver)(node.callee.object,context.sourceCode)){return}const first=node.arguments[0];if(first===void 0)return;if(method==="addAll"){if(first.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return;for(const element of first.elements){if(element===null)continue;if(element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;report(node,resourceUrl(element))}return}report(node,resourceUrl(first))}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveIndexeddb=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SENSITIVE_PATTERNS=[/password/i,/secret/i,/apikey/i,/api[_-]?key/i,/private[_-]?key/i,/auth[_-]?token/i,/access[_-]?token/i,/credential/i,/ssn/i,/credit[_-]?card/i,/encryption[_-]?key/i];function isSensitive(name){return SENSITIVE_PATTERNS.some(p=>p.test(name))}exports.noSensitiveIndexeddb=(0,eslint_devkit_1.createRule)({name:"no-sensitive-indexeddb",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-indexeddb.md",description:"Disallow storing sensitive data in IndexedDB",cwe:"CWE-922",cvss:7.5},hasSuggestions:true,messages:{sensitiveInIndexedDB:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in IndexedDB",cwe:"CWE-922",owasp:"A02:2021",cvss:7.5,description:'Creating IndexedDB store "{{name}}" for sensitive data. IndexedDB is accessible to XSS attacks.',severity:"HIGH",fix:"Encrypt sensitive data before storing or use server-side storage.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#local-storage"}),useEncryption:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Encrypt Sensitive Data",description:"Use Web Crypto API to encrypt data before storing",severity:"LOW",fix:"const encrypted = await crypto.subtle.encrypt(algo, key, data);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="createObjectStore"){const storeNameArg=node.arguments[0];if(storeNameArg&&storeNameArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof storeNameArg.value==="string"){if(isSensitive(storeNameArg.value)){context.report({node,messageId:"sensitiveInIndexedDB",data:{name:storeNameArg.value},suggest:[{messageId:"useEncryption",fix:()=>null}]})}}}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(node.callee.property.name==="add"||node.callee.property.name==="put")){const dataArg=node.arguments[0];if(dataArg&&dataArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of dataArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isSensitive(prop.key.name)){context.report({node,messageId:"sensitiveInIndexedDB",data:{name:prop.key.name},suggest:[{messageId:"useEncryption",fix:()=>null}]})}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveIndexeddb=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const sensitive_value_evidence_1=require("../../utils/sensitive-value-evidence");function isSensitive(name,extra){return(0,sensitive_value_evidence_1.namesNonBearerSecret)(name,[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS,...extra])||(0,sensitive_value_evidence_1.namesBearerCredential)(name)}exports.noSensitiveIndexeddb=(0,eslint_devkit_1.createRule)({name:"no-sensitive-indexeddb",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-indexeddb.md",description:"Disallow storing sensitive data in IndexedDB",cwe:"CWE-922",cvss:7.5},messages:{sensitiveInIndexedDB:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in IndexedDB",cwe:"CWE-922",owasp:"A02:2021",cvss:7.5,description:'Storing "{{name}}" in IndexedDB. IndexedDB is readable by any script on the origin, so an XSS reads it.',severity:"HIGH",fix:"Encrypt sensitive data before storing or use server-side storage.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#local-storage"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Extra terms that name a secret, added to the built-in vocabulary rather than replacing it. Matched as whole words against the store or key name, never as a substring \u2014 so `token` does not match `tokenizer`. Use this for domain secrets the built-in list cannot know about, e.g. `entitlementGrant`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,additionalPatterns:[]}],create(context,[options={}]){const{allowInTests=true,additionalPatterns=[]}=options;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(context.filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const method=(0,sensitive_value_evidence_1.memberName)(node.callee,context.sourceCode);if(method==="createObjectStore"){const nameArg=node.arguments[0];if(nameArg===void 0)return;const storeName=(0,sensitive_value_evidence_1.resolveKeyText)(nameArg,context.sourceCode);if(storeName!==null&&isSensitive(storeName,additionalPatterns)){context.report({node,messageId:"sensitiveInIndexedDB",data:{name:storeName}})}return}if(method!=="add"&&method!=="put")return;const receiver=node.callee.object;const viaWrapper=(0,sensitive_value_evidence_1.isIdbWrapperDatabase)(receiver,context.sourceCode);if(!viaWrapper&&!(0,sensitive_value_evidence_1.isIndexedDbStoreReceiver)(receiver,context.sourceCode)){return}if(viaWrapper){const storeArg=node.arguments[0];if(storeArg!==void 0){const storeName=(0,sensitive_value_evidence_1.resolveKeyText)(storeArg,context.sourceCode);if(storeName!==null&&isSensitive(storeName,additionalPatterns)){context.report({node,messageId:"sensitiveInIndexedDB",data:{name:storeName}})}}}const dataArg=viaWrapper?node.arguments[1]:node.arguments[0];if(dataArg===void 0)return;if(dataArg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of dataArg.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const key=prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.key.name:(0,sensitive_value_evidence_1.resolveKeyText)(prop.key,context.sourceCode);if(key!==null&&isSensitive(key,additionalPatterns)){context.report({node,messageId:"sensitiveInIndexedDB",data:{name:key}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveLocalstorage=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const DEFAULT_SENSITIVE_PATTERNS=["token","jwt","access_token","accessToken","refresh_token","refreshToken","id_token","idToken","auth","password","passwd","secret","api_key","apiKey","private_key","privateKey","session","sessionId","credential","bearer"];function isSensitiveKey(key,patterns){const lowerKey=key.toLowerCase();return patterns.some(pattern=>lowerKey.includes(pattern.toLowerCase()))}exports.noSensitiveLocalstorage=(0,eslint_devkit_1.createRule)({name:"no-sensitive-localstorage",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-localstorage.md",description:"Disallow storing sensitive data like tokens and passwords in localStorage",cwe:"CWE-922",cvss:5.5},hasSuggestions:true,messages:{sensitiveLocalStorage:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in localStorage",cwe:"CWE-922",description:'Storing "{{key}}" in {{storage}} is dangerous. localStorage is vulnerable to XSS attacks - any script on the page can access it.',severity:"HIGH",fix:"Use httpOnly cookies for tokens, or encrypt data before storage.",documentationLink:"https://owasp.org/www-community/vulnerabilities/Insecure_Storage"}),useHttpOnlyCookie:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use HttpOnly Cookie",description:"Store authentication tokens in httpOnly cookies instead",severity:"LOW",fix:"Set tokens via Set-Cookie header with httpOnly and secure flags.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false},sensitivePatterns:{type:"array",items:{type:"string"},default:DEFAULT_SENSITIVE_PATTERNS},checkSessionStorage:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,sensitivePatterns:DEFAULT_SENSITIVE_PATTERNS,checkSessionStorage:true}],create(context,[options={}]){const{allowInTests=false,sensitivePatterns=DEFAULT_SENSITIVE_PATTERNS,checkSessionStorage=true}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const storageObjects=["localStorage"];if(checkSessionStorage){storageObjects.push("sessionStorage")}return{CallExpression(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&storageObjects.includes(callee.object.name)&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="setItem"){const keyArg=node.arguments[0];if(!keyArg){return}const keyValue=(0,resolve_binding_1.resolveStringKey)(keyArg,context.sourceCode);if(keyValue&&isSensitiveKey(keyValue,sensitivePatterns)){context.report({node,messageId:"sensitiveLocalStorage",data:{key:keyValue,storage:callee.object.name},suggest:[{messageId:"useHttpOnlyCookie",fix:()=>null}]})}}},AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return}const obj=node.left.object;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!storageObjects.includes(obj.name)){return}const keyValue=node.left.computed?(0,resolve_binding_1.resolveStringKey)(node.left.property,context.sourceCode):node.left.property.name;if(keyValue&&isSensitiveKey(keyValue,sensitivePatterns)){context.report({node,messageId:"sensitiveLocalStorage",data:{key:keyValue,storage:obj.name},suggest:[{messageId:"useHttpOnlyCookie",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveLocalstorage=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const sensitive_value_evidence_1=require("../../utils/sensitive-value-evidence");exports.noSensitiveLocalstorage=(0,eslint_devkit_1.createRule)({name:"no-sensitive-localstorage",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-localstorage.md",description:"Disallow storing sensitive data like passwords and keys in localStorage",cwe:"CWE-922",cvss:5.5},messages:{sensitiveLocalStorage:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in localStorage",cwe:"CWE-922",description:'Storing "{{key}}" in {{storage}} is dangerous. {{storage}} is readable by every script on the page, so any XSS reads it.',severity:"HIGH",fix:"Keep the secret server-side, or derive a short-lived value the client can hold instead.",documentationLink:"https://owasp.org/www-community/vulnerabilities/Insecure_Storage"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false},sensitivePatterns:{type:"array",items:{type:"string"},default:[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS]},checkSessionStorage:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,sensitivePatterns:[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS],checkSessionStorage:false}],create(context,[options={}]){const{allowInTests=false,sensitivePatterns=[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS],checkSessionStorage=false}=options;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename);if(isTestFile){return{}}const storageObjects=new Set(["localStorage"]);if(checkSessionStorage){storageObjects.add("sessionStorage")}function check(node,storage,key,valueNode){if(key===null)return;if((0,sensitive_value_evidence_1.namesBearerCredential)(key)||(0,sensitive_value_evidence_1.hasProvableJwtValue)(valueNode,context.sourceCode)){return}if(!(0,sensitive_value_evidence_1.namesNonBearerSecret)(key,sensitivePatterns))return;context.report({node,messageId:"sensitiveLocalStorage",data:{key,storage}})}return{CallExpression(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if((0,sensitive_value_evidence_1.memberName)(callee,context.sourceCode)!=="setItem")return;const storage=(0,sensitive_value_evidence_1.resolveStorageArea)(callee.object,context.sourceCode,storageObjects);if(storage===null)return;const keyArg=node.arguments[0];const valueArg=node.arguments[1];if(keyArg===void 0||valueArg===void 0)return;check(node,storage,(0,sensitive_value_evidence_1.resolveKeyText)(keyArg,context.sourceCode),valueArg)},AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const storage=(0,sensitive_value_evidence_1.resolveStorageArea)(node.left.object,context.sourceCode,storageObjects);if(storage===null)return;const key=node.left.computed?(0,sensitive_value_evidence_1.resolveKeyText)(node.left.property,context.sourceCode):(0,sensitive_value_evidence_1.memberName)(node.left);check(node,storage,key,node.right)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveSessionstorage=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SENSITIVE_PATTERNS=[/password/i,/passwd/i,/secret/i,/apikey/i,/api[_-]?key/i,/private[_-]?key/i,/auth[_-]?token/i,/access[_-]?token/i,/refresh[_-]?token/i,/bearer/i,/credential/i,/ssn/i,/social[_-]?security/i,/credit[_-]?card/i,/card[_-]?number/i,/cvv/i,/cvc/i,/pin/i,/encryption[_-]?key/i];function isSensitiveKey(key,additionalPatterns=[]){const allPatterns=[...SENSITIVE_PATTERNS,...additionalPatterns.map(p=>new RegExp(p,"i"))];return allPatterns.some(pattern=>pattern.test(key))}exports.noSensitiveSessionstorage=(0,eslint_devkit_1.createRule)({name:"no-sensitive-sessionstorage",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-sessionstorage.md",description:"Disallow storing sensitive data in sessionStorage",cwe:"CWE-922",cvss:7.5},hasSuggestions:true,messages:{sensitiveInSessionStorage:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in sessionStorage",cwe:"CWE-922",owasp:"A02:2021",cvss:7.5,description:'Storing sensitive data "{{key}}" in sessionStorage exposes it to XSS attacks. Any malicious script can read sessionStorage.',severity:"HIGH",fix:"Store sensitive data in HttpOnly cookies or use secure server-side sessions.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#local-storage"}),useSecureStorage:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Secure Storage",description:"Use HttpOnly cookies or server-side sessions",severity:"LOW",fix:'Server: res.cookie("session", value, { httpOnly: true, secure: true })',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},additionalPatterns:{type:"array",items:{type:"string"},description:"Extra key-name patterns to treat as sensitive"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true,additionalPatterns=[]}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="sessionStorage"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="setItem"){const keyArg=node.arguments[0];if(!keyArg)return;let keyValue=null;if(keyArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof keyArg.value==="string"){keyValue=keyArg.value}else if(keyArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){keyValue=keyArg.name}if(keyValue&&isSensitiveKey(keyValue,additionalPatterns)){context.report({node,messageId:"sensitiveInSessionStorage",data:{key:keyValue},suggest:[{messageId:"useSecureStorage",fix:()=>null}]})}}},AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const obj=node.left.object;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||obj.name!=="sessionStorage"){return}let keyValue=null;if(node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.left.property.value==="string"){keyValue=node.left.property.value}else if(node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){keyValue=node.left.property.name}if(keyValue&&isSensitiveKey(keyValue,additionalPatterns)){context.report({node,messageId:"sensitiveInSessionStorage",data:{key:keyValue},suggest:[{messageId:"useSecureStorage",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveSessionstorage=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const sensitive_value_evidence_1=require("../../utils/sensitive-value-evidence");const SESSION_STORAGE=new Set(["sessionStorage"]);exports.noSensitiveSessionstorage=(0,eslint_devkit_1.createRule)({name:"no-sensitive-sessionstorage",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-sensitive-sessionstorage.md",description:"Disallow storing sensitive data in sessionStorage",cwe:"CWE-922",cvss:7.5},messages:{sensitiveInSessionStorage:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in sessionStorage",cwe:"CWE-922",owasp:"A02:2021",cvss:7.5,description:'Storing sensitive data "{{key}}" in sessionStorage exposes it to XSS attacks. Any malicious script can read sessionStorage.',severity:"HIGH",fix:"Store sensitive data in HttpOnly cookies or use secure server-side sessions.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#local-storage"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Extra whole-word key terms to treat as sensitive"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,additionalPatterns:[]}],create(context,[options={}]){const{allowInTests=true,additionalPatterns=[]}=options;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(context.filename);if(allowInTests&&isTestFile){return{}}function check(node,key,valueNode){if(key===null)return;if((0,sensitive_value_evidence_1.namesBearerCredential)(key)||(0,sensitive_value_evidence_1.hasProvableJwtValue)(valueNode,context.sourceCode)){return}if(!(0,sensitive_value_evidence_1.namesNonBearerSecret)(key,[...sensitive_value_evidence_1.NON_BEARER_SECRET_TERMS,...additionalPatterns]))return;context.report({node,messageId:"sensitiveInSessionStorage",data:{key}})}return{CallExpression(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if((0,sensitive_value_evidence_1.memberName)(callee,context.sourceCode)!=="setItem")return;if((0,sensitive_value_evidence_1.resolveStorageArea)(callee.object,context.sourceCode,SESSION_STORAGE)===null)return;const keyArg=node.arguments[0];const valueArg=node.arguments[1];if(keyArg===void 0||valueArg===void 0)return;check(node,(0,sensitive_value_evidence_1.resolveKeyText)(keyArg,context.sourceCode),valueArg)},AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if((0,sensitive_value_evidence_1.resolveStorageArea)(node.left.object,context.sourceCode,SESSION_STORAGE)===null){return}const key=node.left.computed?(0,sensitive_value_evidence_1.resolveKeyText)(node.left.property,context.sourceCode):(0,sensitive_value_evidence_1.memberName)(node.left);check(node,key,node.right)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTrackingWithoutConsent=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noTrackingWithoutConsent=(0,eslint_devkit_1.createRule)({name:"no-tracking-without-consent",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-tracking-without-consent.md",description:"Require consent before analytics tracking",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Tracking Without Consent",cwe:"CWE-359",description:"Analytics tracking without consent check - violates privacy regulations",severity:"MEDIUM",fix:"Wrap tracking calls in consent check: if (hasConsent) { analytics.track(...) }",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}function isInsideConsentCheck(node){let current=node.parent;while(current){if(current.type==="IfStatement"){return true}if(current.type==="ConditionalExpression"){return true}current=current.parent}return false}return{CallExpression(node){if(node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="analytics"&&node.callee.property.type==="Identifier"&&["track","identify","page"].includes(node.callee.property.name)){if(!isInsideConsentCheck(node)){report(node)}}if(node.callee.type==="Identifier"&&node.callee.name==="gtag"){if(!isInsideConsentCheck(node)){report(node)}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTrackingWithoutConsent=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const analytics_sinks_1=require("../../utils/analytics-sinks");const DEFAULT_CONSENT_IDENTIFIERS=["consent","gdpr","optin","cookiesaccepted","trackingallowed"];function normalize(name){return name.toLowerCase().replace(/[^a-z0-9]/g,"")}const DEFAULT_ANALYTICS_METHODS=["track","identify","page"];exports.noTrackingWithoutConsent=(0,eslint_devkit_1.createRule)({name:"no-tracking-without-consent",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-tracking-without-consent.md",description:"Require consent before analytics tracking",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Tracking Without Consent",cwe:"CWE-359",description:"Analytics tracking without consent check - violates privacy regulations",severity:"MEDIUM",fix:"Wrap tracking calls in consent check: if (hasConsent) { analytics.track(...) }",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consentIdentifiers:{type:"array",items:{type:"string"},default:DEFAULT_CONSENT_IDENTIFIERS,description:"Words that mark an identifier as a consent flag; replaces the default vocabulary"},analyticsMethods:{type:"array",items:{type:"string"},default:DEFAULT_ANALYTICS_METHODS,description:"Method names on an analytics client that count as a tracking call"}},additionalProperties:false}]},defaultOptions:[{consentIdentifiers:DEFAULT_CONSENT_IDENTIFIERS,analyticsMethods:DEFAULT_ANALYTICS_METHODS}],create(context,[options={}]){const{consentIdentifiers=DEFAULT_CONSENT_IDENTIFIERS,analyticsMethods=DEFAULT_ANALYTICS_METHODS}=options;const words=consentIdentifiers.map(normalize);const methods=analyticsMethods;function report(node){context.report({node,messageId:"violationDetected"})}function mentionsConsent(node,depth=0){if(depth>8)return false;switch(node.type){case"Identifier":return words.some(w=>normalize(node.name).includes(w));case"MemberExpression":return mentionsConsent(node.object,depth+1)||!node.computed&&mentionsConsent(node.property,depth+1);case"CallExpression":return mentionsConsent(node.callee,depth+1);case"UnaryExpression":return mentionsConsent(node.argument,depth+1);case"LogicalExpression":case"BinaryExpression":return mentionsConsent(node.left,depth+1)||mentionsConsent(node.right,depth+1);case"AwaitExpression":return mentionsConsent(node.argument,depth+1);default:return false}}function analyzeTest(test){let negated=false;let current=test;while(current.type==="UnaryExpression"&&current.operator==="!"){negated=!negated;current=current.argument}if(current.type==="BinaryExpression"&&(current.operator==="==="||current.operator==="==")&&current.right.type==="Literal"&&current.right.value===false){negated=!negated;current=current.left}return{consent:mentionsConsent(current),negated}}function within(node,container){return node.range[0]>=container.range[0]&&node.range[1]<=container.range[1]}function isConsentGranted(node){let child=node;let current=node.parent;while(current){if(current.type==="IfStatement"){const{consent,negated}=analyzeTest(current.test);if(consent){const inConsequent=within(child,current.consequent);if(inConsequent?!negated:negated)return true}}else if(current.type==="ConditionalExpression"){const{consent,negated}=analyzeTest(current.test);if(consent){const inConsequent=within(child,current.consequent);if(inConsequent?!negated:negated)return true}}else if(current.type==="LogicalExpression"&&current.operator==="&&"&&current.right===child){const{consent,negated}=analyzeTest(current.left);if(consent&&!negated)return true}else if(current.type==="BlockStatement"||current.type==="Program"){if(guardedByEarlyExit(current,child))return true}child=current;current=current.parent}return false}function guardedByEarlyExit(block,child){for(const statement of block.body){if(statement.range[0]>=child.range[0])break;if(statement.type!=="IfStatement")continue;const{consent,negated}=analyzeTest(statement.test);if(!consent||!negated)continue;if(exitsUnconditionally(statement.consequent))return true}return false}function exitsUnconditionally(branch){if(branch.type==="ReturnStatement"||branch.type==="ThrowStatement"){return true}return branch.type==="BlockStatement"&&branch.body.some(s=>s.type==="ReturnStatement"||s.type==="ThrowStatement")}return{CallExpression(node){if((0,analytics_sinks_1.isAnalyticsTransmission)(node,methods)&&!isConsentGranted(node)){report(node)}}}}});
@@ -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=["http://","ws://","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,secureAlternatives){const lowerValue=value.toLowerCase();for(const protocol of insecureProtocols){const lowerProtocol=protocol.toLowerCase();if(lowerValue.includes(lowerProtocol)){const secureAlternative=secureAlternatives[lowerProtocol];if(secureAlternative){if(!lowerValue.includes(secureAlternative.toLowerCase())){return{isInsecure:true,protocol}}}else{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&&parent.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&INSPECTION_METHODS.has(parent.callee.property.name)){if(WRITES_SECOND_ARGUMENT.has(parent.callee.property.name)){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&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(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(matchesIgnorePattern(text,ignorePatterns)){return}const{isInsecure,protocol}=containsInsecureProtocol(value,protocolsToCheck,secureAlternativesToUse);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,secureAlternativesToUse);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}}});
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&&parent.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&INSPECTION_METHODS.has(parent.callee.property.name)){if(WRITES_SECOND_ARGUMENT.has(parent.callee.property.name)){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(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}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnescapedUrlParameter=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function isInsideEncodingCall(node,sourceCode,trustedLibraries){let current=node;while(current){if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="Identifier"){const calleeName=callee.name;if(["encodeURIComponent","encodeURI","escape"].includes(calleeName)){return true}}if(callee.type==="MemberExpression"){const object=callee.object;if(object.type==="Identifier"){const objectName=object.name.toLowerCase();if(trustedLibraries.some(lib=>objectName.includes(lib.toLowerCase()))){return true}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,ignorePatterns){return ignorePatterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}function isUrlConstruction(node,sourceCode){let text=sourceCode.getText(node);if(node.type==="TemplateLiteral"){text=node.quasis.map(q=>q.value.raw).join("")}const urlPatterns=[/\bhttps?:\/\//,/\bnew\s+URL\s*\(/,/\burl\s*[=:]\s*/,/\burl\s*\+/,/\bwindow\.location/,/\blocation\.href/,/\bwindow\.open\s*\(/,/\?[^=]+=/];return urlPatterns.some(pattern=>pattern.test(text))}exports.noUnescapedUrlParameter=(0,eslint_devkit_2.createRule)({name:"no-unescaped-url-parameter",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unescaped-url-parameter.md",description:"Detects unescaped URL parameters",cwe:"CWE-79",cvss:6.1},hasSuggestions:true,messages:{unescapedUrlParameter:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unescaped URL Parameter",cwe:"CWE-79",description:"Unescaped URL parameter detected: {{parameter}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/79.html"}),useEncodeURIComponent:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use encodeURIComponent",description:"Use encodeURIComponent for URL params",severity:"LOW",fix:"`https://example.com?q=${encodeURIComponent(param)}`",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent"}),useURLSearchParams:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use URLSearchParams",description:"Use URLSearchParams for safe URL construction",severity:"LOW",fix:"new URLSearchParams({ q: param }).toString()",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unescaped URL parameters in test files"},trustedLibraries:{type:"array",items:{type:"string"},default:["url","querystring"],description:"Trusted URL construction libraries"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,trustedLibraries:["url","querystring"],ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,trustedLibraries=["url","querystring"],ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);const sourceCode=context.sourceCode;function checkTemplateLiteral(node){if(isTestFile){return}if(!isUrlConstruction(node,sourceCode)){return}for(const expression of node.expressions){const text=sourceCode.getText(expression);if(matchesIgnorePattern(text,ignorePatterns)){continue}if(isInsideEncodingCall(expression,sourceCode,trustedLibraries)){continue}const userInputPatterns=[/\breq\.(query|params|body|headers|cookies)/,/\brequest\.(query|params|body)/,/\buserInput\b/i,/\binput\b/i,/\bsearchParams\b/,/\bparam\b/i];const fullText=sourceCode.getText(node);const exprText=sourceCode.getText(expression);const isUserInput=userInputPatterns.some(pattern=>pattern.test(text))||userInputPatterns.some(pattern=>pattern.test(fullText))||userInputPatterns.some(pattern=>pattern.test(exprText))||expression.type==="MemberExpression"&&userInputPatterns.some(pattern=>{return pattern.test(exprText)});if(isUserInput){context.report({node:expression,messageId:"unescapedUrlParameter",data:{parameter:text,safeAlternative:`Use encodeURIComponent() or URLSearchParams: const url = \`https://example.com?q=\${encodeURIComponent(${text})}\`;`},suggest:[{messageId:"useEncodeURIComponent",fix:_fixer=>null},{messageId:"useURLSearchParams",fix:_fixer=>null}]})}}}function checkBinaryExpression(node){if(isTestFile){return}if(node.operator==="+"){if(!isUrlConstruction(node,sourceCode)){return}if(node.right.type!=="Literal"){const rightText=sourceCode.getText(node.right);if(matchesIgnorePattern(rightText,ignorePatterns)){return}if(isInsideEncodingCall(node.right,sourceCode,trustedLibraries)){return}const userInputPatterns=[/\breq\.(query|params|body)/,/\brequest\.(query|params|body)/,/\buserInput\b/,/\binput\b/];const isUserInput=userInputPatterns.some(pattern=>pattern.test(rightText));if(isUserInput){context.report({node:node.right,messageId:"unescapedUrlParameter",data:{parameter:rightText,safeAlternative:`Use encodeURIComponent(): ${sourceCode.getText(node.left)} + encodeURIComponent(${rightText})`},suggest:[{messageId:"useEncodeURIComponent",fix:_fixer=>null}]})}}}}function isUserControlled(node,visited=new Set){const text=sourceCode.getText(node);const patterns=[/\breq\.(query|params|body|headers|cookies)/,/\brequest\.(query|params|body)/,/\buserInput\b/i,/\binput\b/i,/\bsearchParams\b/,/\bparam\b/i,/\breturnUrl\b/i,/\burl\b/i,/\bredirect\b/i,/\bnext\b/i];if(patterns.some(p=>p.test(text)))return true;if(node.type==="Identifier"){if(visited.has(node.name))return false;visited.add(node.name);const scope=sourceCode.getScope(node);const variable=scope.variables.find(v=>v.name===node.name);if(variable&&variable.defs.length>0){const def=variable.defs[0];if(def.type==="Variable"&&def.node.init){const init=def.node.init;if(isUserControlled(init,visited))return true;if(init.type==="TemplateLiteral"){return init.expressions.some(expr=>isUserControlled(expr,visited))}if(init.type==="BinaryExpression"){return isUserControlled(init.left,visited)||isUserControlled(init.right,visited)}}}}return false}return{TemplateLiteral:checkTemplateLiteral,BinaryExpression:checkBinaryExpression,AssignmentExpression(node){if(isTestFile)return;const left=node.left;let isLocationAssignment=false;if(left.type==="MemberExpression"){const objectName=left.object.type==="Identifier"?left.object.name:left.object.type==="MemberExpression"?sourceCode.getText(left.object):"";const propName=left.property.type==="Identifier"?left.property.name:"";if(objectName==="window"&&propName==="location"||propName==="href"&&objectName.includes("location")){isLocationAssignment=true}}else if(left.type==="Identifier"&&left.name==="location"){isLocationAssignment=true}if(isLocationAssignment){const right=node.right;const rightText=sourceCode.getText(right);if(right.type==="TemplateLiteral"||right.type==="BinaryExpression"){return}if(matchesIgnorePattern(rightText,ignorePatterns))return;if(isInsideEncodingCall(right,sourceCode,trustedLibraries))return;if(isUserControlled(right)){context.report({node:right,messageId:"unescapedUrlParameter",data:{parameter:rightText,safeAlternative:"Validate and encode URL before redirecting"}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnescapedUrlParameter=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const untrusted_text_1=require("./untrusted-text");const url_shape_1=require("./url-shape");const DEFAULT_TRUSTED_LIBRARIES=["url","querystring"];const URL_SINK_FUNCTIONS=new Set(["fetch"]);const URL_SINK_CONSTRUCTORS=new Set(["URL","Request"]);const XHR_OPEN_URL_INDEX=1;const URL_ATTRIBUTES=new Set(["href","src","action","formAction","poster"]);const HTTP_CLIENT_MODULES=new Set(["axios","ky"]);exports.noUnescapedUrlParameter=(0,eslint_devkit_1.createRule)({name:"no-unescaped-url-parameter",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unescaped-url-parameter.md",description:"Detects unescaped URL parameters",cwe:"CWE-79",cvss:6.1},messages:{unescapedUrlParameter:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unescaped URL Parameter",cwe:"CWE-79",description:"Unescaped URL parameter detected: {{parameter}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/79.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unescaped URL parameters in test files"},trustedLibraries:{type:"array",items:{type:"string"},default:["url","querystring"],description:"Modules whose exports produce already-encoded URL text"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,trustedLibraries:["url","querystring"],ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,trustedLibraries=DEFAULT_TRUSTED_LIBRARIES,ignorePatterns=[]}=options;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename);if(isTestFile)return{};const sourceCode=context.sourceCode;const trusted=new Set(trustedLibraries);const ignoreRegexes=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns,"i");function isTrustedLibraryCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node));if(binding===void 0)return false;const module=binding.module.replace(/^node:/,"");return trusted.has(module)}function isHttpClientCall(node){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node));return binding!==void 0&&HTTP_CLIENT_MODULES.has(binding.module)}function isUnshadowedGlobal(node,names){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!names.has(node.name)){return false}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)return variable.defs.length===0}return true}function isUrlSinkPosition(node){const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.JSXExpressionContainer){const attribute=parent.parent;return attribute?.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute&&attribute.name.type===eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier&&URL_ATTRIBUTES.has(attribute.name.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return parent.arguments[0]===node&&isUnshadowedGlobal(parent.callee,URL_SINK_CONSTRUCTORS)}if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(parent.arguments[0]===node&&isUnshadowedGlobal(parent.callee,URL_SINK_FUNCTIONS)){return true}if(parent.arguments[0]===node&&isHttpClientCall(parent))return true;return parent.arguments[XHR_OPEN_URL_INDEX]===node&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!parent.callee.computed&&parent.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.callee.property.name==="open"}function reachesUrlSink(node){if(isUrlSinkPosition(node))return true;const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}return sourceCode.getDeclaredVariables(declarator).some(variable=>variable.references.filter(r=>r.isWrite()).length===1&&variable.references.some(reference=>!reference.isWrite()&&isUrlSinkPosition(reference.identifier)))}function isInnerConcatenation(node){const parent=node.parent;return parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&parent.operator==="+"}function check(node){const shape=(0,url_shape_1.urlShape)(node,sourceCode);const kind=(0,url_shape_1.urlKind)(shape.text);if(kind===null)return;if(kind==="relative"&&!reachesUrlSink(node))return;for(const hole of shape.holes){if(!(0,url_shape_1.isEncodingPosition)(shape,hole))continue;if(isTrustedLibraryCall(hole.expression))continue;const text=sourceCode.getText(hole.expression);if(ignoreRegexes.some(regex=>regex.test(text)))continue;if(!(0,untrusted_text_1.carriesUntrustedText)(hole.expression,sourceCode))continue;context.report({node:hole.expression,messageId:"unescapedUrlParameter",data:{parameter:text,safeAlternative:`Wrap it: encodeURIComponent(${text}) \u2014 or build the query with URLSearchParams.`}})}}return{TemplateLiteral(node){if(isInnerConcatenation(node))return;const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return}check(node)},BinaryExpression(node){if(node.operator!=="+")return;if(isInnerConcatenation(node))return;check(node)}}}});
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.carriesUntrustedText=carriesUntrustedText;const eslint_devkit_1=require("@interlace/eslint-devkit");const url_taint_1=require("../../utils/url-taint");const TEXT_PRESERVING_METHODS=new Set([...url_taint_1.STEERABILITY_PRESERVING_METHODS,"join","concat","padStart","padEnd","repeat"]);const DOM_TEXT_PROPS=new Set(["value","textContent","innerText"]);const DOM_QUERY_METHODS=new Set(["getElementById","querySelector","querySelectorAll","getElementsByName","getElementsByClassName","getElementsByTagName","closest"]);const DOCUMENT_GLOBALS=new Set(["document"]);const REACT_MODULES=new Set(["react","preact/hooks"]);const EVENT_TARGET_PROPS=new Set(["target","currentTarget"]);function staticProperty(node){if(!node.computed){return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:null}return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"?node.property.value:null}function isUnshadowedGlobal(node,names,sourceCode){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!names.has(node.name)){return false}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)return variable.defs.length===0}return true}function parameterDefinition(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;const def=variable.defs[0];if(def===void 0||def.type!=="Parameter")return null;return{owner:def.node,parameter:def.name}}return null}function isHandlerFunction(fn){const parent=fn.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!parent.callee.computed&&parent.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.callee.property.name==="addEventListener"){return true}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.JSXExpressionContainer){return parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute}return parent?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===fn&&parent.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression}function isReactRef(node,sourceCode,seen){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node));return binding!==void 0&&REACT_MODULES.has(binding.module)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(seen.has(node.name))return false;seen.add(node.name);const init=(0,url_taint_1.resolveBoundInitializer)(node,sourceCode);return init!==void 0&&isReactRef(init,sourceCode,seen)}function isDomElement(node,sourceCode,seen){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const method=staticProperty(callee);if(method===null||!DOM_QUERY_METHODS.has(method))return false;return isUnshadowedGlobal(callee.object,DOCUMENT_GLOBALS,sourceCode)||isDomElement(callee.object,sourceCode,seen)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if(node.computed&&node.property.type!==eslint_devkit_1.AST_NODE_TYPES.Literal){return isDomElement(node.object,sourceCode,seen)}const property=staticProperty(node);if(property===null)return isDomElement(node.object,sourceCode,seen);if(property==="current"){return isReactRef(node.object,sourceCode,seen)}if(!EVENT_TARGET_PROPS.has(property))return false;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const definition=parameterDefinition(node.object,sourceCode);return definition!==null&&isHandlerFunction(definition.owner)}case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(seen.has(node.name))return false;seen.add(node.name);const init=(0,url_taint_1.resolveBoundInitializer)(node,sourceCode);return init!==void 0&&isDomElement(init,sourceCode,seen)}default:return false}}const FORM_DATA_CONSTRUCTORS=new Set(["FormData"]);const FORM_DATA_READERS=new Set(["get","getAll"]);function isFormData(node,sourceCode,seen){if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return isUnshadowedGlobal(node.callee,FORM_DATA_CONSTRUCTORS,sourceCode)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(seen.has(node.name))return false;seen.add(node.name);const init=(0,url_taint_1.resolveBoundInitializer)(node,sourceCode);return init!==void 0&&isFormData(init,sourceCode,seen)}function isFormDataRead(node,sourceCode,seen){const callee=node.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&FORM_DATA_READERS.has(callee.property.name)&&isFormData(callee.object,sourceCode,new Set(seen))}function isExportedDeclaration(node){const parent=node.parent;return parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration||parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExportDefaultDeclaration}function isExportedFunction(fn){if(isExportedDeclaration(fn))return true;const parent=fn.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===fn){return isExportedDeclaration(parent.parent)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition||parent?.type===eslint_devkit_1.AST_NODE_TYPES.PropertyDefinition){return isExportedDeclaration(parent.parent.parent)}return false}function isUnknowableParameter(node,sourceCode){const definition=parameterDefinition(node,sourceCode);if(definition===null||!isExportedFunction(definition.owner)){return false}return!hasClosedType(definition.parameter.typeAnnotation?.typeAnnotation)}function hasClosedType(annotation){if(annotation===void 0)return false;switch(annotation.type){case eslint_devkit_1.AST_NODE_TYPES.TSLiteralType:return annotation.literal.type===eslint_devkit_1.AST_NODE_TYPES.Literal;case eslint_devkit_1.AST_NODE_TYPES.TSNumberKeyword:case eslint_devkit_1.AST_NODE_TYPES.TSBooleanKeyword:case eslint_devkit_1.AST_NODE_TYPES.TSBigIntKeyword:return true;case eslint_devkit_1.AST_NODE_TYPES.TSUnionType:return annotation.types.every(hasClosedType);default:return false}}function isArithmetic(node){const isNumericLiteral=n=>n.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof n.value==="number";const isTextual=n=>n.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof n.value==="string"||n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral;const left=node.left;return(isNumericLiteral(left)||isNumericLiteral(node.right))&&!isTextual(left)&&!isTextual(node.right)}function carriesUntrustedText(node,sourceCode,seen=new Set){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if((0,url_taint_1.isAttackerSteerableUrl)(node,sourceCode))return true;const property=staticProperty(node);return property!==null&&DOM_TEXT_PROPS.has(property)&&isDomElement(node.object,sourceCode,new Set(seen))}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{if((0,url_taint_1.isAttackerSteerableUrl)(node,sourceCode))return true;if(isFormDataRead(node,sourceCode,seen))return true;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TEXT_PRESERVING_METHODS.has(callee.property.name)){return carriesUntrustedText(callee.object,sourceCode,seen)}const[first]=node.arguments;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&url_taint_1.STEERABILITY_PRESERVING_FUNCTIONS.has(callee.name)&&first!==void 0&&first.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return carriesUntrustedText(first,sourceCode,seen)}return false}case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(seen.has(node.name))return false;seen.add(node.name);const init=(0,url_taint_1.resolveBoundInitializer)(node,sourceCode);if(init!==void 0){return carriesUntrustedText(init,sourceCode,seen)}return isUnknowableParameter(node,sourceCode)}case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return node.operator==="+"&&!isArithmetic(node)&&(carriesUntrustedText(node.left,sourceCode,seen)||carriesUntrustedText(node.right,sourceCode,seen));case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>carriesUntrustedText(expression,sourceCode,seen));case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return carriesUntrustedText(node.left,sourceCode,seen)||carriesUntrustedText(node.right,sourceCode,seen);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return carriesUntrustedText(node.consequent,sourceCode,seen)||carriesUntrustedText(node.alternate,sourceCode,seen);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:case eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression:return carriesUntrustedText(node.expression,sourceCode,seen);case eslint_devkit_1.AST_NODE_TYPES.ChainExpression:return carriesUntrustedText(node.expression,sourceCode,seen);case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:return carriesUntrustedText(node.argument,sourceCode,seen);default:return false}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.urlShape=urlShape;exports.urlKind=urlKind;exports.isEncodingPosition=isEncodingPosition;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const AUTHORITY_PREFIX=/^(?:[a-z][a-z0-9+.-]*:)?\/\//i;const RELATIVE_PREFIX=/^[./?#]/;function collect(node,sourceCode,out){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){node.quasis.forEach((quasi,index)=>{out.text+=quasi.value.cooked;const expression=node.expressions[index];if(expression!==void 0){out.holes.push({expression,offset:out.text.length})}});return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){collect(node.left,sourceCode,out);collect(node.right,sourceCode,out);return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){out.text+=node.value;return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);if(init!==void 0&&init.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof init.value==="string"){out.text+=init.value;return}}out.holes.push({expression:node,offset:out.text.length})}function urlShape(node,sourceCode){const out={text:"",holes:[]};collect(node,sourceCode,out);return out}function urlKind(text){if(AUTHORITY_PREFIX.test(text))return"absolute";if(RELATIVE_PREFIX.test(text))return"relative";return null}function isEncodingPosition(shape,hole){const authority=AUTHORITY_PREFIX.exec(shape.text);const from=authority===null?0:authority[0].length;for(let index=from;index<shape.text.length;index+=1){const character=shape.text[index];if(character!=="/"&&character!=="?"&&character!=="#")continue;return index<hole.offset}return false}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeEvalCsp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noUnsafeEvalCsp=(0,eslint_devkit_1.createRule)({name:"no-unsafe-eval-csp",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unsafe-eval-csp.md",description:"Disallow 'unsafe-eval' in Content Security Policy",cwe:"CWE-95",cvss:8.1},hasSuggestions:true,messages:{unsafeEval:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-eval' Detected",cwe:"CWE-95",owasp:"A03:2021",cvss:8.1,description:"'unsafe-eval' in CSP allows eval(), new Function(), and setTimeout(string). This enables code injection attacks.",severity:"HIGH",fix:"Remove 'unsafe-eval' and refactor code to avoid eval-like patterns.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src"}),removeUnsafeEval:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Remove 'unsafe-eval'",description:"Refactor code to avoid eval() and remove unsafe-eval from CSP",severity:"LOW",fix:"script-src 'self'; // Remove 'unsafe-eval'",documentationLink:"https://web.dev/strict-csp/"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const UNSAFE_EVAL_PATTERN=/'unsafe-eval'/gi;function checkForUnsafeEval(node,value){if(UNSAFE_EVAL_PATTERN.test(value)){context.report({node,messageId:"unsafeEval",suggest:[{messageId:"removeUnsafeEval",fix:()=>null}]})}}return{Literal(node){if(typeof node.value==="string"){checkForUnsafeEval(node,node.value)}},TemplateLiteral(node){const value=node.quasis.map(q=>q.value.raw).join("");checkForUnsafeEval(node,value)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeEvalCsp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const csp_directive_1=require("../../utils/csp-directive");exports.noUnsafeEvalCsp=(0,eslint_devkit_1.createRule)({name:"no-unsafe-eval-csp",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unsafe-eval-csp.md",description:"Disallow 'unsafe-eval' in Content Security Policy",cwe:"CWE-95",cvss:8.1},messages:{unsafeEval:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-eval' Detected",cwe:"CWE-95",owasp:"A03:2021",cvss:8.1,description:"'unsafe-eval' in CSP allows eval(), new Function(), and setTimeout(string). This enables code injection attacks.",severity:"HIGH",fix:"Remove 'unsafe-eval' and refactor code to avoid eval-like patterns.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src"})},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 UNSAFE_EVAL="unsafe-eval";const sourceCode=context.sourceCode;function checkPolicyText(node,value){if((0,csp_directive_1.policyGrantsKeyword)(value,UNSAFE_EVAL)){context.report({node,messageId:"unsafeEval"})}}return{Literal(node){if(typeof node.value!=="string")return;checkPolicyText(node,node.value);if((0,csp_directive_1.cspSourceKeyword)(node.value)===UNSAFE_EVAL&&(0,csp_directive_1.isCspSourceListElement)(node,sourceCode)){context.report({node,messageId:"unsafeEval"})}},TemplateLiteral(node){checkPolicyText(node,node.quasis.map(q=>q.value.raw).join(" "))}}}});
@@ -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:{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},hasSuggestions:true,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/styles 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"}),useNonceOrHash:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Nonce or Hash",description:"Replace unsafe-inline with nonces or hashes",severity:"LOW",fix:"script-src 'self' 'nonce-randomValue'; (generate nonce per-request)",documentationLink:"https://content-security-policy.com/nonce/"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const UNSAFE_INLINE_PATTERN=/'unsafe-inline'/i;const CSP_DIRECTIVES=/\b(?:default|script|style|img|connect|font|frame|media|object|worker|child|manifest|prefetch|base|form)-(?:src|uri|action)(?:-elem|-attr)?\b/i;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&&!parent.computed){if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return isCspName(parent.key.name);if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof parent.key.value==="string"){return isCspName(parent.key.value)}return false}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXExpressionContainer||parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute){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))}return false}function checkForUnsafeInline(node,value){if(!UNSAFE_INLINE_PATTERN.test(value))return;if(!CSP_DIRECTIVES.test(value)&&!atCspSink(node))return;context.report({node,messageId:"unsafeInline",suggest:[{messageId:"useNonceOrHash",fix:()=>null}]})}return{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
+ "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:{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/styles 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"})},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 UNSAFE_INLINE_PATTERN=/'unsafe-inline'/i;const CSP_DIRECTIVES=/\b(?:default|script|style|img|connect|font|frame|media|object|worker|child|manifest|prefetch|base|form)-(?:src|uri|action)(?:-elem|-attr)?\b/i;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&&!parent.computed){if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return isCspName(parent.key.name);if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof parent.key.value==="string"){return isCspName(parent.key.value)}return false}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXExpressionContainer||parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute){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))}return false}function checkForUnsafeInline(node,value){if(!UNSAFE_INLINE_PATTERN.test(value))return;if(!CSP_DIRECTIVES.test(value)&&!atCspSink(node))return;context.report({node,messageId:"unsafeInline"})}return{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.noUnvalidatedDeeplinks=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const url_taint_1=require("../../utils/url-taint");exports.noUnvalidatedDeeplinks=(0,eslint_devkit_1.createRule)({name:"no-unvalidated-deeplinks",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unvalidated-deeplinks.md",description:"Require validation of deep link URLs",cwe:"CWE-939",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unvalidated Deeplink",cwe:"CWE-939",description:"Deep link URL used without validation - potential open redirect",severity:"HIGH",fix:"Validate deep link URLs against a whitelist before navigation",documentationLink:"https://cwe.mitre.org/data/definitions/939.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}return{CallExpression(node){if(node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Linking"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="openURL"){const urlArg=node.arguments[0];if(urlArg&&urlArg.type==="Identifier"){report(node)}if(urlArg&&urlArg.type==="MemberExpression"){report(node)}}if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="navigate"){const urlArg=node.arguments[0];if(urlArg&&(0,url_taint_1.isAttackerSteerableUrl)(urlArg,context.sourceCode)){report(node)}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnvalidatedDeeplinks=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const navigation_targets_1=require("../../utils/navigation-targets");const resolve_binding_1=require("../../utils/resolve-binding");function memberPath(node,sourceCode,depth=0){if(depth>4)return null;const parts=[];let current=node;while(current.type==="MemberExpression"){if(!current.computed&&current.property.type==="Identifier"){parts.unshift(current.property.name)}current=current.object}if(current.type!=="Identifier")return null;const init=(0,resolve_binding_1.resolveInitializer)(current,sourceCode);if(init!==void 0){const base=memberPath(init,sourceCode,depth+1);if(base!==null)return[...base,...parts]}parts.unshift(current.name);return parts}function isRouteParam(node,sourceCode){const path=memberPath(node,sourceCode);if(path===null)return false;for(let i=0;i+2<path.length;i+=1){if((path[i]==="route"||path[i]==="routes")&&path[i+1]==="params"){return true}}return false}function isLinkingCall(node,method){return node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&!node.callee.computed&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Linking"&&node.callee.property.type==="Identifier"&&node.callee.property.name===method}function deepLinkParamKind(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)continue;if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Parameter")return null;const fn=def.node;const call=fn.parent;if(call===void 0||call.type!=="CallExpression")return null;if(isLinkingCall(call,"addEventListener")&&call.arguments[0]?.type==="Literal"&&call.arguments[0].value==="url"){return"event"}if(call.callee.type==="MemberExpression"&&!call.callee.computed&&call.callee.property.type==="Identifier"&&call.callee.property.name==="then"&&isLinkingCall(call.callee.object,"getInitialURL")){return"url"}return null}return null}function isDeepLinkSteerable(node,sourceCode){if(node.type==="ChainExpression"){return isDeepLinkSteerable(node.expression,sourceCode)}if((0,navigation_targets_1.isSteerableUrlValue)(node,sourceCode))return true;if(isRouteParam(node,sourceCode))return true;if(node.type==="CallExpression"){const index=(0,navigation_targets_1.identityArgumentIndex)(node,sourceCode);if(index!==null){const argument=node.arguments[index];return argument!==void 0&&argument.type!=="SpreadElement"&&isDeepLinkSteerable(argument,sourceCode)}}if(node.type==="AwaitExpression"){return isLinkingCall(node.argument,"getInitialURL")}if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="url"&&node.object.type==="Identifier"){return deepLinkParamKind(node.object,sourceCode)==="event"}if(node.type==="Identifier"){if(deepLinkParamKind(node,sourceCode)==="url")return true;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&isDeepLinkSteerable(init,sourceCode)}return false}exports.noUnvalidatedDeeplinks=(0,eslint_devkit_1.createRule)({name:"no-unvalidated-deeplinks",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unvalidated-deeplinks.md",description:"Require validation of deep link URLs",cwe:"CWE-939",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unvalidated Deeplink",cwe:"CWE-939",description:"Deep link URL used without validation - potential open redirect",severity:"HIGH",fix:"Validate deep link URLs against a whitelist before navigation",documentationLink:"https://cwe.mitre.org/data/definitions/939.html"})},schema:[]},defaultOptions:[],create(context){const{sourceCode}=context;function report(node){context.report({node,messageId:"violationDetected"})}return{CallExpression(node){if(isLinkingCall(node,"openURL")){const urlArg=node.arguments[0];if(urlArg&&isDeepLinkSteerable(urlArg,sourceCode)){report(node)}}if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="navigate"){const urlArg=node.arguments[0];if(urlArg&&(0,navigation_targets_1.isSteerableUrlValue)(urlArg,context.sourceCode)){report(node)}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWebsocketEval=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const EVAL_FUNCTIONS=new Set(["eval","Function"]);exports.noWebsocketEval=(0,eslint_devkit_1.createRule)({name:"no-websocket-eval",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-websocket-eval.md",description:"Disallow using eval() or Function() with WebSocket message data",cwe:"CWE-95",cvss:9.8},hasSuggestions:true,messages:{evalWithWsData:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Remote Code Execution via WebSocket",cwe:"CWE-95",owasp:"A03:2021",cvss:9.8,description:"Using {{method}} with WebSocket data enables remote code execution. A compromised server or MITM attacker can execute arbitrary JavaScript.",severity:"CRITICAL",fix:"Parse WebSocket data as JSON and validate the structure instead of executing it.",documentationLink:"https://cwe.mitre.org/data/definitions/95.html"}),parseDataSafely:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Parse Data Safely",description:"Use JSON.parse() and validate the data structure",severity:"LOW",fix:'const data = JSON.parse(event.data); if (data.action === "update") { handleUpdate(data); }',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isWsAddEventListener(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="addEventListener"&&node.arguments.length>=2){const eventType=node.arguments[0];if(eventType.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&eventType.value==="message"){const callback=node.arguments[1];if(callback.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||callback.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=callback.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}function isEvalCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVAL_FUNCTIONS.has(node.callee.name)){return node.callee.name}return null}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{CallExpression(node){const evalFn=isEvalCall(node);if(evalFn){for(const arg of node.arguments){if(payloadSource(arg)==="websocket"){context.report({node,messageId:"evalWithWsData",data:{method:evalFn},suggest:[{messageId:"parseDataSafely",fix:()=>null}]});break}}}},"CallExpression:exit"(node){const{isHandler}=isWsAddEventListener(node);if(isHandler){}},NewExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Function"){for(const arg of node.arguments){if(payloadSource(arg)==="websocket"){context.report({node,messageId:"evalWithWsData",data:{method:"new Function"},suggest:[{messageId:"parseDataSafely",fix:()=>null}]});break}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWebsocketEval=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const dynamic_code_sinks_1=require("../../utils/dynamic-code-sinks");exports.noWebsocketEval=(0,eslint_devkit_1.createRule)({name:"no-websocket-eval",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-websocket-eval.md",description:"Disallow using eval() or Function() with WebSocket message data",cwe:"CWE-95",cvss:9.8},messages:{evalWithWsData:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Remote Code Execution via WebSocket",cwe:"CWE-95",owasp:"A03:2021",cvss:9.8,description:"Using {{method}} with WebSocket data enables remote code execution. A compromised server or MITM attacker can execute arbitrary JavaScript.",severity:"CRITICAL",fix:"Parse WebSocket data as JSON and validate the structure instead of executing it.",documentationLink:"https://cwe.mitre.org/data/definitions/95.html"})},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);function inspect(node){const sink=(0,dynamic_code_sinks_1.dynamicCodeSink)(node,context.sourceCode);if(sink===void 0)return;if(sink.name===null)return;if(!sink.codeArguments.some(arg=>payloadSource(arg)==="websocket"))return;context.report({node,messageId:"evalWithWsData",data:{method:node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression?`new ${sink.name}`:sink.name}})}return{CallExpression:inspect,NewExpression:inspect}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWebsocketInnerhtml=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.noWebsocketInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-websocket-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-websocket-innerhtml.md",description:"Disallow using innerHTML or similar methods with WebSocket message data",cwe:"CWE-79",cvss:8.1},hasSuggestions:true,messages:{unsafeInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via WebSocket",cwe:"CWE-79",owasp:"A03:2021",cvss:8.1,description:"Using {{method}} with WebSocket data enables XSS attacks. Malicious server or MITM can send crafted HTML to execute scripts.",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/WebSocket"}),useTextContent:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Safe DOM Methods",description:"Use textContent or sanitize input with DOMPurify",severity:"LOW",fix:"element.textContent = event.data; // For plain text\nelement.innerHTML = DOMPurify.sanitize(event.data); // For HTML",documentationLink:"https://github.com/cure53/DOMPurify"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isWsOnmessageAssignment(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.property.name==="onmessage"){const handler=node.right;if(handler.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||handler.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=handler.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}return{isHandler:false,eventParam:null}}function isWsAddEventListener(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="addEventListener"&&node.arguments.length>=2){const eventType=node.arguments[0];if(eventType.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&eventType.value==="message"){const callback=node.arguments[1];if(callback.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||callback.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=callback.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_PROPERTIES.has(node.left.property.name)){if(payloadSource(node.right)==="websocket"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.left.property.name},suggest:[{messageId:"useTextContent",fix:()=>null}]})}}},"AssignmentExpression:exit"(node){const{isHandler}=isWsOnmessageAssignment(node);if(isHandler){}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_METHODS.has(node.callee.property.name)){for(const arg of node.arguments){if(payloadSource(arg)==="websocket"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.callee.property.name},suggest:[{messageId:"useTextContent",fix:()=>null}]});break}}}},"CallExpression:exit"(node){const{isHandler}=isWsAddEventListener(node);if(isHandler){}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWebsocketInnerhtml=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.noWebsocketInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-websocket-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-websocket-innerhtml.md",description:"Disallow using innerHTML or similar methods with WebSocket message data",cwe:"CWE-79",cvss:8.1},messages:{unsafeInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via WebSocket",cwe:"CWE-79",owasp:"A03:2021",cvss:8.1,description:"Using {{method}} with WebSocket data enables XSS attacks. Malicious server or MITM can send crafted HTML to execute scripts.",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/WebSocket"})},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{}}function isWsOnmessageAssignment(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.property.name==="onmessage"){const handler=node.right;if(handler.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||handler.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=handler.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}return{isHandler:false,eventParam:null}}function isWsAddEventListener(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="addEventListener"&&node.arguments.length>=2){const eventType=node.arguments[0];if(eventType.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&eventType.value==="message"){const callback=node.arguments[1];if(callback.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||callback.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=callback.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_PROPERTIES.has(node.left.property.name)){if(payloadSource(node.right)==="websocket"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.left.property.name}})}}},"AssignmentExpression:exit"(node){const{isHandler}=isWsOnmessageAssignment(node);if(isHandler){}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_METHODS.has(node.callee.property.name)){for(const arg of node.arguments){if(payloadSource(arg)==="websocket"){context.report({node,messageId:"unsafeInnerhtml",data:{method:node.callee.property.name}});break}}}},"CallExpression:exit"(node){const{isHandler}=isWsAddEventListener(node);if(isHandler){}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWorkerMessageInnerhtml=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.noWorkerMessageInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-worker-message-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-worker-message-innerhtml.md",description:"Disallow using innerHTML with Web Worker message data",cwe:"CWE-79",cvss:7.5},hasSuggestions:true,messages:{workerInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via Worker Message",cwe:"CWE-79",owasp:"A03:2021",cvss:7.5,description:"Using {{method}} with Worker message data can enable XSS if the worker processes untrusted input.",severity:"HIGH",fix:"Sanitize worker data with DOMPurify before rendering, or use textContent.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event"}),sanitizeWorkerData:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Sanitize Worker Data",description:"Use textContent or sanitize with DOMPurify",severity:"LOW",fix:"const sanitized = DOMPurify.sanitize(event.data);\nelement.innerHTML = sanitized;",documentationLink:"https://github.com/cure53/DOMPurify"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isWorkerOnmessageAssignment(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.property.name==="onmessage"){{const handler=node.right;if(handler.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||handler.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=handler.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}function isWorkerAddEventListener(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="addEventListener"&&node.arguments.length>=2){const eventType=node.arguments[0];if(eventType.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&eventType.value==="message"){const callback=node.arguments[1];if(callback.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||callback.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=callback.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_PROPERTIES.has(node.left.property.name)){if(payloadSource(node.right)==="worker"){context.report({node,messageId:"workerInnerhtml",data:{method:node.left.property.name},suggest:[{messageId:"sanitizeWorkerData",fix:()=>null}]})}}},"AssignmentExpression:exit"(node){const{isHandler}=isWorkerOnmessageAssignment(node);if(isHandler){}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_METHODS.has(node.callee.property.name)){for(const arg of node.arguments){if(payloadSource(arg)==="worker"){context.report({node,messageId:"workerInnerhtml",data:{method:node.callee.property.name},suggest:[{messageId:"sanitizeWorkerData",fix:()=>null}]});break}}}},"CallExpression:exit"(node){const{isHandler}=isWorkerAddEventListener(node);if(isHandler){}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWorkerMessageInnerhtml=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.noWorkerMessageInnerhtml=(0,eslint_devkit_1.createRule)({name:"no-worker-message-innerhtml",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-worker-message-innerhtml.md",description:"Disallow using innerHTML with Web Worker message data",cwe:"CWE-79",cvss:7.5},messages:{workerInnerhtml:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"XSS via Worker Message",cwe:"CWE-79",owasp:"A03:2021",cvss:7.5,description:"Using {{method}} with Worker message data can enable XSS if the worker processes untrusted input.",severity:"HIGH",fix:"Sanitize worker data with DOMPurify before rendering, or use textContent.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event"})},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{}}function isWorkerOnmessageAssignment(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.property.name==="onmessage"){{const handler=node.right;if(handler.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||handler.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=handler.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}function isWorkerAddEventListener(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="addEventListener"&&node.arguments.length>=2){const eventType=node.arguments[0];if(eventType.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&eventType.value==="message"){const callback=node.arguments[1];if(callback.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||callback.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){const firstParam=callback.params[0];if(firstParam&&firstParam.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return{isHandler:true,eventParam:firstParam.name}}}}}return{isHandler:false,eventParam:null}}const payloadSource=(0,eslint_devkit_1.createPayloadResolver)(context.sourceCode);return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_PROPERTIES.has(node.left.property.name)){if(payloadSource(node.right)==="worker"){context.report({node,messageId:"workerInnerhtml",data:{method:node.left.property.name}})}}},"AssignmentExpression:exit"(node){const{isHandler}=isWorkerOnmessageAssignment(node);if(isHandler){}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DANGEROUS_METHODS.has(node.callee.property.name)){for(const arg of node.arguments){if(payloadSource(arg)==="worker"){context.report({node,messageId:"workerInnerhtml",data:{method:node.callee.property.name}});break}}}},"CallExpression:exit"(node){const{isHandler}=isWorkerAddEventListener(node);if(isHandler){}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBlobUrlRevocation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.requireBlobUrlRevocation=(0,eslint_devkit_1.createRule)({name:"require-blob-url-revocation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-blob-url-revocation.md",description:"Require revoking Blob URLs to prevent memory leaks",cwe:"CWE-401",cvss:5.3},hasSuggestions:true,messages:{missingRevoke:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Blob URL Memory Leak",cwe:"CWE-401",owasp:"A06:2021",cvss:5.3,description:"URL.createObjectURL() creates a reference that persists until explicitly revoked. Without revokeObjectURL(), memory leaks occur.",severity:"MEDIUM",fix:"Call URL.revokeObjectURL(blobUrl) when the URL is no longer needed.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL"}),addRevocation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add URL Revocation",description:"Revoke the Blob URL after use",severity:"LOW",fix:"URL.revokeObjectURL(blobUrl);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const createdUrls=new Map;const revokedUrls=new Set;return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="URL"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="createObjectURL"){const parent=node.parent;if(parent&&parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){createdUrls.set(parent.id.name,parent)}}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="URL"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="revokeObjectURL"){const arg=node.arguments[0];if(arg&&arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){revokedUrls.add(arg.name)}}},"Program:exit"(){for(const[urlVar,declaratorNode]of createdUrls){if(!revokedUrls.has(urlVar)){context.report({node:declaratorNode,messageId:"missingRevoke",suggest:[{messageId:"addRevocation",fix:()=>null}]})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBlobUrlRevocation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const global_object_1=require("../../utils/global-object");const URL_GLOBAL=new Set(["URL"]);function isUrlMethod(node,method){const callee=node.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name===method&&(0,global_object_1.resolveGlobalObject)(callee.object,URL_GLOBAL)!==null}function pathKey(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===eslint_devkit_1.AST_NODE_TYPES.ThisExpression)return"this";if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const base=pathKey(node.object);return base===null?null:`${base}.${node.property.name}`}return null}function ownerOf(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const found=scope.variables.find(v=>v.name===identifier.name);if(found!==void 0)return found}return identifier.name}function escapes(node){const parent=node.parent;return parent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.Property||parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}exports.requireBlobUrlRevocation=(0,eslint_devkit_1.createRule)({name:"require-blob-url-revocation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-blob-url-revocation.md",description:"Require revoking Blob URLs to prevent memory leaks",cwe:"CWE-401",cvss:5.3},messages:{missingRevoke:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Blob URL Memory Leak",cwe:"CWE-401",owasp:"A06:2021",cvss:5.3,description:"URL.createObjectURL() creates a reference that persists until explicitly revoked. Without revokeObjectURL(), memory leaks occur.",severity:"MEDIUM",fix:"Call URL.revokeObjectURL(blobUrl) when the URL is no longer needed.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL"})},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 sourceCode=context.sourceCode;const byOwner=new Map;const byPath=new Map;const unreachable=[];const revokedOwners=new Set;const revokedPaths=new Set;function trackCreation(node){const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){byOwner.set(ownerOf(parent.id,sourceCode),parent);return}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){if(parent.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){byOwner.set(ownerOf(parent.left,sourceCode),parent);return}const key=pathKey(parent.left);if(key!==null)byPath.set(key,parent);return}if(escapes(node))return;unreachable.push(node)}function trackRevocation(node){const arg=node.arguments[0];if(arg===void 0)return;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){revokedOwners.add(ownerOf(arg,sourceCode));return}const key=pathKey(arg);if(key!==null)revokedPaths.add(key)}return{CallExpression(node){if(isUrlMethod(node,"createObjectURL"))trackCreation(node);if(isUrlMethod(node,"revokeObjectURL"))trackRevocation(node)},"Program:exit"(){for(const[owner,site]of byOwner){if(!revokedOwners.has(owner)){context.report({node:site,messageId:"missingRevoke"})}}for(const[key,site]of byPath){if(!revokedPaths.has(key)){context.report({node:site,messageId:"missingRevoke"})}}for(const site of unreachable){context.report({node:site,messageId:"missingRevoke"})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCookieSecureAttrs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.requireCookieSecureAttrs=(0,eslint_devkit_1.createRule)({name:"require-cookie-secure-attrs",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-cookie-secure-attrs.md",description:"Require Secure and SameSite attributes when setting cookies",cwe:"CWE-614",cvss:6.5},hasSuggestions:true,messages:{missingSecure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Cookie Missing Secure Attribute",cwe:"CWE-614",owasp:"A02:2021",cvss:6.5,description:"Cookie set without Secure attribute. It will be sent over unencrypted HTTP connections.",severity:"MEDIUM",fix:'Add Secure attribute: document.cookie = "name=value; Secure; SameSite=Strict"',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies"}),missingSameSite:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Cookie Missing SameSite Attribute",cwe:"CWE-352",owasp:"A01:2021",cvss:6.5,description:"Cookie set without SameSite attribute. It may be vulnerable to CSRF attacks.",severity:"MEDIUM",fix:'Add SameSite attribute: document.cookie = "name=value; SameSite=Strict"',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite"}),addSecureAttrs:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Secure Attributes",description:"Add Secure and SameSite attributes",severity:"LOW",fix:'document.cookie = "name=value; Secure; SameSite=Strict"',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"})},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=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.object.name==="document"&&node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.property.name==="cookie"){let cookieValue="";if(node.right.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.right.value==="string"){cookieValue=node.right.value}else if(node.right.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){cookieValue=node.right.quasis.map(q=>q.value.raw).join("")}if(!cookieValue)return;const hasSecure=/;\s*secure/i.test(cookieValue);const hasSameSite=/;\s*samesite/i.test(cookieValue);if(!hasSecure){context.report({node,messageId:"missingSecure",suggest:[{messageId:"addSecureAttrs",fix:()=>null}]})}if(!hasSameSite){context.report({node,messageId:"missingSameSite",suggest:[{messageId:"addSecureAttrs",fix:()=>null}]})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCookieSecureAttrs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const sensitive_value_evidence_1=require("../../utils/sensitive-value-evidence");exports.requireCookieSecureAttrs=(0,eslint_devkit_1.createRule)({name:"require-cookie-secure-attrs",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-cookie-secure-attrs.md",description:"Require Secure and SameSite attributes when setting cookies",cwe:"CWE-614",cvss:6.5},messages:{missingSecure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Cookie Missing Secure Attribute",cwe:"CWE-614",owasp:"A02:2021",cvss:6.5,description:"Cookie set without Secure attribute. It will be sent over unencrypted HTTP connections.",severity:"MEDIUM",fix:'Add Secure attribute: document.cookie = "name=value; Secure; SameSite=Strict"',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies"}),missingSameSite:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Cookie Missing SameSite Attribute",cwe:"CWE-352",owasp:"A01:2021",cvss:6.5,description:"Cookie set without SameSite attribute. It may be vulnerable to CSRF attacks.",severity:"MEDIUM",fix:'Add SameSite attribute: document.cookie = "name=value; SameSite=Strict"',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(context.filename);if(allowInTests&&isTestFile){return{}}return{AssignmentExpression(node){if(!(0,sensitive_value_evidence_1.isDocumentCookieTarget)(node.left))return;const cookieText=(0,sensitive_value_evidence_1.staticCookieText)(node.right,context.sourceCode);if(cookieText===null)return;if((0,sensitive_value_evidence_1.cookieNameFrom)(cookieText)===null)return;if((0,sensitive_value_evidence_1.isCookieDeletion)(cookieText))return;if(!/;\s*secure\s*(?:;|$)/i.test(cookieText)){context.report({node,messageId:"missingSecure"})}if(!/;\s*samesite\s*=/i.test(cookieText)){context.report({node,messageId:"missingSameSite"})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCspHeaders=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.requireCspHeaders=(0,eslint_devkit_1.createRule)({name:"require-csp-headers",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-csp-headers.md",description:"Require Content Security Policy headers",cwe:"CWE-1021",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSP",cwe:"CWE-1021",description:"HTML response without Content-Security-Policy header",severity:"MEDIUM",fix:"Use helmet.contentSecurityPolicy() or set CSP header manually",documentationLink:"https://cwe.mitre.org/data/definitions/1021.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}let helmetInstalled=false;return{Program(){helmetInstalled=false},ImportDeclaration(node){if(typeof node.source.value==="string"&&/^helmet(\/|$)/.test(node.source.value)){helmetInstalled=true}},'CallExpression[callee.name="require"]'(node){const arg=node.arguments[0];if(arg?.type==="Literal"&&typeof arg.value==="string"&&/^helmet(\/|$)/.test(arg.value)){helmetInstalled=true}},CallExpression(node){if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="send"){const arg=node.arguments[0];if(arg&&arg.type==="TemplateLiteral"){const quasi=arg.quasis[0]?.value?.raw||"";if(quasi.includes("<html")||quasi.includes("<!DOCTYPE")){report(node)}}if(arg&&arg.type==="Literal"&&typeof arg.value==="string"){if(arg.value.includes("<html")||arg.value.includes("<!DOCTYPE")){report(node)}}}if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="render"){if(!helmetInstalled){report(node)}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCspHeaders=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const EMIT_METHODS=new Set(["send","end","write","render"]);const FILE_METHODS=new Set(["sendFile"]);const DOCUMENT_EXTENSIONS=new Set([".html",".htm"]);const HEADER_METHODS=new Set(["setHeader","writeHead","header","set"]);const CSP_HEADER="content-security-policy";const HELMET_MODULE=/^helmet(\/|$)/;function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function staticString(node,sourceCode,depth){if(depth>5)return null;if(node.type==="Literal"){return typeof node.value==="string"?node.value:null}if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value?.raw??"").join(" ")}if(node.type==="Identifier"){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:staticString(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=foldToArray(node.object,sourceCode,depth+1);const element=array?.elements[index.value];return element==null?null:staticString(element,sourceCode,depth+1)}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const fn=resolveLocalFunction(node.callee,sourceCode);if(fn===null)return null;return returnedString(fn,sourceCode,depth+1)}return null}function foldToArray(node,sourceCode,depth){if(depth>5)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 resolveLocalFunction(callee,sourceCode){for(let scope=sourceCode.getScope(callee);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===callee.name);if(variable===void 0)continue;if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type==="FunctionName")return def.node;if(def.type==="Variable"){const init=def.node.init;return init?.type==="ArrowFunctionExpression"||init?.type==="FunctionExpression"?init:null}return null}return null}function returnedString(fn,sourceCode,depth){if((fn.type==="ArrowFunctionExpression"||fn.type==="FunctionExpression"||fn.type==="FunctionDeclaration")&&fn.body.type!=="BlockStatement"){return staticString(fn.body,sourceCode,depth)}const parts=[];walk(fn,child=>{if(child.type!=="ReturnStatement"||child.argument===null)return;const value=staticString(child.argument,sourceCode,depth);if(value!==null)parts.push(value)});return parts.length>0?parts.join(" "):null}function walk(node,visit){visit(node);for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(Array.isArray(child)){for(const item of child)if(isNode(item))walk(item,visit)}else if(isNode(child)){walk(child,visit)}}}function isHtmlDocument(text){const lower=text.toLowerCase();return lower.includes("<!doctype")||lower.includes("<html")}function mayHoldDocument(node,sourceCode){const folded=staticString(node,sourceCode,0);if(folded!==null&&isHtmlDocument(folded))return true;if(node.type!=="Identifier")return false;const variable=sourceCode.getScope(node).references.find(ref=>ref.identifier===node)?.resolved;if(variable==null)return false;for(const def of variable.defs){if(def.type!=="Variable"||def.node.init==null)continue;const value=staticString(def.node.init,sourceCode,0);if(value!==null&&isHtmlDocument(value))return true}for(const reference of variable.references){if(!reference.isWrite())continue;const written=reference.writeExpr;if(written==null)continue;const value=staticString(written,sourceCode,0);if(value!==null&&isHtmlDocument(value))return true}return false}function namesDocumentFile(node,sourceCode){const candidates=[];const direct=staticString(node,sourceCode,0);if(direct!==null)candidates.push(direct);if(node.type==="CallExpression"){for(const arg of node.arguments){const value=staticString(arg,sourceCode,0);if(value!==null)candidates.push(value)}}return candidates.some(candidate=>{const dot=candidate.lastIndexOf(".");return dot!==-1&&DOCUMENT_EXTENSIONS.has(candidate.slice(dot).toLowerCase())})}exports.requireCspHeaders=(0,eslint_devkit_1.createRule)({name:"require-csp-headers",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-csp-headers.md",description:"Require Content Security Policy headers",cwe:"CWE-1021",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSP",cwe:"CWE-1021",description:"HTML response without Content-Security-Policy header",severity:"MEDIUM",fix:"Use helmet.contentSecurityPolicy() or set CSP header manually",documentationLink:"https://cwe.mitre.org/data/definitions/1021.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}let cspEstablished;function fileEstablishesCsp(){if(cspEstablished!==void 0)return cspEstablished;let found=false;walk(context.sourceCode.ast,node=>{if(found||!establishesCsp(node))return;found=true});cspEstablished=found;return found}return{CallExpression(node){const method=calleeMethodOf(node);if(method===null)return;if(FILE_METHODS.has(method)){const target=node.arguments[0];if(target===void 0||!namesDocumentFile(target,context.sourceCode)){return}}else{if(!EMIT_METHODS.has(method))return;if(method!=="render"){const body=node.arguments[0];if(body===void 0)return;if(!mayHoldDocument(body,context.sourceCode))return}}if(fileEstablishesCsp())return;if(scopeSetsResponseHeaders(node))return;report(node)}};function calleeMethodOf(node){if(node.callee.type!=="MemberExpression")return null;const property=node.callee.property;return node.callee.computed?staticString(property,context.sourceCode,0):property.name}function scopeSetsResponseHeaders(node){let scope=context.sourceCode.ast;for(let current=node.parent;current!=null;current=current.parent){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){scope=current;break}}let found=false;walk(scope,child=>{if(child.type==="CallExpression"&&child.callee.type==="MemberExpression"&&!child.callee.computed&&child.callee.property.type==="Identifier"&&HEADER_METHODS.has(child.callee.property.name)){found=true}});return found}}});function establishesCsp(node){if(node.type==="ImportDeclaration"){return typeof node.source.value==="string"&&HELMET_MODULE.test(node.source.value)}if(node.type==="CallExpression"){const arg=node.arguments[0];return node.callee.type==="Identifier"&&node.callee.name==="require"&&arg?.type==="Literal"&&typeof arg.value==="string"&&HELMET_MODULE.test(arg.value)}if(node.type==="Literal"){return typeof node.value==="string"&&node.value.toLowerCase()===CSP_HEADER&&isHeaderNamePosition(node)}if(node.type==="JSXAttribute"){return node.name.type==="JSXIdentifier"&&(node.name.name==="httpEquiv"||node.name.name==="http-equiv")&&node.value?.type==="Literal"&&typeof node.value.value==="string"&&node.value.value.toLowerCase()===CSP_HEADER}return false}function isHeaderNamePosition(node){const parent=node.parent;if(parent.type==="CallExpression"&&parent.arguments[0]===node&&parent.callee.type==="MemberExpression"&&!parent.callee.computed&&parent.callee.property.type==="Identifier"&&HEADER_METHODS.has(parent.callee.property.name)){return true}if(parent.type==="Property"&&!parent.computed){if(parent.key===node)return true;if(parent.value===node&&parent.key.type==="Identifier"&&parent.key.name==="key"){return true}}return false}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHttpsOnly=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const AXIOS_HTTP_METHODS=["get","post","put","delete","patch","head","options"];exports.requireHttpsOnly=(0,eslint_devkit_1.createRule)({name:"require-https-only",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-https-only.md",description:"Enforce HTTPS for all external requests",cwe:"CWE-319",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-319",description:"Enforce HTTPS for all external requests detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}return{CallExpression(node){const callee=node.callee;const isFetch=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.name==="fetch";const isAxios=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="axios"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&AXIOS_HTTP_METHODS.includes(callee.property.name);if((isFetch||isAxios)&&node.arguments[0]){const url=node.arguments[0];if(url.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof url.value==="string"&&url.value.startsWith("http://")){report(node)}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHttpsOnly=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const loopback_hosts_1=require("../../utils/loopback-hosts");const transport_ownership_1=require("../../utils/transport-ownership");function writtenAuthority(cooked){const rest=/^http:\/\/([^/?#]*)/i.exec(cooked);const authority=rest[1].replace(/:$/,"");return authority===""?null:authority}exports.requireHttpsOnly=(0,eslint_devkit_1.createRule)({name:"require-https-only",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-https-only.md",description:"Enforce HTTPS for all external requests",cwe:"CWE-319",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-319",description:"Enforce HTTPS for all external requests detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}function writtenPrefix(node){let current=node;for(;;){if(current.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof current.value==="string"?current.value:null}if(current.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return current.quasis[0].value.cooked}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&current.operator==="+"){current=current.left;continue}return null}}return{CallExpression(node){if(!(0,transport_ownership_1.isRequestCall)(node,context.sourceCode.getScope(node))){return}const url=node.arguments[0];if(url===void 0){return}const prefix=writtenPrefix(url);if(prefix===null||!/^http:\/\//i.test(prefix)){return}const authority=writtenAuthority(prefix);if(authority!==null&&(0,loopback_hosts_1.isNonTransmittingUrl)(`http://${authority}`)){return}report(url)}}}});