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.
- package/package.json +2 -2
- package/src/index.js +1 -1
- package/src/rules/detect-mixed-content/index.js +1 -1
- package/src/rules/no-allow-arbitrary-loads/index.js +1 -1
- package/src/rules/no-clickjacking/index.js +1 -1
- package/src/rules/no-client-side-auth-logic/index.js +1 -1
- package/src/rules/no-cookie-auth-tokens/index.js +1 -1
- package/src/rules/no-dynamic-service-worker-url/index.js +1 -1
- package/src/rules/no-eval/index.js +1 -1
- package/src/rules/no-filereader-innerhtml/index.js +1 -1
- package/src/rules/no-http-urls/index.js +1 -1
- package/src/rules/no-innerhtml/index.js +1 -1
- package/src/rules/no-insecure-redirects/index.js +1 -1
- package/src/rules/no-insecure-websocket/index.js +1 -1
- package/src/rules/no-jwt-in-storage/index.js +1 -1
- package/src/rules/no-missing-cors-check/index.js +1 -1
- package/src/rules/no-missing-csrf-protection/index.js +1 -1
- package/src/rules/no-missing-security-headers/index.js +1 -1
- package/src/rules/no-password-in-url/index.js +1 -1
- package/src/rules/no-permissive-cors/index.js +1 -1
- package/src/rules/no-postmessage-innerhtml/index.js +1 -1
- package/src/rules/no-postmessage-wildcard-origin/index.js +1 -1
- package/src/rules/no-sensitive-cookie-js/index.js +1 -1
- package/src/rules/no-sensitive-data-in-analytics/index.js +1 -1
- package/src/rules/no-sensitive-data-in-cache/index.js +1 -1
- package/src/rules/no-sensitive-indexeddb/index.js +1 -1
- package/src/rules/no-sensitive-localstorage/index.js +1 -1
- package/src/rules/no-sensitive-sessionstorage/index.js +1 -1
- package/src/rules/no-tracking-without-consent/index.js +1 -1
- package/src/rules/no-unencrypted-transmission/index.js +1 -1
- package/src/rules/no-unescaped-url-parameter/index.js +1 -1
- package/src/rules/no-unescaped-url-parameter/untrusted-text.js +1 -0
- package/src/rules/no-unescaped-url-parameter/url-shape.js +1 -0
- package/src/rules/no-unsafe-eval-csp/index.js +1 -1
- package/src/rules/no-unsafe-inline-csp/index.js +1 -1
- package/src/rules/no-unvalidated-deeplinks/index.js +1 -1
- package/src/rules/no-websocket-eval/index.js +1 -1
- package/src/rules/no-websocket-innerhtml/index.js +1 -1
- package/src/rules/no-worker-message-innerhtml/index.js +1 -1
- package/src/rules/require-blob-url-revocation/index.js +1 -1
- package/src/rules/require-cookie-secure-attrs/index.js +1 -1
- package/src/rules/require-csp-headers/index.js +1 -1
- package/src/rules/require-https-only/index.js +1 -1
- package/src/rules/require-mime-type-validation/index.js +1 -1
- package/src/rules/require-postmessage-origin-check/index.js +1 -1
- package/src/rules/require-url-validation/index.js +1 -1
- package/src/rules/require-websocket-wss/index.js +1 -1
- package/src/utils/analytics-sinks.js +1 -0
- package/src/utils/csp-directive.js +1 -0
- package/src/utils/dynamic-code-sinks.js +1 -0
- package/src/utils/express-app.js +1 -0
- package/src/utils/global-object.js +1 -0
- package/src/utils/navigation-targets.js +1 -0
- package/src/utils/sensitive-value-evidence.js +1 -0
- package/src/utils/transport-ownership.js +1 -0
- package/src/utils/url-taint.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireMimeTypeValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.requireMimeTypeValidation=(0,eslint_devkit_1.createRule)({name:"require-mime-type-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-mime-type-validation.md",description:"Require MIME type validation for file uploads",cwe:"CWE-434",cvss:8.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing MIME Validation",cwe:"CWE-434",description:"File upload without MIME type validation - unrestricted upload vulnerability",severity:"HIGH",fix:"Add fileFilter option
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireMimeTypeValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("../../utils/resolve-binding");const IANA_TOP_LEVEL_TYPES=new Set(["application","audio","example","font","haptics","image","message","model","multipart","text","video"]);const SUBSTRING_TESTS=new Set(["startsWith","endsWith","includes","indexOf","lastIndexOf","search","match"]);const MULTER_FIELD_METHODS=new Set(["single","array","fields","any","none"]);function isMediaTypeLiteral(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return false;if(typeof node.value!=="string")return false;const slash=node.value.indexOf("/");if(slash<=0)return false;return IANA_TOP_LEVEL_TYPES.has(node.value.slice(0,slash))}function isTypeRead(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="type"}function isFilesRead(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="files"}function walk(node,visit){visit(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value)if(isNode(child))walk(child,visit)}else if(isNode(value)){walk(value,visit)}}}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function enclosingFunction(node,sourceCode){return sourceCode.getScope(node).variableScope.block}function isUploadSink(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.name==="fetch"&&node.arguments[1]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return node.arguments[1].properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name==="body")}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(callee.property.name==="send")return node.arguments.length>0;if(callee.property.name==="append")return node.arguments.length>=2}return false}function multerCall(node,scope,sourceCode){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return(0,eslint_devkit_1.isModuleBinding)(node.callee,scope,"multer")?node:void 0}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?void 0:multerCall(init,scope,sourceCode)}return void 0}exports.requireMimeTypeValidation=(0,eslint_devkit_1.createRule)({name:"require-mime-type-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-mime-type-validation.md",description:"Require MIME type validation for file uploads",cwe:"CWE-434",cvss:8.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing MIME Validation",cwe:"CWE-434",description:"File upload without MIME type validation - unrestricted upload vulnerability",severity:"HIGH",fix:"Add a fileFilter option that compares file.mimetype against an exact allowlist. A limits option caps file SIZE and validates no type.",documentationLink:"https://cwe.mitre.org/data/definitions/434.html"}),prefixMimeCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MIME Type Checked by Prefix",cwe:"CWE-434",description:'A media type tested with {{method}} rather than compared for equality. "image/svg+xml" satisfies a prefix test for "image/" and then executes script when the file is served back.',severity:"HIGH",fix:"Compare the type for exact equality against an allowlist: ALLOWED.has(file.type).",documentationLink:"https://cwe.mitre.org/data/definitions/434.html"}),missingMimeValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"File Uploaded Without MIME Validation",cwe:"CWE-434",description:"Selected files are uploaded without any media-type check in this handler - unrestricted upload vulnerability.",severity:"HIGH",fix:"Compare file.type for exact equality against an allowlist before uploading. The accept attribute is a UI hint and is not enforced.",documentationLink:"https://cwe.mitre.org/data/definitions/434.html"})},schema:[]},defaultOptions:[],create(context){const sourceCode=context.sourceCode;const reportedScopes=new Set;function hasMimeEvidence(scope){let found=false;walk(scope,node=>{if(found)return;if(isTypeRead(node)||isMediaTypeLiteral(node))found=true});return found}function readsSelectedFiles(scope){let found=false;walk(scope,node=>{if(found)return;if(isFilesRead(node))found=true});return found}return{CallExpression(node){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&&SUBSTRING_TESTS.has(callee.property.name)&&isTypeRead(callee.object)&&node.arguments.some(isMediaTypeLiteral)){context.report({node,messageId:"prefixMimeCheck",data:{method:callee.property.name}});return}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&MULTER_FIELD_METHODS.has(callee.property.name)){const factory=multerCall(callee.object,sourceCode.getScope(node),sourceCode);if(factory!==void 0){const config=factory.arguments[0];const hasFileFilter=config?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&config.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name==="fileFilter");if(!hasFileFilter){context.report({node,messageId:"violationDetected"})}return}}if(!isUploadSink(node))return;const scope=enclosingFunction(node,sourceCode);if(reportedScopes.has(scope))return;if(!readsSelectedFiles(scope))return;if(hasMimeEvidence(scope))return;reportedScopes.add(scope);context.report({node,messageId:"missingMimeValidation"})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requirePostmessageOriginCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const regexp_anchoring_1=require("../../utils/regexp-anchoring");const NON_WINDOW_RECEIVERS=new Set(["WebSocket","EventSource","Worker","SharedWorker","BroadcastChannel","MessagePort","MessageChannel"]);function receiverKey(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){if(node.object.type==="ThisExpression"){return`this.${node.property.name}`}if(node.object.type==="Identifier"){return`${node.object.name}.${node.property.name}`}}return void 0}function annotatedTypeName(annotation){const type=annotation?.typeAnnotation;if(type?.type==="TSTypeReference"&&type.typeName.type==="Identifier"){return type.typeName.name}return void 0}function hasOriginCheck(node,sourceCode){const text=sourceCode.getText(node);const originPatterns=[/event\.origin\s*[!=]==?\s*/,/e\.origin\s*[!=]==?\s*/,/\.origin\s*[!=]==?\s*/,/origin\s*[!=]==?\s*/,/checkOrigin/i,/validateOrigin/i,/isAllowedOrigin/i,/trustedOrigins/i,/allowedOrigins/i];return originPatterns.some(pattern=>pattern.test(text))}exports.requirePostmessageOriginCheck=(0,eslint_devkit_1.createRule)({name:"require-postmessage-origin-check",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-postmessage-origin-check.md",description:"Require origin validation in postMessage event listeners",cwe:"CWE-346",cvss:7.5},
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requirePostmessageOriginCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const regexp_anchoring_1=require("../../utils/regexp-anchoring");const NON_WINDOW_RECEIVERS=new Set(["WebSocket","EventSource","Worker","SharedWorker","BroadcastChannel","MessagePort","MessageChannel"]);function receiverKey(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){if(node.object.type==="ThisExpression"){return`this.${node.property.name}`}if(node.object.type==="Identifier"){return`${node.object.name}.${node.property.name}`}}return void 0}function annotatedTypeName(annotation){const type=annotation?.typeAnnotation;if(type?.type==="TSTypeReference"&&type.typeName.type==="Identifier"){return type.typeName.name}return void 0}function hasOriginCheck(node,sourceCode){const text=sourceCode.getText(node);const originPatterns=[/event\.origin\s*[!=]==?\s*/,/e\.origin\s*[!=]==?\s*/,/\.origin\s*[!=]==?\s*/,/origin\s*[!=]==?\s*/,/checkOrigin/i,/validateOrigin/i,/isAllowedOrigin/i,/trustedOrigins/i,/allowedOrigins/i];return originPatterns.some(pattern=>pattern.test(text))}exports.requirePostmessageOriginCheck=(0,eslint_devkit_1.createRule)({name:"require-postmessage-origin-check",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-postmessage-origin-check.md",description:"Require origin validation in postMessage event listeners",cwe:"CWE-346",cvss:7.5},messages:{missingOriginCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing postMessage Origin Validation",cwe:"CWE-346",description:"postMessage listener lacks origin check. Malicious sites can send messages that will be processed.",severity:"HIGH",fix:"Add origin validation: if (event.origin !== 'https://trusted-domain.com') return;",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;const unverified=[];const nonWindowReceivers=new Set;function rememberIfNonWindow(key,typeName){if(key===void 0||typeName===void 0)return;if(NON_WINDOW_RECEIVERS.has(typeName))nonWindowReceivers.add(key)}const anchoredOriginTests=[];function isOriginRead(node){return node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="origin"}return{PropertyDefinition(node){if(node.key.type!=="Identifier")return;rememberIfNonWindow(`this.${node.key.name}`,annotatedTypeName(node.typeAnnotation))},VariableDeclarator(node){if(node.id.type!=="Identifier")return;rememberIfNonWindow(node.id.name,annotatedTypeName(node.id.typeAnnotation))},NewExpression(node){if(node.callee.type!=="Identifier")return;const typeName=node.callee.name;const parent=node.parent;if(parent?.type==="VariableDeclarator"&&parent.init===node){rememberIfNonWindow(receiverKey(parent.id),typeName);return}if(parent?.type==="AssignmentExpression"&&parent.right===node){rememberIfNonWindow(receiverKey(parent.left),typeName)}},CallExpression(node){const callee=node.callee;if(node.arguments.length===1&&isOriginRead(node.arguments[0])&&(0,regexp_anchoring_1.isAnchoredRegexpTest)(node,sourceCode)){anchoredOriginTests.push([node.range[0],node.range[1]])}let isMessageListener=false;let receiver;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="addEventListener"){const eventArg=node.arguments[0];if(eventArg&&eventArg.type==="Literal"&&eventArg.value==="message"){isMessageListener=true;receiver=receiverKey(callee.object);if(callee.object.type==="NewExpression"&&callee.object.callee.type==="Identifier"&&NON_WINDOW_RECEIVERS.has(callee.object.callee.name)){return}}}if(callee.type==="Identifier"&&callee.name==="addEventListener"){const eventArg=node.arguments[0];if(eventArg&&eventArg.type==="Literal"&&eventArg.value==="message"){isMessageListener=true}}if(!isMessageListener){return}const handlerArg=node.arguments[1];if(!handlerArg){return}if(handlerArg.type==="FunctionExpression"||handlerArg.type==="ArrowFunctionExpression"){if(!hasOriginCheck(handlerArg,sourceCode)){unverified.push({handler:handlerArg,receiver})}}if(handlerArg.type==="Identifier"){}},"Program:exit"(){for(const{handler,receiver}of unverified){if(receiver!==void 0&&nonWindowReceivers.has(receiver)){continue}const guarded=anchoredOriginTests.some(([start,end])=>start>=handler.range[0]&&end<=handler.range[1]);if(guarded)continue;context.report({node:handler,messageId:"missingOriginCheck"})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireUrlValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.requireUrlValidation=(0,eslint_devkit_1.createRule)({name:"require-url-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-url-validation.md",description:"Enforce URL validation before navigation",cwe:"CWE-601",cvss:6.1},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"URL Validation Required",cwe:"CWE-601",description:"Unvalidated URL used for navigation - this is a security risk",severity:"HIGH",fix:"Validate URLs before using them for navigation",documentationLink:"https://cwe.mitre.org/data/definitions/601.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireUrlValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const navigation_targets_1=require("../../utils/navigation-targets");const regexp_anchoring_1=require("../../utils/regexp-anchoring");exports.requireUrlValidation=(0,eslint_devkit_1.createRule)({name:"require-url-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-url-validation.md",description:"Enforce URL validation before navigation",cwe:"CWE-601",cvss:6.1},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"URL Validation Required",cwe:"CWE-601",description:"Unvalidated URL used for navigation - this is a security risk",severity:"HIGH",fix:"Validate URLs before using them for navigation",documentationLink:"https://cwe.mitre.org/data/definitions/601.html"})},schema:[]},defaultOptions:[],create(context){const{sourceCode}=context;function report(node){context.report({node,messageId:"violationDetected"})}const provesSafeDestination=test=>(0,regexp_anchoring_1.isAnchoredHostGuard)(test,sourceCode)||(0,navigation_targets_1.isRelativePathGuard)(test,sourceCode)||(0,navigation_targets_1.isOriginEqualityGuard)(test,sourceCode);const OPENERS=new Set(["window","self","globalThis","top","parent"]);function calleeParts(node){const callee=node.callee;if(callee.type!=="MemberExpression"||callee.computed)return null;if(callee.property.type!=="Identifier")return null;return{object:callee.object,method:callee.property.name}}return{CallExpression(node){const parts=calleeParts(node);if(parts===null)return;const urlArg=node.arguments[0];if(urlArg===void 0)return;const isOpen=parts.method==="open"&&parts.object.type==="Identifier"&&OPENERS.has(parts.object.name);const isRouterNavigation=(parts.method==="push"||parts.method==="replace")&&(0,navigation_targets_1.isRouterObject)(parts.object,sourceCode);if(!isOpen&&!isRouterNavigation)return;if(!(0,navigation_targets_1.isSteerableUrlValue)(urlArg,sourceCode))return;if((0,navigation_targets_1.isGuardedDestination)(node,urlArg,sourceCode,provesSafeDestination)){return}report(node)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireWebsocketWss=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.requireWebsocketWss=(0,eslint_devkit_1.createRule)({name:"require-websocket-wss",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-websocket-wss.md",description:"Require secure WebSocket connections (wss://) instead of unencrypted (ws://)",cwe:"CWE-319",cvss:7.5},fixable:"code",hasSuggestions:true,messages:{insecureWebsocket:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure WebSocket Connection",cwe:"CWE-319",owasp:"A02:2021",cvss:7.5,description:"WebSocket connection uses unencrypted ws:// protocol. Data transmitted is vulnerable to MITM attacks and eavesdropping.",severity:"HIGH",fix:"Use wss:// (WebSocket Secure) instead of ws:// for encrypted connections.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"}),useWss:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Secure WebSocket",description:"Replace ws:// with wss:// for encrypted connection",severity:"LOW",fix:"Change 'ws://' to 'wss://'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},allowLocalhost:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,allowLocalhost:true}],create(context,[options={}]){const{allowInTests=true,allowLocalhost=true}=options;const filename=context.filename;const isTestFile
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireWebsocketWss=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const loopback_hosts_1=require("../../utils/loopback-hosts");const CLEARTEXT_WS_SCHEME=/^ws:\/\//i;function toSecureScheme(url){return url.replace(CLEARTEXT_WS_SCHEME,"wss://")}exports.requireWebsocketWss=(0,eslint_devkit_1.createRule)({name:"require-websocket-wss",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-websocket-wss.md",description:"Require secure WebSocket connections (wss://) instead of unencrypted (ws://)",cwe:"CWE-319",cvss:7.5},fixable:"code",hasSuggestions:true,messages:{insecureWebsocket:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure WebSocket Connection",cwe:"CWE-319",owasp:"A02:2021",cvss:7.5,description:"WebSocket connection uses unencrypted ws:// protocol. Data transmitted is vulnerable to MITM attacks and eavesdropping.",severity:"HIGH",fix:"Use wss:// (WebSocket Secure) instead of ws:// for encrypted connections.",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"}),useWss:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Secure WebSocket",description:"Replace ws:// with wss:// for encrypted connection",severity:"LOW",fix:"Change 'ws://' to 'wss://'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},allowLocalhost:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,allowLocalhost:true}],create(context,[options={}]){const{allowInTests=true,allowLocalhost=true}=options;const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return{}}function isNonTransmitting(url){return allowLocalhost&&(0,loopback_hosts_1.isLoopbackUrl)(url)||(0,loopback_hosts_1.isReservedExampleUrl)(url)}function checkWebSocketUrl(node,urlArg){if(urlArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof urlArg.value==="string"){const url=urlArg.value;if(isNonTransmitting(url)){return}if(CLEARTEXT_WS_SCHEME.test(url)){const fixedUrl=toSecureScheme(url);context.report({node:urlArg,messageId:"insecureWebsocket",fix:fixer=>fixer.replaceText(urlArg,`'${fixedUrl}'`),suggest:[{messageId:"useWss",fix:fixer=>fixer.replaceText(urlArg,`'${fixedUrl}'`)}]})}}if(urlArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const firstQuasi=urlArg.quasis[0];if(firstQuasi&&CLEARTEXT_WS_SCHEME.test(firstQuasi.value.raw)){const authority=/^ws:\/\/([^/?#]*)/i.exec(firstQuasi.value.raw)?.[1];if(authority!==void 0&&authority!==""&&isNonTransmitting(`ws://${authority}`)){return}const sourceCode=context.sourceCode;const originalText=sourceCode.getText(urlArg);const fixedText=originalText.replace(/(?<=^.)ws:\/\//i,"wss://");context.report({node:urlArg,messageId:"insecureWebsocket",suggest:[{messageId:"useWss",fix:fixer=>fixer.replaceText(urlArg,fixedText)}]})}}}return{NewExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="WebSocket"){const urlArg=node.arguments[0];if(urlArg){checkWebSocketUrl(node,urlArg)}}}}}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isAnalyticsTransmission=isAnalyticsTransmission;const eslint_devkit_1=require("@interlace/eslint-devkit");const ANALYTICS_METHODS=new Map([["analytics",new Set(["track","identify","page","screen","group"])],["mixpanel",new Set(["track","identify","register"])],["posthog",new Set(["capture","identify","setPersonProperties"])],["amplitude",new Set(["track","logEvent","identify"])],["Sentry",new Set(["setUser","setContext"])],["dataLayer",new Set(["push"])]]);const ANALYTICS_FUNCTIONS=new Set(["gtag"]);const GLOBAL_ALIASES=new Set(["window","self","globalThis"]);function analyticsClientName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ANALYTICS_METHODS.has(node.name)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&ANALYTICS_METHODS.has(node.property.name)&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&GLOBAL_ALIASES.has(node.object.name)){return node.property.name}return null}function isAnalyticsTransmission(node,extraAnalyticsMethods=[]){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&ANALYTICS_FUNCTIONS.has(callee.name)){return true}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed||callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const client=analyticsClientName(callee.object);if(client===null)return false;const method=callee.property.name;if(ANALYTICS_METHODS.get(client)?.has(method)===true)return true;return client==="analytics"&&extraAnalyticsMethods.includes(method)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isCspDirectiveName=isCspDirectiveName;exports.cspSourceKeyword=cspSourceKeyword;exports.parsePolicy=parsePolicy;exports.policyGrantsKeyword=policyGrantsKeyword;exports.isCspSourceListElement=isCspSourceListElement;const CSP_DIRECTIVE_NAMES_KEBAB=["child-src","connect-src","default-src","fenced-frame-src","font-src","frame-src","img-src","manifest-src","media-src","object-src","prefetch-src","script-src","script-src-elem","script-src-attr","style-src","style-src-elem","style-src-attr","worker-src","base-uri","sandbox","form-action","frame-ancestors","navigate-to","report-uri","report-to","require-trusted-types-for","trusted-types","upgrade-insecure-requests","block-all-mixed-content","require-sri-for"];function toCamelCase(kebab){return kebab.replace(/-([a-z])/g,(_,c)=>c.toUpperCase())}const CSP_DIRECTIVE_NAMES=new Set([...CSP_DIRECTIVE_NAMES_KEBAB,...CSP_DIRECTIVE_NAMES_KEBAB.map(toCamelCase)]);function isCspDirectiveName(name){return CSP_DIRECTIVE_NAMES.has(name.toLowerCase())||CSP_DIRECTIVE_NAMES.has(name)}const CSP_KEYWORDS=new Set(["self","none","unsafe-eval","wasm-unsafe-eval","unsafe-inline","unsafe-hashes","strict-dynamic","report-sample","inline-speculation-rules","unsafe-allow-redirects"]);function cspSourceKeyword(source){const trimmed=source.trim().toLowerCase();const unquoted=trimmed.length>1&&trimmed.startsWith("'")&&trimmed.endsWith("'")?trimmed.slice(1,-1):trimmed;return CSP_KEYWORDS.has(unquoted)?unquoted:null}function parsePolicy(text){const directives=[];for(const segment of text.split(";")){const tokens=segment.trim().split(/\s+/).filter(Boolean);if(tokens.length===0)continue;if(!isCspDirectiveName(tokens[0]))continue;directives.push({name:tokens[0].toLowerCase(),sources:tokens.slice(1)})}return directives}function policyGrantsKeyword(text,keyword){return parsePolicy(text).some(directive=>directive.sources.some(source=>cspSourceKeyword(source)===keyword))}function isCspSourceListElement(node,sourceCode){const array=node.parent;if(array==null||array.type!=="ArrayExpression")return false;const owner=array.parent;if(owner.type==="Property"&&!owner.computed&&owner.value===array){const key=owner.key;if(key.type==="Identifier")return isCspDirectiveName(key.name);if(key.type==="Literal"&&typeof key.value==="string"){return isCspDirectiveName(key.value)}return false}if(owner.type==="VariableDeclarator"&&owner.id.type==="Identifier"){return isSplicedAfterDirectiveName(owner,sourceCode)}return false}function isSplicedAfterDirectiveName(declarator,sourceCode){for(const variable of sourceCode.getDeclaredVariables(declarator)){for(const reference of variable.references){if(reference.identifier.range[0]<declarator.range[1])continue;if(precedingQuasiEndsWithDirective(reference.identifier))return true}}return false}function precedingQuasiEndsWithDirective(node){let current=node;for(let depth=0;current!=null&&depth<6;depth++){const parent=current.parent;if(parent!=null&&parent.type==="TemplateLiteral"){const slot=parent.expressions.indexOf(current);const before=parent.quasis[slot].value.raw;const tokens=before.trim().split(/[\s;]+/).filter(Boolean);const last=tokens[tokens.length-1];return last!==void 0&&isCspDirectiveName(last)}current=parent}return false}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.dynamicCodeSink=dynamicCodeSink;const eslint_devkit_1=require("@interlace/eslint-devkit");const resolve_binding_1=require("./resolve-binding");const DYNAMIC_CODE_NAMES=new Set(["eval","Function","execScript"]);const GLOBAL_RECEIVERS=new Set(["window","self","globalThis","global"]);const TIMER_NAMES=new Set(["setTimeout","setInterval","setImmediate"]);function isUnshadowedGlobal(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length===0}return true}function bareGlobal(node,sourceCode){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(!DYNAMIC_CODE_NAMES.has(node.name))return null;return isUnshadowedGlobal(node,sourceCode)?node.name:null}function qualifiedGlobal(node,sourceCode){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!GLOBAL_RECEIVERS.has(node.object.name)||!isUnshadowedGlobal(node.object,sourceCode)){return null}const property=node.computed?literalString(node.property):node.property.name;if(property===null)return null;return DYNAMIC_CODE_NAMES.has(property)?property:null}function literalString(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"?node.value:null}function constructorChain(node){const isConstructorAccess=n=>n.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!n.computed&&n.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.property.name==="constructor";if(!isConstructorAccess(node))return null;return isConstructorAccess(node.object)?"Function":null}function sequenceCallee(node,sourceCode){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.SequenceExpression)return null;const last=node.expressions[node.expressions.length-1];return bareGlobal(last,sourceCode)}function aliasedGlobal(node,sourceCode){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);if(init===void 0)return null;return bareGlobal(init,sourceCode)??qualifiedGlobal(init,sourceCode)??constructorChain(init)}function isProvableString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isProvableString(node.left)||isProvableString(node.right)}return false}function timerName(callee,sourceCode){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TIMER_NAMES.has(callee.name)&&isUnshadowedGlobal(callee,sourceCode)){return callee.name}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&GLOBAL_RECEIVERS.has(callee.object.name)&&isUnshadowedGlobal(callee.object,sourceCode)&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TIMER_NAMES.has(callee.property.name)){return callee.property.name}return null}const LABELS={eval:"eval",Function:"Function constructor",execScript:"execScript"};function dynamicCodeSink(node,sourceCode){const callee=node.callee;const args=node.arguments;const direct=bareGlobal(callee,sourceCode);if(direct!==null){return{kind:"direct",name:direct,label:LABELS[direct],codeArguments:args}}const indirect=qualifiedGlobal(callee,sourceCode)??constructorChain(callee)??sequenceCallee(callee,sourceCode)??aliasedGlobal(callee,sourceCode);if(indirect!==null){return{kind:"indirect",name:indirect,label:LABELS[indirect],codeArguments:args}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const timer=timerName(callee,sourceCode);const body=args[0];if(timer!==null&&body!==void 0&&isProvableString(body)){return{kind:"timer",name:null,label:`${timer} with string`,codeArguments:[body]}}}return void 0}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isExpressAppOrRouter=isExpressAppOrRouter;exports.asExpressRouteRegistration=asExpressRouteRegistration;const eslint_devkit_1=require("@interlace/eslint-devkit");const ROUTER_RETURNING_METHODS=new Set(["route","use"]);function isExpressAppOrRouter(node,scope,seen=new Set){if(seen.has(node))return false;seen.add(node);if(node.type==="CallExpression"||node.type==="NewExpression"){const{callee}=node;if((0,eslint_devkit_1.isModuleBinding)(callee,scope,"express",[]))return true;if((0,eslint_devkit_1.isModuleBinding)(callee,scope,"express",["Router"]))return true;if(callee.type==="MemberExpression"&&!callee.computed&&callee.property.type==="Identifier"&&ROUTER_RETURNING_METHODS.has(callee.property.name)){return isExpressAppOrRouter(callee.object,scope,seen)}return false}if(node.type!=="Identifier")return false;for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable===void 0)continue;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.node.init===null)return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;return isExpressAppOrRouter(def.node.init,scope,seen)}return false}function asExpressRouteRegistration(node,scope,methods){const{callee}=node;if(callee.type!=="MemberExpression"||callee.computed||callee.property.type!=="Identifier"){return null}const method=callee.property.name;if(!methods.has(method.toLowerCase()))return null;if(!isExpressAppOrRouter(callee.object,scope))return null;if(isRouteCall(callee.object)){return node.arguments.length>0?{method,pathArg:null}:null}if(node.arguments.length<2)return null;if(!isRoutePath(node.arguments[0]))return null;return{method,pathArg:node.arguments[0]}}function isRouteCall(node){return node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&!node.callee.computed&&node.callee.property.type==="Identifier"&&node.callee.property.name==="route"}function isRoutePath(node){if(node.type==="Literal"){return typeof node.value==="string"||node.value instanceof RegExp}if(node.type==="TemplateLiteral")return true;if(node.type==="ArrayExpression"){return node.elements.length>0&&node.elements.every(el=>el!==null&&isRoutePath(el))}return false}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveGlobalObject=resolveGlobalObject;exports.isGlobalObject=isGlobalObject;const GLOBAL_ALIASES=new Set(["window","self","globalThis"]);function resolveGlobalObject(node,names){if(node.type==="Identifier"){return names.has(node.name)?node.name:null}if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&names.has(node.property.name)&&node.object.type==="Identifier"&&GLOBAL_ALIASES.has(node.object.name)){return node.property.name}return null}function isGlobalObject(node,names){return resolveGlobalObject(node,names)!==null}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isLocationTarget=isLocationTarget;exports.isLocationNavigationWrite=isLocationNavigationWrite;exports.isLocationNavigationCall=isLocationNavigationCall;exports.identityArgumentIndex=identityArgumentIndex;exports.isSteerableUrlValue=isSteerableUrlValue;exports.isRelativePathGuard=isRelativePathGuard;exports.isOriginEqualityGuard=isOriginEqualityGuard;exports.isOpaquePredicateOverTarget=isOpaquePredicateOverTarget;exports.isGuardedDestination=isGuardedDestination;exports.isRouterObject=isRouterObject;const eslint_devkit_1=require("@interlace/eslint-devkit");const url_taint_1=require("./url-taint");const resolve_binding_1=require("./resolve-binding");const LOCATION_HOLDERS=new Set(["window","document","self","top","parent","globalThis"]);const STEERABLE_LOCATION_PROPS=new Set(["href","search","hash","pathname"]);function staticKey(node){if(!node.computed){return node.property.type==="Identifier"?node.property.name:null}return node.property.type==="Literal"&&typeof node.property.value==="string"?node.property.value:null}function isLocationTarget(node){if(node.type==="Identifier"){return node.name==="location"}return node.type==="MemberExpression"&&staticKey(node)==="location"&&node.object.type==="Identifier"&&LOCATION_HOLDERS.has(node.object.name)}function isLocationNavigationWrite(node){if(node.type!=="MemberExpression")return false;if(isLocationTarget(node)&&node.object.type==="Identifier")return true;return staticKey(node)==="href"&&isLocationTarget(node.object)}function isLocationNavigationCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;const method=staticKey(callee);return(method==="assign"||method==="replace")&&isLocationTarget(callee.object)}function isSteerableLocationRead(node){if(node.type!=="MemberExpression")return false;const key=staticKey(node);return key!==null&&STEERABLE_LOCATION_PROPS.has(key)&&isLocationTarget(node.object)}const ROUTER_MODULES=["next/navigation","next/router","vue-router","react-router","react-router-dom","@tanstack/react-router"];const SEARCH_PARAM_MODULES=["next/navigation","react-router","react-router-dom"];function isHookCallFrom(node,sourceCode,hook,modules){if(node.type!=="CallExpression"||node.callee.type!=="Identifier"){return false}if(node.callee.name!==hook)return false;const scope=sourceCode.getScope(node.callee);return modules.some(module=>(0,eslint_devkit_1.isModuleBinding)(node.callee,scope,module,[hook]))}function urlContainerKind(node,sourceCode,seen){switch(node.type){case"NewExpression":{if(node.callee.type!=="Identifier")return null;const first=node.arguments[0];if(first===void 0||first.type==="SpreadElement")return null;if(node.callee.name==="URLSearchParams"){return isSteerableUrlValue(first,sourceCode,seen)?"params":null}if(node.callee.name==="URL"){return isSteerableUrlValue(first,sourceCode,seen)?"url":null}return null}case"MemberExpression":{if(staticKey(node)==="searchParams"&&urlContainerKind(node.object,sourceCode,seen)==="url"){return"params"}return null}case"CallExpression":{if(isHookCallFrom(node,sourceCode,"useSearchParams",SEARCH_PARAM_MODULES)){return"params"}return null}case"Identifier":{if(seen.has(node.name))return null;seen.add(node.name);const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:urlContainerKind(init,sourceCode,seen)}default:return null}}const PARAM_READERS=new Set(["get","getAll"]);function resolveFunctionNode(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 void 0;const def=variable.defs[0];if(def.type==="FunctionName"){return def.node.type==="FunctionDeclaration"?def.node:void 0}const init=(0,resolve_binding_1.resolveInitializer)(identifier,sourceCode);if(init!==void 0&&(init.type==="FunctionExpression"||init.type==="ArrowFunctionExpression")){return init}return void 0}return void 0}function identityArgumentIndex(node,sourceCode){if(node.callee.type!=="Identifier")return null;const fn=resolveFunctionNode(node.callee,sourceCode);if(fn===void 0)return null;const returned=fn.body.type==="BlockStatement"?fn.body.body.length===1&&fn.body.body[0].type==="ReturnStatement"?fn.body.body[0].argument:null:fn.body;if(returned===null||returned===void 0)return null;if(returned.type!=="Identifier")return null;const index=fn.params.findIndex(param=>param.type==="Identifier"&¶m.name===returned.name);return index===-1?null:index}function isSteerableUrlValue(node,sourceCode,seen=new Set){if((0,url_taint_1.isAttackerSteerableUrl)(node,sourceCode))return true;if(isSteerableLocationRead(node))return true;switch(node.type){case"CallExpression":{const callee=node.callee;if(callee.type==="MemberExpression"&&!callee.computed&&callee.property.type==="Identifier"&&PARAM_READERS.has(callee.property.name)&&urlContainerKind(callee.object,sourceCode,seen)==="params"){return true}const index=identityArgumentIndex(node,sourceCode);if(index!==null){const argument=node.arguments[index];return argument!==void 0&&argument.type!=="SpreadElement"&&isSteerableUrlValue(argument,sourceCode,seen)}return false}case"MemberExpression":{const key=staticKey(node);return key!==null&&STEERABLE_LOCATION_PROPS.has(key)&&urlContainerKind(node.object,sourceCode,seen)==="url"}case"Identifier":{if(seen.has(node.name))return false;seen.add(node.name);const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&isSteerableUrlValue(init,sourceCode,seen)}case"BinaryExpression":return node.operator==="+"&&isSteerableUrlValue(node.left,sourceCode,seen);case"TemplateLiteral":return node.quasis[0].value.cooked===""&&node.expressions.length>0&&isSteerableUrlValue(node.expressions[0],sourceCode,seen);case"LogicalExpression":return isSteerableUrlValue(node.left,sourceCode,seen)||isSteerableUrlValue(node.right,sourceCode,seen);case"ConditionalExpression":return isSteerableUrlValue(node.consequent,sourceCode,seen)||isSteerableUrlValue(node.alternate,sourceCode,seen);default:return false}}function isRelativePathGuard(test,sourceCode){const conjuncts=[];const flatten=node=>{if(node.type==="LogicalExpression"&&node.operator==="&&"){flatten(node.left);flatten(node.right);return}conjuncts.push(node)};flatten(test);const startsWith=(node,negated)=>{let current=node;let seenNegation=false;while(current.type==="UnaryExpression"&¤t.operator==="!"){seenNegation=!seenNegation;current=current.argument}if(seenNegation!==negated)return null;if(current.type!=="CallExpression"||current.callee.type!=="MemberExpression"||current.callee.computed||current.callee.property.type!=="Identifier"||current.callee.property.name!=="startsWith"){return null}const argument=current.arguments[0];if(argument===void 0||argument.type!=="Literal"||typeof argument.value!=="string"){return null}return{receiver:sourceCode.getText(current.callee.object),prefix:argument.value}};const rejectsBothViaRegex=conjuncts.some(conjunct=>{if(conjunct.type!=="CallExpression"||conjunct.callee.type!=="MemberExpression"||conjunct.callee.computed||conjunct.callee.property.type!=="Identifier"||conjunct.callee.property.name!=="test"||conjunct.callee.object.type!=="Literal"||!("regex"in conjunct.callee.object)||conjunct.callee.object.regex===void 0){return false}const{pattern}=conjunct.callee.object.regex;return pattern.startsWith("^\\/[^/")||pattern.startsWith("^\\/(?!\\/)")});if(rejectsBothViaRegex)return true;const positives=conjuncts.map(conjunct=>startsWith(conjunct,false)).filter(hit=>hit!==null).filter(hit=>hit.prefix==="/");if(positives.length===0)return false;return conjuncts.some(conjunct=>{const hit=startsWith(conjunct,true);return hit!==null&&hit.prefix==="//"&&positives.some(positive=>positive.receiver===hit.receiver)})}const ORIGIN_COMPONENTS=new Set(["origin","host","hostname"]);function isOriginEqualityGuard(test,sourceCode){const isParsedOriginRead=node=>node.type==="MemberExpression"&&ORIGIN_COMPONENTS.has(staticKey(node)??"")&&urlContainerKind(node.object,sourceCode,new Set)==="url";const visit=(node,depth)=>{if(depth>6)return false;switch(node.type){case"LogicalExpression":return visit(node.left,depth+1)||visit(node.right,depth+1);case"BinaryExpression":if(node.operator!=="==="&&node.operator!=="==")return false;return isParsedOriginRead(node.left)||isParsedOriginRead(node.right);default:return false}};return visit(test,0)}function resolvesToKnowableFunction(node,sourceCode){if(node.type!=="Identifier")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)continue;if(variable.defs.length!==1)return false;if(variable.defs[0].type==="FunctionName")return true;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&(init.type==="FunctionExpression"||init.type==="ArrowFunctionExpression")}return false}function isOpaquePredicateOverTarget(test,target,sourceCode){const targetText=sourceCode.getText(target);const visit=(node,depth)=>{if(depth>6)return false;if(node.type==="LogicalExpression"){return visit(node.left,depth+1)||visit(node.right,depth+1)}if(node.type!=="CallExpression")return false;const receivesTarget=node.arguments.some(argument=>argument.type!=="SpreadElement"&&sourceCode.getText(argument)===targetText);if(!receivesTarget)return false;return!resolvesToKnowableFunction(node.callee,sourceCode)};return visit(test,0)}function isGuardedDestination(node,target,sourceCode,provesSafe){const guards=test=>provesSafe(test)||isOpaquePredicateOverTarget(test,target,sourceCode);if(target.type==="ConditionalExpression"&&provesSafe(target.test)){return true}const guardedByEarlyExit=(block,child2)=>block.body.some(statement=>{if(statement.range[0]>=child2.range[0])return false;if(statement.type!=="IfStatement")return false;if(statement.test.type!=="UnaryExpression"||statement.test.operator!=="!"||!guards(statement.test.argument)){return false}const branch=statement.consequent;return branch.type==="ReturnStatement"||branch.type==="ThrowStatement"||branch.type==="BlockStatement"&&branch.body.some(s=>s.type==="ReturnStatement"||s.type==="ThrowStatement")});let child=node;let current=node.parent;let depth=0;while(current&&depth<20){if(current.type==="IfStatement"&&guards(current.test))return true;if((current.type==="BlockStatement"||current.type==="Program")&&guardedByEarlyExit(current,child)){return true}child=current;current=current.parent;depth++}return false}function isRouterObject(node,sourceCode){if(node.type!=="Identifier")return false;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&isHookCallFrom(init,sourceCode,"useRouter",ROUTER_MODULES)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NON_BEARER_SECRET_TERMS=exports.BEARER_CREDENTIAL_TERMS=void 0;exports.normalizeResourceKey=normalizeResourceKey;exports.namesMeasurementOnly=namesMeasurementOnly;exports.namesBearerCredential=namesBearerCredential;exports.namesNonBearerSecret=namesNonBearerSecret;exports.resolveStorageArea=resolveStorageArea;exports.memberName=memberName;exports.resolveKeyText=resolveKeyText;exports.isJwtLiteral=isJwtLiteral;exports.hasProvableJwtValue=hasProvableJwtValue;exports.isCacheStorageReceiver=isCacheStorageReceiver;exports.isIndexedDbStoreReceiver=isIndexedDbStoreReceiver;exports.isIdbWrapperDatabase=isIdbWrapperDatabase;exports.isDocumentCookieTarget=isDocumentCookieTarget;exports.staticCookieText=staticCookieText;exports.cookieNameFrom=cookieNameFrom;exports.isCookieDeletion=isCookieDeletion;const eslint_devkit_1=require("@interlace/eslint-devkit");const global_object_1=require("./global-object");const resolve_binding_1=require("./resolve-binding");exports.BEARER_CREDENTIAL_TERMS=["jwt","token","bearer","auth","authorization","session","sid","credential","credentials"];exports.NON_BEARER_SECRET_TERMS=["password","passwd","pwd","passphrase","secret","api key","apikey","private key","secret key","encryption key","signing key","client secret","credit card","card number","cvv","cvc","ssn","social security","seed phrase","mnemonic","recovery code"];function normalizeResourceKey(key){return key.replace(/[/?&=:#%+*]+/g,"-")}const MEASUREMENT_TERMS=["count","length","size","limit","total","index","offset","expiry","expires","expiration","ttl","timeout","version","enabled","visible"];function singularizeWords(key){return(0,eslint_devkit_1.identifierWords)(normalizeResourceKey(key)).map(w=>w.length>3&&w.endsWith("s")&&!w.endsWith("ss")?w.slice(0,-1):w).join(" ")}function namesMeasurementOnly(key){return(0,eslint_devkit_1.nameHasAnyWord)(singularizeWords(key),MEASUREMENT_TERMS)}function namesBearerCredential(key,terms=exports.BEARER_CREDENTIAL_TERMS){return!namesMeasurementOnly(key)&&(0,eslint_devkit_1.nameHasAnyWord)(singularizeWords(key),terms)}function namesNonBearerSecret(key,terms=exports.NON_BEARER_SECRET_TERMS){return!namesMeasurementOnly(key)&&(0,eslint_devkit_1.nameHasAnyWord)(singularizeWords(key),terms)}function lookupVariable(name,scope){for(let s=scope;s!==null;s=s.upper){const found=s.variables.find(v=>v.name===name);if(found!==void 0)return found}return null}const GLOBAL_ALIASES=new Set(["window","self","globalThis"]);function destructuredGlobalName(variable,names){const def=variable.defs[0];if(def===void 0||def.type!=="Variable")return null;if(def.node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return null;const init=def.node.init;if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!GLOBAL_ALIASES.has(init.name)){return null}for(const property of def.node.id.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;if(!names.has(property.key.name))continue;if(property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===variable.name){return property.key.name}}return null}function resolveStorageArea(node,sourceCode,names){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=lookupVariable(node.name,sourceCode.getScope(node));if(variable===null||variable.defs.length===0){return names.has(node.name)?node.name:null}return destructuredGlobalName(variable,names)}return(0,global_object_1.resolveGlobalObject)(node,names)}function memberName(member,sourceCode){if(!member.computed){return member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?member.property.name:null}if(member.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof member.property.value==="string"){return member.property.value}if(member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&sourceCode){const init=(0,resolve_binding_1.resolveInitializer)(member.property,sourceCode);if(init!==void 0&&init.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof init.value==="string"){return init.value}}return null}const UNKNOWN="*";function resolveKeyText(node,sourceCode,followBinding=true){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(UNKNOWN)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveKeyText(node.left,sourceCode,followBinding);const right=resolveKeyText(node.right,sourceCode,followBinding);if(left===null&&right===null)return null;return(left??UNKNOWN)+(right??UNKNOWN)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&followBinding){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);if(init!==void 0&&(init.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||init.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)){const composed=resolveKeyText(init,sourceCode,false);if(composed!==null)return composed}}return(0,resolve_binding_1.resolveStringKey)(node,sourceCode)}const BASE64URL_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function decodeBase64Url(segment){let bits=0;let acc=0;let out="";for(const ch of segment){acc=acc<<6|BASE64URL_ALPHABET.indexOf(ch);bits+=6;if(bits>=8){bits-=8;out+=String.fromCharCode(acc>>bits&255)}}return out}const JWT_SHAPE=/^([A-Za-z0-9_-]{8,})\.([A-Za-z0-9_-]{2,})\.([A-Za-z0-9_-]*)$/;function isJwtLiteral(value){const shape=JWT_SHAPE.exec(value);if(shape===null)return false;let header;try{header=JSON.parse(decodeBase64Url(shape[1]))}catch{return false}return typeof header==="object"&&header!==null&&"alg"in header}const JWT_MINTING_MODULES=new Set(["jsonwebtoken","jose"]);function hasProvableJwtValue(node,sourceCode,followBinding=true){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return isJwtLiteral(node.value)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length===0){return isJwtLiteral(node.quasis[0].value.raw)}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&&JWT_MINTING_MODULES.has(binding.module)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&followBinding){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&hasProvableJwtValue(init,sourceCode,false)}return false}const CACHE_STORAGE_GLOBAL=new Set(["caches"]);function unwrapAwait(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?node.argument:node}function isCachesOpenCall(node){const call=unwrapAwait(node);return call.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!call.callee.computed&&call.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&call.callee.property.name==="open"&&(0,global_object_1.resolveGlobalObject)(call.callee.object,CACHE_STORAGE_GLOBAL)!==null}function isCachesOpenThenParameter(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 false;const call=def.node.parent;return call!==void 0&&call.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!call.callee.computed&&call.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&call.callee.property.name==="then"&&isCachesOpenCall(call.callee.object)}return false}function isCacheStorageReceiver(node,sourceCode){if(isCachesOpenCall(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);if(init!==void 0&&isCachesOpenCall(init))return true;return isCachesOpenThenParameter(node,sourceCode)}function isObjectStoreCall(node){const call=unwrapAwait(node);return call.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!call.callee.computed&&call.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(call.callee.property.name==="objectStore"||call.callee.property.name==="createObjectStore")}function isIndexedDbStoreReceiver(node,sourceCode,hops=3){if(isObjectStoreCall(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||hops===0)return false;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init!==void 0&&isIndexedDbStoreReceiver(init,sourceCode,hops-1)}const IDB_WRAPPER_MODULES=new Set(["idb"]);function isIdbWrapperDatabase(node,sourceCode){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);if(init===void 0)return false;const call=unwrapAwait(init);if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const binding=(0,eslint_devkit_1.resolveModuleBinding)(call.callee,sourceCode.getScope(node));return binding!==void 0&&IDB_WRAPPER_MODULES.has(binding.module)}const DOCUMENT_GLOBAL=new Set(["document"]);function isDocumentCookieTarget(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&memberName(node)==="cookie"&&(0,global_object_1.resolveGlobalObject)(node.object,DOCUMENT_GLOBAL)!==null}const OPAQUE="\0";function staticCookieText(node,sourceCode,followBinding=true){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(OPAQUE)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=staticCookieText(node.left,sourceCode,followBinding);const right=staticCookieText(node.right,sourceCode,followBinding);if(left===null&&right===null)return null;return(left??OPAQUE)+(right??OPAQUE)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&followBinding){const init=(0,resolve_binding_1.resolveInitializer)(node,sourceCode);return init===void 0?null:staticCookieText(init,sourceCode,false)}return null}function cookieNameFrom(text){const equals=text.indexOf("=");if(equals<=0)return null;const name=text.slice(0,equals).trim();return name.includes(OPAQUE)?null:name}function isCookieDeletion(text){const[pair]=text.split(";");const equals=pair.indexOf("=");if(equals<0||pair.slice(equals+1).trim().length>0)return false;return/;\s*(?:max-age\s*=\s*(?:0|-\d+)|expires\s*=)/i.test(text)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isRequestCallSiteUrl=isRequestCallSiteUrl;exports.isRequestCall=isRequestCall;exports.isWebSocketConstructorUrl=isWebSocketConstructorUrl;exports.isSubresourcePosition=isSubresourcePosition;const eslint_devkit_1=require("@interlace/eslint-devkit");const global_object_1=require("./global-object");const FETCH_NAMES=new Set(["fetch"]);const AXIOS_HTTP_METHODS=new Set(["get","post","put","delete","patch","head","options"]);function argumentAncestor(node){let current=node;let parent=current.parent;while(parent!==void 0&&(parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&parent.operator==="+")){current=parent;parent=current.parent}return current}function isRequestCallSiteUrl(node,scope){const argument=argumentAncestor(node);const call=argument.parent;return call?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.arguments[0]===argument&&isRequestCall(call,scope)}function isRequestCall(call,scope){const callee=call.callee;if((0,global_object_1.isGlobalObject)(callee,FETCH_NAMES)){return true}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed||callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!AXIOS_HTTP_METHODS.has(callee.property.name)){return false}return isAxiosClient(callee.object,scope)}function isAxiosClient(receiver,scope){if((0,eslint_devkit_1.isModuleBinding)(receiver,scope,"axios")){return true}return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&receiver.name==="axios"}function isWebSocketConstructorUrl(node){const argument=argumentAncestor(node);const call=argument.parent;return call?.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&call.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&call.callee.name==="WebSocket"&&call.arguments[0]===argument}const SUBRESOURCE_ATTRIBUTES=new Map([["img",new Set(["src","srcSet","srcset"])],["image",new Set(["src","href","xlinkHref"])],["script",new Set(["src"])],["link",new Set(["href"])],["iframe",new Set(["src"])],["frame",new Set(["src"])],["embed",new Set(["src"])],["object",new Set(["data"])],["video",new Set(["src","poster"])],["audio",new Set(["src"])],["source",new Set(["src","srcSet","srcset"])],["track",new Set(["src"])],["input",new Set(["src"])],["form",new Set(["action"])]]);const SUBRESOURCE_PROPERTIES=new Set(["src","srcset","poster"]);const SUBRESOURCE_LOADERS=new Set(["importScripts"]);function isSubresourcePosition(node){const value=argumentAncestor(node);const parent=value.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute&&parent.value===value&&parent.name.type===eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier){return isSubresourceJsxAttribute(parent,parent.name.name)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXExpressionContainer&&parent.parent?.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute&&parent.parent.name.type===eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier){return isSubresourceJsxAttribute(parent.parent,parent.parent.name.name)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===value&&parent.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&SUBRESOURCE_PROPERTIES.has(propertyNameOf(parent.left)??"")){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=parent.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&SUBRESOURCE_LOADERS.has(callee.name)&&parent.arguments.includes(value)){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(SUBRESOURCE_LOADERS.has(callee.property.name)&&parent.arguments.includes(value)){return true}if(callee.property.name==="setAttribute"&&parent.arguments[1]===value&&parent.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof parent.arguments[0].value==="string"&&SUBRESOURCE_PROPERTIES.has(parent.arguments[0].value.toLowerCase())){return true}}}return false}const FETCHING_LINK_RELS=new Set(["stylesheet","preload","modulepreload","prefetch","prerender","icon","apple-touch-icon","apple-touch-startup-image","mask-icon","manifest","preconnect","dns-prefetch"]);function isSubresourceJsxAttribute(attribute,attributeName){const element=attribute.parent;const name=element.name;if(name.type!==eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier){return false}const attributes=SUBRESOURCE_ATTRIBUTES.get(name.name);if(attributes===void 0||!attributes.has(attributeName)){return false}if(name.name==="link"){return hasFetchingRel(element)}return true}function hasFetchingRel(element){for(const attribute of element.attributes){if(attribute.type!==eslint_devkit_1.AST_NODE_TYPES.JSXAttribute||attribute.name.type!==eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier||attribute.name.name!=="rel"){continue}const value=attribute.value;const rel=value?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"?value.value:void 0;if(rel===void 0){return false}return rel.toLowerCase().split(/\s+/).some(token=>FETCHING_LINK_RELS.has(token))}return false}function propertyNameOf(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}if(member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof member.property.value==="string"){return member.property.value}return void 0}
|
package/src/utils/url-taint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isLocationObject=isLocationObject;exports.isAttackerSteerableUrl=isAttackerSteerableUrl;const resolve_binding_1=require("./resolve-binding");const STEERABLE_LOCATION_PROPS=new Set(["href","search","hash","pathname"]);const LOCATION_HOLDERS=new Set(["window","document","self","top","parent","globalThis"]);const REQUEST_INPUT_PROPS=new Set(["query","body","params"]);function isLocationObject(node){if(node.type==="Identifier"){return node.name==="location"}return node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="location"&&node.object.type==="Identifier"&&LOCATION_HOLDERS.has(node.object.name)}function isRequestInput(node){let current=node;let sawInputProp=false;while(current.type==="MemberExpression"){if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.STEERABILITY_PRESERVING_FUNCTIONS=exports.STEERABILITY_PRESERVING_METHODS=void 0;exports.isLocationObject=isLocationObject;exports.resolveBoundInitializer=resolveBoundInitializer;exports.isAttackerSteerableUrl=isAttackerSteerableUrl;const resolve_binding_1=require("./resolve-binding");const STEERABLE_LOCATION_PROPS=new Set(["href","search","hash","pathname"]);const LOCATION_HOLDERS=new Set(["window","document","self","top","parent","globalThis"]);const REQUEST_INPUT_PROPS=new Set(["query","body","params"]);function isLocationObject(node){if(node.type==="Identifier"){return node.name==="location"}return node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="location"&&node.object.type==="Identifier"&&LOCATION_HOLDERS.has(node.object.name)}function isRequestInput(node){let current=node;let sawInputProp=false;while(current.type==="MemberExpression"){const property=staticProperty(current);if(property!==null&&REQUEST_INPUT_PROPS.has(property)){sawInputProp=true}current=current.object}return sawInputProp&¤t.type==="Identifier"&&(current.name==="req"||current.name==="request")}exports.STEERABILITY_PRESERVING_METHODS=new Set(["slice","substring","substr","trim","trimStart","trimEnd","toString","toLowerCase","toUpperCase","normalize","valueOf"]);exports.STEERABILITY_PRESERVING_FUNCTIONS=new Set(["decodeURI","decodeURIComponent","unescape","String"]);function staticProperty(node){if(!node.computed){return node.property.type==="Identifier"?node.property.name:null}return node.property.type==="Literal"&&typeof node.property.value==="string"?node.property.value:null}function resolveBoundInitializer(identifier,sourceCode){const init=(0,resolve_binding_1.resolveInitializer)(identifier,sourceCode);if(init===void 0)return void 0;const declarator=init.parent;if(declarator?.type==="VariableDeclarator"&&declarator.id.type!=="Identifier"){return void 0}return init}function isSteerableMember(node){const property=staticProperty(node);if(property===null){return isRequestInput(node)}if(STEERABLE_LOCATION_PROPS.has(property)&&isLocationObject(node.object)){return true}if((property==="URL"||property==="referrer")&&node.object.type==="Identifier"&&node.object.name==="document"){return true}return isRequestInput(node)}const URL_CONSTRUCTORS=new Set(["URL"]);const PARAMS_CONSTRUCTORS=new Set(["URLSearchParams"]);const PARAMS_READERS=new Set(["get","getAll"]);const URL_STRINGIFIERS=new Set(["toString","toJSON","valueOf"]);function isUnshadowedGlobal(node,names,sourceCode){if(node.type!=="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 urlContainerKind(node,sourceCode,seen){switch(node.type){case"NewExpression":{const[argument]=node.arguments;if(argument===void 0||argument.type==="SpreadElement"){return null}if(!isAttackerSteerableUrl(argument,sourceCode,seen))return null;if(isUnshadowedGlobal(node.callee,PARAMS_CONSTRUCTORS,sourceCode)){return"params"}if(isUnshadowedGlobal(node.callee,URL_CONSTRUCTORS,sourceCode)){return"url"}return null}case"MemberExpression":{if(staticProperty(node)!=="searchParams"){return null}return urlContainerKind(node.object,sourceCode,seen)==="url"?"params":null}case"Identifier":{if(seen.has(node.name))return null;seen.add(node.name);const init=resolveBoundInitializer(node,sourceCode);return init===void 0?null:urlContainerKind(init,sourceCode,seen)}default:return null}}function isUrlContainerRead(node,sourceCode,seen){const probe=new Set(seen);if(node.type==="CallExpression"){const callee=node.callee;if(callee.type!=="MemberExpression")return false;const reader=staticProperty(callee);if(reader===null)return false;const kind=urlContainerKind(callee.object,sourceCode,probe);if(kind==="params")return PARAMS_READERS.has(reader);return kind==="url"&&URL_STRINGIFIERS.has(reader)}const property=staticProperty(node);return property!==null&&STEERABLE_LOCATION_PROPS.has(property)&&urlContainerKind(node.object,sourceCode,probe)==="url"}function isAttackerSteerableUrl(node,sourceCode,seen=new Set){switch(node.type){case"MemberExpression":return isSteerableMember(node)||isUrlContainerRead(node,sourceCode,seen);case"Identifier":{if(seen.has(node.name))return false;seen.add(node.name);const init=resolveBoundInitializer(node,sourceCode);return init!==void 0&&isAttackerSteerableUrl(init,sourceCode,seen)}case"BinaryExpression":return node.operator==="+"&&isAttackerSteerableUrl(node.left,sourceCode,seen);case"TemplateLiteral":return node.quasis[0].value.cooked===""&&node.expressions.length>0&&isAttackerSteerableUrl(node.expressions[0],sourceCode,seen);case"CallExpression":{if(isUrlContainerRead(node,sourceCode,seen))return true;const callee=node.callee;if(callee.type==="MemberExpression"&&!callee.computed&&callee.property.type==="Identifier"&&exports.STEERABILITY_PRESERVING_METHODS.has(callee.property.name)){return isAttackerSteerableUrl(callee.object,sourceCode,seen)}if(callee.type==="Identifier"&&exports.STEERABILITY_PRESERVING_FUNCTIONS.has(callee.name)&&node.arguments.length>0){return isAttackerSteerableUrl(node.arguments[0],sourceCode,seen)}return false}case"ConditionalExpression":return isAttackerSteerableUrl(node.consequent,sourceCode,seen)||isAttackerSteerableUrl(node.alternate,sourceCode,seen);case"LogicalExpression":return isAttackerSteerableUrl(node.left,sourceCode,seen)||isAttackerSteerableUrl(node.right,sourceCode,seen);default:return false}}
|