eslint-plugin-postgresql-security 2.4.0 → 2.6.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/check-query-params/index.js +1 -1
- package/src/rules/no-batch-insert-loop/index.js +1 -1
- package/src/rules/no-floating-query/index.js +1 -1
- package/src/rules/no-hardcoded-credentials/index.js +1 -1
- package/src/rules/no-insecure-ssl/index.js +1 -1
- package/src/rules/no-missing-client-release/index.js +1 -1
- package/src/rules/no-select-all/index.js +1 -1
- package/src/rules/no-transaction-on-pool/index.js +1 -1
- package/src/rules/no-unsafe-copy-from/index.js +1 -1
- package/src/rules/no-unsafe-query/index.js +1 -1
- package/src/rules/no-unsafe-search-path/index.js +1 -1
- package/src/rules/prefer-pool-query/index.js +1 -1
- package/src/rules/prevent-double-release/index.js +1 -1
- package/src/utils/connection-config.js +1 -1
- package/src/utils/cross-file.js +1 -0
- package/src/utils/index.js +1 -1
- package/src/utils/pool-receiver.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-postgresql-security",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.6.0",
|
|
4
4
|
"description": "ESLint plugin for the pg PostgreSQL driver — detects SQL injection, unreleased clients, floating queries, unsafe search_path, and insecure SSL.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
}
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@interlace/eslint-devkit": "^1.
|
|
79
|
+
"@interlace/eslint-devkit": "^1.20.0"
|
|
80
80
|
},
|
|
81
81
|
"funding": {
|
|
82
82
|
"type": "github",
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-unsafe-query"(){return require("./rules/no-unsafe-query").noUnsafeQuery},get"no-insecure-ssl"(){return require("./rules/no-insecure-ssl").noInsecureSsl},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"check-query-params"(){return require("./rules/check-query-params").checkQueryParams},get"no-missing-client-release"(){return require("./rules/no-missing-client-release").noMissingClientRelease},get"no-transaction-on-pool"(){return require("./rules/no-transaction-on-pool").noTransactionOnPool},get"no-floating-query"(){return require("./rules/no-floating-query").noFloatingQuery},get"no-select-all"(){return require("./rules/no-select-all").noSelectAll},get"prefer-pool-query"(){return require("./rules/prefer-pool-query").preferPoolQuery},get"no-batch-insert-loop"(){return require("./rules/no-batch-insert-loop").noBatchInsertLoop},get"no-unsafe-search-path"(){return require("./rules/no-unsafe-search-path").noUnsafeSearchPath},get"no-unsafe-copy-from"(){return require("./rules/no-unsafe-copy-from").noUnsafeCopyFrom},get"prevent-double-release"(){return require("./rules/prevent-double-release").preventDoubleRelease}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-postgresql-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-postgresql-security",version:"2.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-unsafe-query"(){return require("./rules/no-unsafe-query").noUnsafeQuery},get"no-insecure-ssl"(){return require("./rules/no-insecure-ssl").noInsecureSsl},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"check-query-params"(){return require("./rules/check-query-params").checkQueryParams},get"no-missing-client-release"(){return require("./rules/no-missing-client-release").noMissingClientRelease},get"no-transaction-on-pool"(){return require("./rules/no-transaction-on-pool").noTransactionOnPool},get"no-floating-query"(){return require("./rules/no-floating-query").noFloatingQuery},get"no-select-all"(){return require("./rules/no-select-all").noSelectAll},get"prefer-pool-query"(){return require("./rules/prefer-pool-query").preferPoolQuery},get"no-batch-insert-loop"(){return require("./rules/no-batch-insert-loop").noBatchInsertLoop},get"no-unsafe-search-path"(){return require("./rules/no-unsafe-search-path").noUnsafeSearchPath},get"no-unsafe-copy-from"(){return require("./rules/no-unsafe-copy-from").noUnsafeCopyFrom},get"prevent-double-release"(){return require("./rules/prevent-double-release").preventDoubleRelease}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-postgresql-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-postgresql-security",version:"2.6.0"},rules:exports.rules};exports.configs={flagship:{plugins:{"postgresql-security":exports.plugin,"pg":exports.plugin},rules:{"postgresql-security/no-unsafe-query":"error"}},recommended:{plugins:{"postgresql-security":exports.plugin,"pg":exports.plugin},rules:{"postgresql-security/no-unsafe-query":"error","postgresql-security/no-insecure-ssl":"error","postgresql-security/no-hardcoded-credentials":"error","postgresql-security/no-unsafe-search-path":"error","postgresql-security/no-unsafe-copy-from":"error","postgresql-security/no-transaction-on-pool":"error","postgresql-security/no-missing-client-release":"error","postgresql-security/prevent-double-release":"warn","postgresql-security/no-floating-query":"warn","postgresql-security/check-query-params":"warn","postgresql-security/no-select-all":"warn","postgresql-security/prefer-pool-query":"warn","postgresql-security/no-batch-insert-loop":"warn"}},strict:{plugins:{"postgresql-security":exports.plugin,"pg":exports.plugin},rules:{"postgresql-security/no-unsafe-query":"error","postgresql-security/no-insecure-ssl":"error","postgresql-security/no-hardcoded-credentials":"error","postgresql-security/no-unsafe-search-path":"error","postgresql-security/no-unsafe-copy-from":"error","postgresql-security/no-transaction-on-pool":"error","postgresql-security/no-missing-client-release":"error","postgresql-security/prevent-double-release":"error","postgresql-security/no-floating-query":"error","postgresql-security/check-query-params":"error","postgresql-security/no-select-all":"error","postgresql-security/prefer-pool-query":"error","postgresql-security/no-batch-insert-loop":"error"}}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.checkQueryParams=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const sql_scan_1=require("../../utils/sql-scan");const SQL_SINK_METHODS=new Set(["query","execute"]);const PLACEHOLDER=/\$(\d+)/g;const MAX_RESOLUTION_DEPTH=4;function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(tag)==="raw"}function singleAssignedInit(variable){if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const[only]=body.body;if(body.body.length!==1||only.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument===null?null:returnedExpression(only.argument)}return body}function effectiveExpression(node,scope,depth=0){if(depth>=MAX_RESOLUTION_DEPTH)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return isStringRawTag(node)?node.quasi:node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=variable===null?null:singleAssignedInit(variable);return init===null?node:effectiveExpression(init,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:effectiveExpression(returned,scope,depth+1)}return node}function knowableText(node){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.TemplateLiteral){if(node.expressions.length>0)return null;const[{value}]=node.quasis;return value.cooked??value.raw}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=knowableText(node.left);const right=knowableText(node.right);return left===null||right===null?null:left+right}return null}function highestPlaceholder(text){const executable=(0,sql_scan_1.blankNonPlaceholderText)(text);let highest=0;for(const match of executable.matchAll(PLACEHOLDER)){highest=Math.max(highest,Number.parseInt(match[1],10))}return highest}function knowableValueCount(node,scope){const resolved=effectiveExpression(node,scope);if(resolved.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;if(resolved.elements.some(el=>el!==null&&el.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)){return null}return resolved.elements.length}function configPair(node){let text=null;let values=null;for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=(0,eslint_devkit_1.objectKeyName)(property);if(name==="text")text=property.value;if(name==="values")values=property.value}return text!==null&&values!==null?{text,values}:null}exports.checkQueryParams={meta:{type:"problem",docs:{description:"Ensure the number of query parameters matches the arguments array.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/check-query-params.md",cwe:"CWE-20",cvss:7.5},messages:{parameterCountMismatch:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.QUALITY,issueName:"Parameter Count Mismatch",description:"Query parameter count mismatch detected: {{expected}} placeholder(s), {{actual}} value(s).",severity:"HIGH",cwe:"CWE-20",effort:"low",fix:"Ensure the number of arguments matches the number of placeholders ($1, $2, etc.).",documentationLink:"https://node-postgres.com/features/queries"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.checkQueryParams=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const sql_scan_1=require("../../utils/sql-scan");const SQL_SINK_METHODS=new Set(["query","execute"]);const PLACEHOLDER=/\$(\d+)/g;const MAX_RESOLUTION_DEPTH=4;function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(tag)==="raw"}function singleAssignedInit(variable){if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const[only]=body.body;if(body.body.length!==1||only.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument===null?null:returnedExpression(only.argument)}return body}function effectiveExpression(node,scope,depth=0){if(depth>=MAX_RESOLUTION_DEPTH)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return isStringRawTag(node)?node.quasi:node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=variable===null?null:singleAssignedInit(variable);return init===null?node:effectiveExpression(init,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:effectiveExpression(returned,scope,depth+1)}return node}function knowableText(node){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.TemplateLiteral){if(node.expressions.length>0)return null;const[{value}]=node.quasis;return value.cooked??value.raw}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=knowableText(node.left);const right=knowableText(node.right);return left===null||right===null?null:left+right}return null}function highestPlaceholder(text){const executable=(0,sql_scan_1.blankNonPlaceholderText)(text);let highest=0;for(const match of executable.matchAll(PLACEHOLDER)){highest=Math.max(highest,Number.parseInt(match[1],10))}return highest}function knowableValueCount(node,scope){const resolved=effectiveExpression(node,scope);if(resolved.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;if(resolved.elements.some(el=>el!==null&&el.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)){return null}return resolved.elements.length}function configPair(node){let text=null;let values=null;for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=(0,eslint_devkit_1.objectKeyName)(property);if(name==="text")text=property.value;if(name==="values")values=property.value}return text!==null&&values!==null?{text,values}:null}exports.checkQueryParams={meta:{type:"problem",docs:{description:"Ensure the number of query parameters matches the arguments array.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/check-query-params.md",cwe:"CWE-20",cvss:7.5},messages:{parameterCountMismatch:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.QUALITY,issueName:"Parameter Count Mismatch",description:"Query parameter count mismatch detected: {{expected}} placeholder(s), {{actual}} value(s).",severity:"HIGH",cwe:"CWE-20",effort:"low",fix:"Ensure the number of arguments matches the number of placeholders ($1, $2, etc.).",documentationLink:"https://node-postgres.com/features/queries"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};const check=(textNode,valuesNode,scope)=>{const text=knowableText(effectiveExpression(textNode,scope));if(text===null)return;const provided=knowableValueCount(valuesNode,scope);if(provided===null)return;const highest=highestPlaceholder(text);const mismatched=provided<highest||highest>=1&&provided>highest;if(!mismatched)return;context.report({node:valuesNode,messageId:"parameterCountMismatch",data:{expected:highest.toString(),actual:provided.toString()}})};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||!SQL_SINK_METHODS.has(node.callee.property.name)){return}const[first,second]=node.arguments;if(first===void 0||first.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return;const scope=context.sourceCode.getScope(node);const resolved=effectiveExpression(first,scope);if(resolved.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const pair=configPair(resolved);if(pair!==null)check(pair.text,pair.values,scope);return}if(second===void 0||second.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return;check(first,second,scope)}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noBatchInsertLoop=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const query_call_1=require("../../utils/query-call");const ITERATION_METHODS=new Set(["forEach","filter","reduce","reduceRight","some","every","find","findIndex","findLast","findLastIndex"]);const TRANSPARENT_METHODS=new Set(["then","catch","finally","map","flatMap"]);const WRITE_MAPPING_METHODS=new Set(["map","flatMap","from"]);const WRITE_STATEMENT=/^\s*(?:insert\s+into|update\b[\s\S]*\bset\b|delete\s+from|merge\s+into)\b/i;const BATCHED_STATEMENT=/\bunnest\s*\(|\bjsonb?_to_recordset\s*\(|%L/i;const LIMIT=/\bLIMIT\b/i;const OFFSET=/\bOFFSET\b/i;function isLoop(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement}function isFunction(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression}function callbackMethod(fn){const call=fn.parent;if(call===void 0||call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return null;if(call.callee===fn)return"iife";if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}return call.callee.property.name}function iterationContext(start,writes){for(let node=start.parent;node;node=node.parent){if(isLoop(node))return{kind:"loop",node};if(!isFunction(node))continue;const method=callbackMethod(node);if(method===null)return null;if(ITERATION_METHODS.has(method))return{kind:"method"};if(writes&&WRITE_MAPPING_METHODS.has(method))return{kind:"method"};if(method!=="iife"&&!TRANSPARENT_METHODS.has(method))return null}return null}function statementText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const[first]=node.arguments;return first===void 0?null:statementText(first)}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.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.cooked).join(" 1 ")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!property.computed&&property.key.name==="text");return text===void 0?null:statementText(text.value)}return null}function isPagination(text,context){if(text===null||!LIMIT.test(text))return false;if(OFFSET.test(text))return true;return context.kind==="loop"&&(context.node.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||context.node.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement||context.node.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement&&context.node.test===null)}exports.noBatchInsertLoop={meta:{type:"problem",docs:{description:"Prevent executing database queries within loops (N+1 problem).",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-batch-insert-loop.md",cwe:"CWE-1049",cvss:7.5},messages:{noBatchInsertLoop:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"N+1 Query Detection",description:"Database query loop detected.",severity:"HIGH",cwe:"CWE-1049",effort:"medium",fix:'Batch queries using arrays and "UNNEST" or a single batched INSERT.',documentationLink:"https://use-the-index-luke.com/sql/joins/nested-loops-join-n1-problem"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noBatchInsertLoop=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const query_call_1=require("../../utils/query-call");const ITERATION_METHODS=new Set(["forEach","filter","reduce","reduceRight","some","every","find","findIndex","findLast","findLastIndex"]);const TRANSPARENT_METHODS=new Set(["then","catch","finally","map","flatMap"]);const WRITE_MAPPING_METHODS=new Set(["map","flatMap","from"]);const WRITE_STATEMENT=/^\s*(?:insert\s+into|update\b[\s\S]*\bset\b|delete\s+from|merge\s+into)\b/i;const BATCHED_STATEMENT=/\bunnest\s*\(|\bjsonb?_to_recordset\s*\(|%L/i;const LIMIT=/\bLIMIT\b/i;const OFFSET=/\bOFFSET\b/i;function isLoop(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement}function isFunction(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression}function callbackMethod(fn){const call=fn.parent;if(call===void 0||call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return null;if(call.callee===fn)return"iife";if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}return call.callee.property.name}function iterationContext(start,writes){for(let node=start.parent;node;node=node.parent){if(isLoop(node))return{kind:"loop",node};if(!isFunction(node))continue;const method=callbackMethod(node);if(method===null)return null;if(ITERATION_METHODS.has(method))return{kind:"method",node};if(writes&&WRITE_MAPPING_METHODS.has(method))return{kind:"method",node};if(method!=="iife"&&!TRANSPARENT_METHODS.has(method))return null}return null}function configValue(object,key){const found=object.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(p)===key);return found?.value}function within(node,container){return node.range[0]>=container.range[0]&&node.range[1]<=container.range[1]}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function variesPerIteration(node,iteration,sourceCode,seen){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=lookup(node.name,sourceCode.getScope(node));if(variable===null||seen.has(variable))return false;seen.add(variable);if(variable.defs.some(def=>within(def.name,iteration)&&(def.type==="Parameter"||def.node.parent?.parent===iteration))){return true}return variable.references.some(ref=>ref.isWrite()&&within(ref.identifier,iteration)&&(ref.writeExpr==null||variesPerIteration(ref.writeExpr,iteration,sourceCode,seen)))}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;if(key==="property"&&node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed)continue;if(key==="key"&&node.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!node.computed)continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(typeof child==="object"&&child!==null&&typeof child.type==="string"&&variesPerIteration(child,iteration,sourceCode,seen)){return true}}}return false}function statementText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const[first]=node.arguments;return first===void 0?null:statementText(first)}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.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.cooked).join(" 1 ")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!property.computed&&property.key.name==="text");return text===void 0?null:statementText(text.value)}return null}function isPagination(text,context){if(text===null||!LIMIT.test(text))return false;if(OFFSET.test(text))return true;return context.kind==="loop"&&(context.node.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||context.node.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement||context.node.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement&&context.node.test===null)}exports.noBatchInsertLoop={meta:{type:"problem",docs:{description:"Prevent executing database queries within loops (N+1 problem).",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-batch-insert-loop.md",cwe:"CWE-1049",cvss:7.5},messages:{noBatchInsertLoop:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"N+1 Query Detection",description:"Database query loop detected.",severity:"HIGH",cwe:"CWE-1049",effort:"medium",fix:'Batch queries using arrays and "UNNEST" or a single batched INSERT.',documentationLink:"https://use-the-index-luke.com/sql/joins/nested-loops-join-n1-problem"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))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!=="query"){return}const[queryArg]=node.arguments;if((0,query_call_1.isNonPgQueryObject)(queryArg))return;const text=queryArg===void 0?null:statementText(queryArg);const iteration=iterationContext(node,text!==null&&WRITE_STATEMENT.test(text));if(iteration===null)return;if(text!==null&&BATCHED_STATEMENT.test(text))return;if(isPagination(text,iteration))return;const config=queryArg?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?queryArg:null;const statement=config===null?queryArg:configValue(config,"text");const params=config===null?node.arguments[1]:configValue(config,"values");const varies=target=>target!==void 0&&variesPerIteration(target,iteration.node,context.sourceCode,new Set);if(varies(statement)||!varies(params))return;context.report({node,messageId:"noBatchInsertLoop"})}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFloatingQuery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const query_call_1=require("../../utils/query-call");const TRANSPARENT_POSITIONS=new Set([eslint_devkit_1.AST_NODE_TYPES.ChainExpression,eslint_devkit_1.AST_NODE_TYPES.SequenceExpression,eslint_devkit_1.AST_NODE_TYPES.LogicalExpression,eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression]);function promiseChain(node){let current=node;let rejectionHandled=false;for(;;){const member=current.parent;if(member===void 0||member.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.object!==current||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){break}const call=member.parent;if(call===void 0||call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.callee!==member){break}const method=member.property.name;if(method==="catch"||method==="then"&&call.arguments.length>=2){rejectionHandled=true}current=call}return{root:current,rejectionHandled}}function isRead(variable){return variable!==void 0&&variable.references.some(ref=>ref.isRead())}function lookup(scope,name){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return void 0}exports.noFloatingQuery={meta:{type:"problem",docs:{description:"Ensure all queries are awaited or returned to prevent unhandled promise rejections.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-floating-query.md",cwe:"CWE-391",cvss:5.3},messages:{noFloatingQuery:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Floating Query",description:"Promise-returning query is neither awaited nor returned.",severity:"HIGH",cwe:"CWE-391",effort:"low",fix:'Add "await" or "return" to handle the query promise.',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFloatingQuery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const query_call_1=require("../../utils/query-call");const TRANSPARENT_POSITIONS=new Set([eslint_devkit_1.AST_NODE_TYPES.ChainExpression,eslint_devkit_1.AST_NODE_TYPES.SequenceExpression,eslint_devkit_1.AST_NODE_TYPES.LogicalExpression,eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression]);function promiseChain(node){let current=node;let rejectionHandled=false;for(;;){const member=current.parent;if(member===void 0||member.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.object!==current||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){break}const call=member.parent;if(call===void 0||call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.callee!==member){break}const method=member.property.name;if(method==="catch"||method==="then"&&call.arguments.length>=2){rejectionHandled=true}current=call}return{root:current,rejectionHandled}}function isRead(variable){return variable!==void 0&&variable.references.some(ref=>ref.isRead())}function lookup(scope,name){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return void 0}exports.noFloatingQuery={meta:{type:"problem",docs:{description:"Ensure all queries are awaited or returned to prevent unhandled promise rejections.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-floating-query.md",cwe:"CWE-391",cvss:5.3},messages:{noFloatingQuery:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Floating Query",description:"Promise-returning query is neither awaited nor returned.",severity:"HIGH",cwe:"CWE-391",effort:"low",fix:'Add "await" or "return" to handle the query promise.',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))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!=="query"){return}const last=node.arguments.at(-1);if(last?.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||last?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return}if((0,query_call_1.isNonPgQueryObject)(node.arguments[0]))return;const{root,rejectionHandled}=promiseChain(node);let owner=root.parent;while(TRANSPARENT_POSITIONS.has(owner.type)){owner=owner.parent}if(owner.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){if(owner.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const[variable]=context.sourceCode.getDeclaredVariables(owner);if(isRead(variable))return;context.report({node,messageId:"noFloatingQuery"});return}if(owner.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&owner.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(isRead(lookup(context.sourceCode.getScope(node),owner.left.name)))return;context.report({node,messageId:"noFloatingQuery"});return}if(owner.type!==eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement||rejectionHandled)return;context.report({node,messageId:"noFloatingQuery"})}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const constants_1=require("../../constants");const utils_1=require("../../utils");const connection_config_1=require("../../utils/connection-config");function propertyKeyName(prop){if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed)return prop.key.name;const staticText1=(0,eslint_devkit_1.staticString)(prop.key);if(staticText1!==null){return staticText1}return null}function property(object,name){return object.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&propertyKeyName(prop)===name)}function parseDsnWithPassword(dsn){if(!constants_1.PG_PROTOCOLS.some(protocol=>dsn.startsWith(protocol)))return null;let parsed;try{parsed=new URL(dsn)}catch{return null}return parsed.password===""?null:parsed}const LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);exports.noHardcodedCredentials={meta:{type:"problem",docs:{description:"Detect hardcoded credentials in pg Client or Pool initialization.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-hardcoded-credentials.md",cwe:"CWE-798",cvss:9.8},messages:{noHardcodedCredentials:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"Hardcoded credentials detected in database connection.",severity:"CRITICAL",cwe:"CWE-798",owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:"Use environment variables (process.env.DB_PASSWORD) instead of hardcoding secrets.",documentationLink:"https://owasp.org/www-community/vulnerabilities/Use_of_hard-coded_password"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const constants_1=require("../../constants");const utils_1=require("../../utils");const connection_config_1=require("../../utils/connection-config");const cross_file_1=require("../../utils/cross-file");function propertyKeyName(prop){if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed)return prop.key.name;const staticText1=(0,eslint_devkit_1.staticString)(prop.key);if(staticText1!==null){return staticText1}return null}function property(object,name){return object.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&propertyKeyName(prop)===name)}function parseDsnWithPassword(dsn){if(!constants_1.PG_PROTOCOLS.some(protocol=>dsn.startsWith(protocol)))return null;let parsed;try{parsed=new URL(dsn)}catch{return null}return parsed.password===""?null:parsed}const LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);exports.noHardcodedCredentials={meta:{type:"problem",docs:{description:"Detect hardcoded credentials in pg Client or Pool initialization.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-hardcoded-credentials.md",cwe:"CWE-798",cvss:9.8},messages:{noHardcodedCredentials:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"Hardcoded credentials detected in database connection.",severity:"CRITICAL",cwe:"CWE-798",owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:"Use environment variables (process.env.DB_PASSWORD) instead of hardcoding secrets.",documentationLink:"https://owasp.org/www-community/vulnerabilities/Use_of_hard-coded_password"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};const consumed=new Set;const dsnLiterals=[];const env=(0,cross_file_1.envOf)(context);const stringValue=start=>{const value=(0,cross_file_1.follow)(start);const text=(0,eslint_devkit_1.staticString)(value.node);if(text!==null)consumed.add(value.node);return text};const report=(value,fallback)=>{context.report({node:value.env.module===null?value.node:fallback,messageId:"noHardcodedCredentials"})};const checkConfig=(argument,scope)=>{const start={node:argument,scope,env};const bare=stringValue(start);if(bare!==null){if(parseDsnWithPassword(bare)!==null){context.report({node:argument,messageId:"noHardcodedCredentials"})}return}const config=(0,cross_file_1.follow)(start);if(config.node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const at=node=>({node,scope:config.env.scopeOf(node),env:config.env});const connectionString=property(config.node,"connectionString");if(connectionString!==void 0){const dsn=stringValue(at(connectionString.value));if(dsn!==null&&parseDsnWithPassword(dsn)!==null){report(at(connectionString.value),argument)}}const password=property(config.node,"password");if(password!==void 0){const secret=stringValue(at(password.value));if(secret!==null&&secret!==""){report(at(password.value),argument)}}};const checkCall=node=>{const scope=context.sourceCode.getScope(node);for(const argument of(0,connection_config_1.connectionConfigArguments)(node,scope))checkConfig(argument,scope)};const collectDsn=node=>{const text=(0,eslint_devkit_1.staticString)(node);if(text!==null&&constants_1.PG_PROTOCOLS.some(protocol=>text.startsWith(protocol))){dsnLiterals.push(node)}};return{NewExpression:checkCall,CallExpression:checkCall,Literal:collectDsn,TemplateLiteral:collectDsn,"Program:exit"(){for(const node of dsnLiterals){if(consumed.has(node))continue;const parsed=parseDsnWithPassword((0,eslint_devkit_1.staticString)(node));if(parsed===null||LOOPBACK_HOSTS.has(parsed.hostname))continue;context.report({node,messageId:"noHardcodedCredentials"})}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureSsl=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const connection_config_1=require("../../utils/connection-config");function propertyKeyName(prop){if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed){return prop.key.name}const staticText1=(0,eslint_devkit_1.staticString)(prop.key);if(staticText1!==null){return staticText1}return null}function property(object,name){return object.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&propertyKeyName(prop)===name)}function disablesVerification(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureSsl=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const connection_config_1=require("../../utils/connection-config");const cross_file_1=require("../../utils/cross-file");function propertyKeyName(prop){if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed){return prop.key.name}const staticText1=(0,eslint_devkit_1.staticString)(prop.key);if(staticText1!==null){return staticText1}return null}function property(object,name){return object.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&propertyKeyName(prop)===name)}function disablesVerification(start){const value=(0,cross_file_1.follow)(start).node;if(value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return false;return value.value===false||value.value===0||value.value===""||value.value===null}function dsnSkipsVerification(dsn){const separator=dsn.indexOf("?");if(separator===-1)return false;const sslmode=new URLSearchParams(dsn.slice(separator+1)).get("sslmode");return sslmode!==null&&sslmode.toLowerCase()==="no-verify"}exports.noInsecureSsl={meta:{type:"problem",docs:{description:"Prevent the use of insecure SSL configurations (rejectUnauthorized: false).",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-insecure-ssl.md",cwe:"CWE-319",cvss:7.5},messages:{noInsecureSsl:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure SSL",description:"Insecure SSL configuration detected (rejectUnauthorized: false).",severity:"HIGH",cwe:"CWE-319",owasp:"A05:2021",compliance:["SOC2","PCI-DSS","HIPAA","GDPR"],effort:"low",fix:'Set "rejectUnauthorized: true" or use a valid CA bundle. Do not disable SSL verification in production.',documentationLink:"https://node-postgres.com/features/ssl"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};const env=(0,cross_file_1.envOf)(context);const reported=new Set;const report=node=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId:"noInsecureSsl"})};const sslBranches=start=>{const value=(0,cross_file_1.follow)(start);const at=node=>({node,scope:value.env.scopeOf(node),env:value.env});if(value.node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return[...sslBranches(at(value.node.consequent)),...sslBranches(at(value.node.alternate))]}if(value.node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return[...sslBranches(at(value.node.left)),...sslBranches(at(value.node.right))]}return[value]};const reportAt=(value,fallback)=>{report(value.env.module===null?value.node:fallback)};const checkConfig=(argument,scope)=>{const config=(0,cross_file_1.follow)({node:argument,scope,env});const at=node=>({node,scope:config.env.scopeOf(node),env:config.env});const dsnText=(0,eslint_devkit_1.staticString)(config.node);if(dsnText!==null){if(dsnSkipsVerification(dsnText))report(argument);return}if(config.node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const connectionString=property(config.node,"connectionString");if(connectionString!==void 0){const dsn=(0,cross_file_1.follow)(at(connectionString.value)).node;if(dsn.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof dsn.value==="string"&&dsnSkipsVerification(dsn.value)){reportAt(at(connectionString.value),argument);return}}const ssl=property(config.node,"ssl");if(ssl===void 0)return;for(const branch of sslBranches(at(ssl.value))){if(branch.node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;const rejectUnauthorized=property(branch.node,"rejectUnauthorized");if(rejectUnauthorized!==void 0&&disablesVerification({node:rejectUnauthorized.value,scope:branch.env.scopeOf(rejectUnauthorized.value),env:branch.env})){reportAt({node:rejectUnauthorized,scope:branch.scope,env:branch.env},argument)}}};const checkCall=node=>{const scope=context.sourceCode.getScope(node);for(const argument of(0,connection_config_1.connectionConfigArguments)(node,scope))checkConfig(argument,scope)};return{NewExpression:checkCall,CallExpression:checkCall,VariableDeclarator(node){const scope=context.sourceCode.getScope(node);const config=(0,connection_config_1.typedConnectionConfig)(node,scope);if(config!==null)checkConfig(config,scope)}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingClientRelease=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const pool_receiver_1=require("../../utils/pool-receiver");const PG_MODULE_SET=new Set(utils_1.PG_MODULES);function isPgPoolConstructor(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding===void 0)return false;const parts=binding.module.split("/");const root=binding.module.startsWith("@")?parts.slice(0,2).join("/"):parts[0];if(!PG_MODULE_SET.has(root))return false;const[exported]=binding.path;return exported===void 0||exported==="Pool"}function isPgPool(receiver,scope,poolProperties){if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&receiver.object.type===eslint_devkit_1.AST_NODE_TYPES.ThisExpression&&(0,eslint_devkit_1.propertyName)(receiver)!==null){return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(receiver),poolProperties)}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let current=scope;current;current=current.upper){const variable=current.set.get(receiver.name);if(variable===void 0)continue;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return false;const def=variable.defs.find(d=>d.type==="Variable");const init=def===void 0?null:def.node.init;if(init==null||init.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression)return false;return isPgPoolConstructor(init.callee,scope)}return false}function isReleaseCall(identifier){const member=identifier.parent;if(member?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.object!==identifier||(0,eslint_devkit_1.propertyName)(member)!=="release"){return false}return member.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&member.parent.callee===member}function isInsideFinally(node){for(let current=node.parent;current;current=current.parent){if(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement&¤t.parent.finalizer===current){return true}}return false}function isQueryCall(identifier){const member=identifier.parent;return member?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&member.object===identifier&&(0,eslint_devkit_1.propertyName)(member)==="query"&&member.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&member.parent.callee===member}function
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingClientRelease=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const pool_receiver_1=require("../../utils/pool-receiver");const PG_MODULE_SET=new Set(utils_1.PG_MODULES);function isPgPoolConstructor(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding===void 0)return false;const parts=binding.module.split("/");const root=binding.module.startsWith("@")?parts.slice(0,2).join("/"):parts[0];if(!PG_MODULE_SET.has(root))return false;const[exported]=binding.path;return exported===void 0||exported==="Pool"}function isPgPool(receiver,scope,poolProperties){if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&receiver.object.type===eslint_devkit_1.AST_NODE_TYPES.ThisExpression&&(0,eslint_devkit_1.propertyName)(receiver)!==null){return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(receiver),poolProperties)}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let current=scope;current;current=current.upper){const variable=current.set.get(receiver.name);if(variable===void 0)continue;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return false;const def=variable.defs.find(d=>d.type==="Variable");const init=def===void 0?null:def.node.init;if(init==null||init.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression)return false;return isPgPoolConstructor(init.callee,scope)}return false}function isReleaseCall(identifier){const member=identifier.parent;if(member?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.object!==identifier||(0,eslint_devkit_1.propertyName)(member)!=="release"){return false}return member.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&member.parent.callee===member}function isInsideFinally(node){for(let current=node.parent;current;current=current.parent){if(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement&¤t.parent.finalizer===current){return true}}return false}function isQueryCall(identifier){const member=identifier.parent;return member?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&member.object===identifier&&(0,eslint_devkit_1.propertyName)(member)==="query"&&member.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&member.parent.callee===member}function contains(node,types){if(types.includes(node.type))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return false}return Object.entries(node).some(([key,value])=>{if(key==="parent")return false;const children=Array.isArray(value)?value:[value];return children.some(child=>typeof child==="object"&&child!==null&&typeof child.type==="string"&&contains(child,types))})}const containsReturn=node=>contains(node,[eslint_devkit_1.AST_NODE_TYPES.ReturnStatement]);function enclosingBlock(release){const statement=release.parent?.parent?.parent;const block=statement?.parent;if(statement?.type!==eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement||block?.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return null}return{block,index:block.body.indexOf(statement)}}function tryBlockRelease(release){const slot=enclosingBlock(release);if(slot===null||slot.block.parent?.type!==eslint_devkit_1.AST_NODE_TYPES.TryStatement||slot.block.parent.block!==slot.block){return null}const before=slot.block.body.slice(0,slot.index);return before.some(containsReturn)?null:slot.block.parent}function isInCatchOf(release,tryStatement){for(let current=release.parent;current;current=current.parent){if(current===tryStatement.handler)return true}return false}const JUMPS=[eslint_devkit_1.AST_NODE_TYPES.ReturnStatement,eslint_devkit_1.AST_NODE_TYPES.ThrowStatement,eslint_devkit_1.AST_NODE_TYPES.BreakStatement,eslint_devkit_1.AST_NODE_TYPES.ContinueStatement];function releaseAfterTry(release,releases){const slot=enclosingBlock(release);if(slot===null)return false;const previous=slot.block.body[slot.index-1];if(previous?.type!==eslint_devkit_1.AST_NODE_TYPES.TryStatement||previous.handler===null||contains(previous.block,[eslint_devkit_1.AST_NODE_TYPES.ReturnStatement,eslint_devkit_1.AST_NODE_TYPES.BreakStatement,eslint_devkit_1.AST_NODE_TYPES.ContinueStatement])){return false}const catchBody=previous.handler.body;if(!contains(catchBody,JUMPS))return true;return releases.some(other=>{const inCatch=enclosingBlock(other);return inCatch?.block===catchBody&&!catchBody.body.slice(0,inCatch.index).some(statement=>contains(statement,JUMPS))})}function transfersOwnership(identifier,runsQueries){const parent=identifier.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)return true;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return!runsQueries&&parent.arguments.includes(identifier)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property)return true;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return true;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===identifier){return true}return false}exports.noMissingClientRelease={meta:{type:"problem",docs:{description:"Ensure pg client is released after use to prevent pool exhaustion.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-missing-client-release.md",cwe:"CWE-404"},messages:{missingClientRelease:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"Missing Client Release",description:"PG client acquired but not released.",severity:"HIGH",cwe:"CWE-404",owasp:"A10:2025",effort:"low",fix:'Ensure "client.release()" is called in a finally block to return the client to the pool.',documentationLink:"https://node-postgres.com/features/pooling#checkout-use-and-return"}),releaseNotGuaranteed:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"Client Release Not Guaranteed",description:"PG client is released on some paths but not all. A throw, an early return or a rejected query skips the release and leaks the connection.",severity:"HIGH",cwe:"CWE-404",owasp:"A10:2025",effort:"low",fix:'Move "client.release()" into a finally block so it runs on every path out of the function.',documentationLink:"https://node-postgres.com/features/pooling#checkout-use-and-return"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};const poolProperties=new Set;return{AssignmentExpression(node){if(node.operator!=="="||node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.left.object.type!==eslint_devkit_1.AST_NODE_TYPES.ThisExpression||node.left.computed||node.left.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.right.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return}if(isPgPoolConstructor(node.right.callee,context.sourceCode.getScope(node))){poolProperties.add(node.left.property.name)}},PropertyDefinition(node){if(node.computed||node.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.value==null||node.value.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return}if(isPgPoolConstructor(node.value.callee,context.sourceCode.getScope(node))){poolProperties.add(node.key.name)}},"CallExpression:exit"(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||(0,eslint_devkit_1.propertyName)(node.callee)!=="connect"){return}const checkout=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?node.parent:node;if(checkout.parent?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator)return;const declarator=checkout.parent;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const uses=context.sourceCode.getDeclaredVariables(declarator).flatMap(variable=>variable.references.map(ref=>ref.identifier));const runsQueries=uses.some(id=>isQueryCall(id));const scope=context.sourceCode.getScope(node);if(!isPgPool(node.callee.object,scope,poolProperties)&&!(0,pool_receiver_1.isDeclaredPgPool)(node.callee.object,scope)&&!runsQueries){return}if(uses.some(id=>transfersOwnership(id,runsQueries)))return;const releases=uses.filter(id=>isReleaseCall(id));if(releases.length===0){context.report({node:declarator,messageId:"missingClientRelease"});return}const coveredByTryAndCatch=releases.some(id=>{const tryStatement=tryBlockRelease(id);return tryStatement!==null&&releases.some(other=>isInCatchOf(other,tryStatement))});if(!coveredByTryAndCatch&&!releases.some(id=>releaseAfterTry(id,releases))&&!releases.some(id=>isInsideFinally(id))){context.report({node:declarator,messageId:"releaseNotGuaranteed"})}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSelectAll=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const SELECT_PREFIX=String.raw`SELECT\s+(?:ALL\s+|DISTINCT\s+(?:ON\s*\([^)]*\)\s*)?)?`;const SELECT_STAR=new RegExp(String.raw`\b${SELECT_PREFIX}(?:[A-Za-z_][\w$]*\s*\.\s*)?\*`,"i");const COMMA_STAR=new RegExp(String.raw`,\s*(?:[A-Za-z_][\w$]*\s*\.\s*)?\*`);const SELECT_KEYWORD=/\bSELECT\b/i;const EXISTS_STAR=new RegExp(String.raw`\bEXISTS\s*\(\s*${SELECT_PREFIX}\*`,"gi");const SELECT_STAR_FROM_FUNCTION=new RegExp(String.raw`\b${SELECT_PREFIX}\*\s+FROM\s+[A-Za-z_][\w$]*\s*\(`,"gi");function stripSqlNoise(sql){let out="";let index=0;while(index<sql.length){const rest=sql.slice(index);if(rest.startsWith("--")){const newline=sql.indexOf("\n",index);out+=" ";index=newline===-1?sql.length:newline;continue}if(rest.startsWith("/*")){const end=sql.indexOf("*/",index+2);out+=" ";index=end===-1?sql.length:end+2;continue}const dollarTag=/^\$[A-Za-z_]\w*\$|^\$\$/.exec(rest);if(dollarTag!==null){const tag=dollarTag[0];const end=sql.indexOf(tag,index+tag.length);out+=" ";index=end===-1?sql.length:end+tag.length;continue}const char=sql[index];if(char==="'"||char==='"'){index+=1;while(index<sql.length){if(sql[index]!==char){index+=1;continue}if(sql[index+1]===char){index+=2;continue}index+=1;break}out+=" ";continue}out+=char;index+=1}return out}const SELECT_STAR_FROM_DERIVED=new RegExp(String.raw`\b${SELECT_PREFIX}\*\s+FROM\s*\(`,"gi");const CTE_NAME=/(?:\bWITH(?:\s+RECURSIVE)?|,)\s{0,20}([A-Za-z_][\w$]{0,62})\s{0,20}(?:\([^)]{0,500}\)\s{0,20})?AS\s*(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi;function exemptCteStars(sql){let out=sql;for(const[,name]of sql.matchAll(CTE_NAME)){const escaped=name.replaceAll("$","\\$");out=out.replace(new RegExp(String.raw`\b${SELECT_PREFIX}\*(\s+FROM\s+${escaped}\b)`,"gi"),"SELECT 1$1")}return out}function selectsEveryColumn(sql){const cleaned=exemptCteStars(stripSqlNoise(sql).replace(EXISTS_STAR,"EXISTS ( SELECT 1").replace(SELECT_STAR_FROM_FUNCTION,"SELECT 1 FROM f(").replace(SELECT_STAR_FROM_DERIVED,"SELECT 1 FROM ("));if(SELECT_STAR.test(cleaned))return true;const comma=COMMA_STAR.exec(cleaned);return comma!==null&&SELECT_KEYWORD.test(cleaned.slice(0,comma.index))}function queryText(node,scope){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.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.cooked).join(" 1 ")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!property.computed&&property.key.name==="text"||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value==="text"));return text===void 0?null:queryText(text.value,scope)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return bindingText(node,scope)}return null}function bindingText(node,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(node.name);if(variable===void 0)continue;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;const init=def.node.init;if(init==null||init.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;return queryText(init,scope)}return null}exports.noSelectAll={meta:{type:"problem",docs:{description:"Prevent using * in SELECT statements (implicit columns).",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-select-all.md",cwe:"CWE-1049",cvss:5},messages:{noSelectAll:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"Select All",description:'Avoid using "SELECT *" which fetches all columns.',severity:"MEDIUM",cwe:"CWE-1049",effort:"low",fix:"Explicitly list the columns you need (e.g., SELECT id, name FROM ...).",documentationLink:"https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_SELECT_.2A"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSelectAll=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const SELECT_PREFIX=String.raw`SELECT\s+(?:ALL\s+|DISTINCT\s+(?:ON\s*\([^)]*\)\s*)?)?`;const SELECT_STAR=new RegExp(String.raw`\b${SELECT_PREFIX}(?:[A-Za-z_][\w$]*\s*\.\s*)?\*`,"i");const COMMA_STAR=new RegExp(String.raw`,\s*(?:[A-Za-z_][\w$]*\s*\.\s*)?\*`);const SELECT_KEYWORD=/\bSELECT\b/i;const EXISTS_STAR=new RegExp(String.raw`\bEXISTS\s*\(\s*${SELECT_PREFIX}\*`,"gi");const SELECT_STAR_FROM_FUNCTION=new RegExp(String.raw`\b${SELECT_PREFIX}\*\s+FROM\s+[A-Za-z_][\w$]*\s*\(`,"gi");function stripSqlNoise(sql){let out="";let index=0;while(index<sql.length){const rest=sql.slice(index);if(rest.startsWith("--")){const newline=sql.indexOf("\n",index);out+=" ";index=newline===-1?sql.length:newline;continue}if(rest.startsWith("/*")){const end=sql.indexOf("*/",index+2);out+=" ";index=end===-1?sql.length:end+2;continue}const dollarTag=/^\$[A-Za-z_]\w*\$|^\$\$/.exec(rest);if(dollarTag!==null){const tag=dollarTag[0];const end=sql.indexOf(tag,index+tag.length);out+=" ";index=end===-1?sql.length:end+tag.length;continue}const char=sql[index];if(char==="'"||char==='"'){index+=1;while(index<sql.length){if(sql[index]!==char){index+=1;continue}if(sql[index+1]===char){index+=2;continue}index+=1;break}out+=" ";continue}out+=char;index+=1}return out}const SELECT_STAR_FROM_DERIVED=new RegExp(String.raw`\b${SELECT_PREFIX}\*\s+FROM\s*\(`,"gi");const CTE_NAME=/(?:\bWITH(?:\s+RECURSIVE)?|,)\s{0,20}([A-Za-z_][\w$]{0,62})\s{0,20}(?:\([^)]{0,500}\)\s{0,20})?AS\s*(?:NOT\s+)?(?:MATERIALIZED\s+)?\(/gi;function exemptCteStars(sql){let out=sql;for(const[,name]of sql.matchAll(CTE_NAME)){const escaped=name.replaceAll("$","\\$");out=out.replace(new RegExp(String.raw`\b${SELECT_PREFIX}\*(\s+FROM\s+${escaped}\b)`,"gi"),"SELECT 1$1")}return out}function selectsEveryColumn(sql){const cleaned=exemptCteStars(stripSqlNoise(sql).replace(EXISTS_STAR,"EXISTS ( SELECT 1").replace(SELECT_STAR_FROM_FUNCTION,"SELECT 1 FROM f(").replace(SELECT_STAR_FROM_DERIVED,"SELECT 1 FROM ("));if(SELECT_STAR.test(cleaned))return true;const comma=COMMA_STAR.exec(cleaned);return comma!==null&&SELECT_KEYWORD.test(cleaned.slice(0,comma.index))}function queryText(node,scope){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.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.cooked).join(" 1 ")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!property.computed&&property.key.name==="text"||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value==="text"));return text===void 0?null:queryText(text.value,scope)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return bindingText(node,scope)}return null}function bindingText(node,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(node.name);if(variable===void 0)continue;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;const init=def.node.init;if(init==null||init.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;return queryText(init,scope)}return null}exports.noSelectAll={meta:{type:"problem",docs:{description:"Prevent using * in SELECT statements (implicit columns).",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-select-all.md",cwe:"CWE-1049",cvss:5},messages:{noSelectAll:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"Select All",description:'Avoid using "SELECT *" which fetches all columns.',severity:"MEDIUM",cwe:"CWE-1049",effort:"low",fix:"Explicitly list the columns you need (e.g., SELECT id, name FROM ...).",documentationLink:"https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_SELECT_.2A"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))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!=="query"){return}const[queryArg]=node.arguments;if(queryArg===void 0)return;const text=queryText(queryArg,context.sourceCode.getScope(node));if(text===null||!selectsEveryColumn(text))return;context.report({node:queryArg,messageId:"noSelectAll"})}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTransactionOnPool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const pool_receiver_1=require("../../utils/pool-receiver");const PG_MODULE_SET=new Set(utils_1.PG_MODULES);const TRANSACTION_STATEMENTS=[/^begin\b/i,/^start\s+transaction\b/i,/^commit\b/i,/^end\b/i,/^rollback\b/i,/^savepoint\b/i,/^release\s+savepoint\b/i];function isPgPoolConstructor(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding===void 0)return false;const parts=binding.module.split("/");const root=binding.module.startsWith("@")?parts.slice(0,2).join("/"):parts[0];if(!PG_MODULE_SET.has(root))return false;const[exported]=binding.path;return exported===void 0||exported==="Pool"}function statementText(node){const staticText=(0,eslint_devkit_1.staticString)(node);if(staticText!==null){return staticText.trim()}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed&&prop.key.name==="text"||prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.key.value==="text"));return text===void 0?null:statementText(text.value)}return null}function isTransactionStatement(text){return TRANSACTION_STATEMENTS.some(pattern=>pattern.test(text))}function isSelfContainedTransaction(text){const statements=text.split(";").map(statement=>statement.trim()).filter(statement=>statement!=="");return statements.length>1&&/^(?:begin|start\s+transaction)\b/i.test(statements[0])&&/^(?:commit|end|rollback)\b/i.test(statements[statements.length-1])}function handsOutClients(receiver,scope){if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let current=scope;current;current=current.upper){const variable=current.set.get(receiver.name);if(variable===void 0)continue;return variable.references.some(ref=>{const member=ref.identifier.parent;const call=member?.parent;const kept=call?.parent?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?call.parent.parent:void 0;return member?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(member)==="connect"&&call?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&kept?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator})}return false}exports.noTransactionOnPool={meta:{type:"problem",docs:{description:"Prevent starting transactions directly on the Pool, which is unsafe due to lack of client affinity.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-transaction-on-pool.md",cwe:"CWE-662",cweJustification:"CWE-662 (Improper Synchronization) \u2014 running BEGIN/COMMIT on a connection pool can split a logical transaction across different physical clients, breaking ACID atomicity.",confidence:"high"},messages:{noTransactionOnPool:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Transaction on Pool",description:"Transactions should not be started on the Pool directly.",severity:"HIGH",effort:"low",fix:'Use "await pool.connect()" to get a client, then start the transaction on the client.',documentationLink:"https://node-postgres.com/features/transactions"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTransactionOnPool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const pool_receiver_1=require("../../utils/pool-receiver");const cross_file_1=require("../../utils/cross-file");const PG_MODULE_SET=new Set(utils_1.PG_MODULES);const TRANSACTION_STATEMENTS=[/^begin\b/i,/^start\s+transaction\b/i,/^commit\b/i,/^end\b/i,/^rollback\b/i,/^savepoint\b/i,/^release\s+savepoint\b/i];function isPgPoolConstructor(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding===void 0)return false;const parts=binding.module.split("/");const root=binding.module.startsWith("@")?parts.slice(0,2).join("/"):parts[0];if(!PG_MODULE_SET.has(root))return false;const[exported]=binding.path;return exported===void 0||exported==="Pool"}function resolvesToPool(receiver,scope,env){const value=(0,cross_file_1.follow)({node:receiver,scope,env});if(value.node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return isPgPoolConstructor(value.node.callee,value.scope)}const declarator=value.node.parent;return declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,pool_receiver_1.isPgPoolType)(declarator.id.typeAnnotation,value.scope)}function statementText(node){const staticText=(0,eslint_devkit_1.staticString)(node);if(staticText!==null){return staticText.trim()}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed&&prop.key.name==="text"||prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.key.value==="text"));return text===void 0?null:statementText(text.value)}return null}function isTransactionStatement(text){return TRANSACTION_STATEMENTS.some(pattern=>pattern.test(text))}function isSelfContainedTransaction(text){const statements=text.split(";").map(statement=>statement.trim()).filter(statement=>statement!=="");return statements.length>1&&/^(?:begin|start\s+transaction)\b/i.test(statements[0])&&/^(?:commit|end|rollback)\b/i.test(statements[statements.length-1])}function handsOutClients(receiver,scope){if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let current=scope;current;current=current.upper){const variable=current.set.get(receiver.name);if(variable===void 0)continue;return variable.references.some(ref=>{const member=ref.identifier.parent;const call=member?.parent;const kept=call?.parent?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?call.parent.parent:void 0;return member?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(member)==="connect"&&call?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&kept?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator})}return false}exports.noTransactionOnPool={meta:{type:"problem",docs:{description:"Prevent starting transactions directly on the Pool, which is unsafe due to lack of client affinity.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-transaction-on-pool.md",cwe:"CWE-662",cweJustification:"CWE-662 (Improper Synchronization) \u2014 running BEGIN/COMMIT on a connection pool can split a logical transaction across different physical clients, breaking ACID atomicity.",confidence:"high"},messages:{noTransactionOnPool:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Transaction on Pool",description:"Transactions should not be started on the Pool directly.",severity:"HIGH",effort:"low",fix:'Use "await pool.connect()" to get a client, then start the transaction on the client.',documentationLink:"https://node-postgres.com/features/transactions"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};const poolProperties=new Set;const isPool=(receiver,scope)=>{if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&receiver.object.type===eslint_devkit_1.AST_NODE_TYPES.ThisExpression&&(0,eslint_devkit_1.propertyName)(receiver)!==null){return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(receiver),poolProperties)}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let current=scope;current;current=current.upper){const variable=current.set.get(receiver.name);if(variable===void 0)continue;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return false;const def=variable.defs.find(d=>d.type==="Variable");const init=def===void 0?null:def.node.init;if(init==null||init.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression)return false;return isPgPoolConstructor(init.callee,scope)}return false};return{AssignmentExpression(node){const field=(0,eslint_devkit_1.memberPropertyName)(node.left);if(node.operator!=="="||node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.left.object.type!==eslint_devkit_1.AST_NODE_TYPES.ThisExpression||field===null||node.right.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return}if(isPgPoolConstructor(node.right.callee,context.sourceCode.getScope(node))){poolProperties.add(field)}},PropertyDefinition(node){if(node.computed||node.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.value==null||node.value.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return}if(isPgPoolConstructor(node.value.callee,context.sourceCode.getScope(node))){poolProperties.add(node.key.name)}},"CallExpression:exit"(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||(0,eslint_devkit_1.propertyName)(node.callee)!=="query"){return}const[queryArg]=node.arguments;if(queryArg===void 0)return;const text=statementText(queryArg);if(text===null||!isTransactionStatement(text))return;if(isSelfContainedTransaction(text))return;const scope=context.sourceCode.getScope(node);const receiver=node.callee.object;if(isPool(receiver,scope)||(0,pool_receiver_1.isDeclaredPgPool)(receiver,scope)||handsOutClients(receiver,scope)||resolvesToPool(receiver,scope,(0,cross_file_1.envOf)(context))){context.report({node:queryArg,messageId:"noTransactionOnPool"})}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeCopyFrom=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const sql_scan_1=require("../../utils/sql-scan");const SQL_SINK_METHODS=new Set(["query","execute"]);const QUOTED_SOURCE=/from\s+['"]([^'"]+)['"]/i;const FROM_STDIN=/^\s*stdin\b/i;const TO_STDOUT=/^\s*stdout\b/i;const MAX_RESOLUTION_DEPTH=4;function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}return(0,eslint_devkit_1.staticString)(node)??""}function copyClauses(text){const found=[];const stripped=(0,sql_scan_1.stripComments)(text);for(const statement of stripped.split(";")){const head=/^\s*copy\b/i.exec(statement);if(head===null)continue;let index=head[0].length;while(index<statement.length&&/\s/.test(statement[index]))index+=1;if(statement[index]==="("){let depth=0;for(;index<statement.length;index+=1){if(statement[index]==="(")depth+=1;else if(statement[index]===")"){depth-=1;if(depth===0){index+=1;break}}}}const direction=/\b(from|to)\b/i.exec(statement.slice(index));if(direction===null)continue;found.push({direction:direction[1].toLowerCase(),clause:statement.slice(index+direction.index+direction[1].length)})}return found}function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const[only]=body.body;if(body.body.length!==1||only.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument===null?null:returnedExpression(only.argument)}return body.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||body.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||(0,eslint_devkit_1.staticString)(body)!==null?body:null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(tag)==="raw"}function singleAssignedInit(variable){if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function effectiveExpression(node,scope,depth=0){if(depth>=MAX_RESOLUTION_DEPTH)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return isStringRawTag(node)?node.quasi:node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=variable===null?null:singleAssignedInit(variable);return init===null?node:effectiveExpression(init,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:effectiveExpression(returned,scope,depth+1)}return node}function hasDynamicPart(node,scope){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some(part=>hasDynamicPart(part,scope))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return hasDynamicPart(node.left,scope)||hasDynamicPart(node.right,scope)}return!(0,eslint_devkit_1.isStaticExpression)({node,scope})}exports.noUnsafeCopyFrom={meta:{type:"problem",docs:{description:"Prevent unsafe COPY FROM usage with dynamic file paths, which can lead to arbitrary file read/RCE.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-copy-from.md",cwe:"CWE-73",cvss:9.5},messages:{dynamicPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"COPY FROM Injection",description:"Dynamic file path in COPY FROM detected - potential arbitrary file read.",severity:"CRITICAL",cwe:"CWE-73",owasp:"A03:2021",compliance:["SOC2","PCI-DSS"],effort:"low",fix:"Never use user input in COPY FROM paths. Use COPY FROM STDIN for user data.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"}),dynamicWritePath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"COPY TO Injection",description:"Dynamic file path in COPY TO detected - potential arbitrary file write on the database server.",severity:"CRITICAL",cwe:"CWE-73",owasp:"A03:2021",compliance:["SOC2","PCI-DSS"],effort:"low",fix:"Never use user input in COPY TO paths. Use COPY TO STDOUT and write the file from the application.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"}),hardcodedPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Server-side COPY FROM",description:"Hardcoded file path in COPY FROM - server-side file access.",severity:"MEDIUM",cwe:"CWE-73",effort:"low",fix:"Prefer COPY FROM STDIN for application code. Use allowHardcodedPaths option if this is an admin script.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"}),unverifiablePath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Unverifiable COPY FROM",description:"Cannot statically verify COPY FROM source - potential injection risk.",severity:"MEDIUM",cwe:"CWE-73",effort:"medium",fix:"Ensure the query source does not contain user input, or refactor to use COPY FROM STDIN.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"})},schema:[{type:"object",properties:{allowHardcodedPaths:{type:"boolean",description:"Allow hardcoded file paths (for admin/migration scripts)"},allowedPaths:{type:"array",items:{type:"string"},description:"List of allowed file path patterns (regex strings)"}},additionalProperties:false}]},defaultOptions:[{}],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeCopyFrom=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const sql_scan_1=require("../../utils/sql-scan");const SQL_SINK_METHODS=new Set(["query","execute"]);const QUOTED_SOURCE=/from\s+['"]([^'"]+)['"]/i;const FROM_STDIN=/^\s*stdin\b/i;const TO_STDOUT=/^\s*stdout\b/i;const MAX_RESOLUTION_DEPTH=4;function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}return(0,eslint_devkit_1.staticString)(node)??""}function copyClauses(text){const found=[];const stripped=(0,sql_scan_1.stripComments)(text);for(const statement of stripped.split(";")){const head=/^\s*copy\b/i.exec(statement);if(head===null)continue;let index=head[0].length;while(index<statement.length&&/\s/.test(statement[index]))index+=1;if(statement[index]==="("){let depth=0;for(;index<statement.length;index+=1){if(statement[index]==="(")depth+=1;else if(statement[index]===")"){depth-=1;if(depth===0){index+=1;break}}}}const direction=/\b(from|to)\b/i.exec(statement.slice(index));if(direction===null)continue;found.push({direction:direction[1].toLowerCase(),clause:statement.slice(index+direction.index+direction[1].length)})}return found}function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const[only]=body.body;if(body.body.length!==1||only.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument===null?null:returnedExpression(only.argument)}return body.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||body.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||(0,eslint_devkit_1.staticString)(body)!==null?body:null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(tag)==="raw"}function singleAssignedInit(variable){if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function effectiveExpression(node,scope,depth=0){if(depth>=MAX_RESOLUTION_DEPTH)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return isStringRawTag(node)?node.quasi:node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=variable===null?null:singleAssignedInit(variable);return init===null?node:effectiveExpression(init,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:effectiveExpression(returned,scope,depth+1)}return node}function hasDynamicPart(node,scope){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some(part=>hasDynamicPart(part,scope))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return hasDynamicPart(node.left,scope)||hasDynamicPart(node.right,scope)}return!(0,eslint_devkit_1.isStaticExpression)({node,scope})}exports.noUnsafeCopyFrom={meta:{type:"problem",docs:{description:"Prevent unsafe COPY FROM usage with dynamic file paths, which can lead to arbitrary file read/RCE.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-copy-from.md",cwe:"CWE-73",cvss:9.5},messages:{dynamicPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"COPY FROM Injection",description:"Dynamic file path in COPY FROM detected - potential arbitrary file read.",severity:"CRITICAL",cwe:"CWE-73",owasp:"A03:2021",compliance:["SOC2","PCI-DSS"],effort:"low",fix:"Never use user input in COPY FROM paths. Use COPY FROM STDIN for user data.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"}),dynamicWritePath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"COPY TO Injection",description:"Dynamic file path in COPY TO detected - potential arbitrary file write on the database server.",severity:"CRITICAL",cwe:"CWE-73",owasp:"A03:2021",compliance:["SOC2","PCI-DSS"],effort:"low",fix:"Never use user input in COPY TO paths. Use COPY TO STDOUT and write the file from the application.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"}),hardcodedPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Server-side COPY FROM",description:"Hardcoded file path in COPY FROM - server-side file access.",severity:"MEDIUM",cwe:"CWE-73",effort:"low",fix:"Prefer COPY FROM STDIN for application code. Use allowHardcodedPaths option if this is an admin script.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"}),unverifiablePath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Unverifiable COPY FROM",description:"Cannot statically verify COPY FROM source - potential injection risk.",severity:"MEDIUM",cwe:"CWE-73",effort:"medium",fix:"Ensure the query source does not contain user input, or refactor to use COPY FROM STDIN.",documentationLink:"https://www.postgresql.org/docs/current/sql-copy.html"})},schema:[{type:"object",properties:{allowHardcodedPaths:{type:"boolean",description:"Allow hardcoded file paths (for admin/migration scripts)"},allowedPaths:{type:"array",items:{type:"string"},description:"List of allowed file path patterns (regex strings)"}},additionalProperties:false}]},defaultOptions:[{}],create(context){if(!(0,utils_1.usesPostgres)(context))return{};const options=context.options[0]??{};const allowHardcodedPaths=options.allowHardcodedPaths??false;const allowedPaths=(options.allowedPaths??[]).map(p=>new RegExp(p));const isPathAllowed=filePath=>allowedPaths.some(pattern=>pattern.test(filePath));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||!SQL_SINK_METHODS.has(node.callee.property.name)){return}const[queryArg]=node.arguments;if(queryArg===void 0||queryArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const scope=context.sourceCode.getScope(node);const expression=effectiveExpression(queryArg,scope);const copies=copyClauses(staticText(expression));if(copies.some(copy=>copy.direction==="to"&&!TO_STDOUT.test(copy.clause))&&hasDynamicPart(expression,scope)){context.report({node:queryArg,messageId:"dynamicWritePath"});return}const source=copies.find(copy=>copy.direction==="from")?.clause;if(source===void 0)return;if(FROM_STDIN.test(source))return;if(hasDynamicPart(expression,scope)){context.report({node:queryArg,messageId:"dynamicPath"});return}const filePath=QUOTED_SOURCE.exec(`from ${source}`);if(filePath!==null&&isPathAllowed(filePath[1]))return;if(allowHardcodedPaths)return;context.report({node:queryArg,messageId:"hardcodedPath"})}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeQuery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const SQL_SINK_METHODS=new Set(["query","execute","none","one","oneOrNone","many","manyOrNone","any","result","multi","multiResult","unsafe"]);const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i,/^\s*with\b[\s\S]*\bas\s*\(/i,/^\s*copy\b[\s\S]*\b(?:from|to)\b/i,/^\s*grant\b[\s\S]*\bon\b/i,/^\s*(create|drop|alter|truncate)\s+(table|index|view|schema|database|sequence|materialized|type|function|trigger|role|user|extension)\b/i,/^\s*select\s/i,/^\s*call\s+[\w".]+\s*\(/i,/^\s*(?:un)?listen\s+[\w"*]*\s*(?:;|$)/i,/^\s*notify\s+[\w"]*\s*(?:,|;|$)/i];const PG_ESCAPER_METHODS=new Set(["escapeIdentifier","escapeLiteral"]);const NUMBER_CONVERSIONS=new Set(["Number","parseInt","parseFloat"]);const NUMBER_NAMESPACES=new Set(["Math","Number"]);const MAPPING_METHODS=new Set(["map","flatMap","from"]);function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}return(0,eslint_devkit_1.staticString)(node)??""}function trailingText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.at(-1).value.raw}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return trailingText(node.right)}return(0,eslint_devkit_1.staticString)(node)??""}function looksLikeSqlStatement(text){return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function isGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function singleInit(variable){if(variable===null)return null;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function endsWithPlaceholderPrefix(text){return text.endsWith("$")&&!text.endsWith("$$")}function isIndexShaped(node){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.Identifier:case eslint_devkit_1.AST_NODE_TYPES.UpdateExpression:return true;case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return(0,eslint_devkit_1.propertyName)(node)==="length";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="push";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return(node.operator==="+"||node.operator==="-"||node.operator==="*")&&isIndexShaped(node.left)&&isIndexShaped(node.right);default:return false}}function isPlaceholderIndex(textBefore,expression){return endsWithPlaceholderPrefix(textBefore)&&isIndexShaped(expression)}function isPlaceholderOnly(node){if((0,eslint_devkit_1.staticString)(node)!==null)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.every((expression,i)=>isPlaceholderIndex(node.quasis[i].value.raw,expression))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=node.left;return isPlaceholderOnly(left)&&(isPlaceholderOnly(node.right)||isPlaceholderIndex(trailingText(left),node.right))}return false}function callbackResult(fn){if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}if(fn.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return fn.body;const last=fn.body.body.at(-1);return last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement?last.argument:null}function isPlaceholderList(node,scope){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=singleInit(resolveVariable(node.name,scope));return init!==null&&init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isPlaceholderList(init,scope)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null||!MAPPING_METHODS.has(method))return false;const mapper=node.arguments.at(-1);const result=mapper===void 0?null:callbackResult(mapper);return result!==null&&isPlaceholderOnly(result)}function isSafeCall(call,scope){const{callee}=call;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(NUMBER_CONVERSIONS.has(callee.name)&&isGlobal(callee.name,scope))return true}else if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(callee);if(method!==null&&PG_ESCAPER_METHODS.has(method))return true;if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&NUMBER_NAMESPACES.has(callee.object.name)&&isGlobal(callee.object.name,scope)){return true}if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee.object)==="as"){return true}if(method==="join"&&isPlaceholderList(callee.object,scope))return true}const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){if(binding.module==="pg-format")return true;const exported=binding.path.at(-1);if(exported!==void 0&&PG_ESCAPER_METHODS.has(exported))return true}return(0,eslint_devkit_1.isStaticExpression)({node:call,scope})}function isConstantMember(node,scope){const key=(0,eslint_devkit_1.propertyName)(node);if(key===null||node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=resolveVariable(node.object.name,scope);if(variable===null)return false;const enumDef=variable.defs.find(d=>d.type==="TSEnumName");if(enumDef!==void 0){const declaration=enumDef.node;const member=declaration.body.members.find(m=>m.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&m.id.name===key);return member!==void 0&&(member.initializer===void 0||member.initializer.type===eslint_devkit_1.AST_NODE_TYPES.Literal)}const init=(0,eslint_devkit_1.unwrapTypeSyntax)(singleInit(variable));if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;const property=init.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(p)===key);return property!==void 0&&(0,eslint_devkit_1.isStaticExpression)({node:property.value,scope})}function isRawValue(value,scope,self){const part=(0,eslint_devkit_1.unwrapTypeSyntax)(value);if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawPart(part,scope,self)}if((0,eslint_devkit_1.isStaticExpression)({node:part,scope}))return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return!isSafeCall(part,scope);if(part.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return!isConstantMember(part,scope);if(part.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(part.name,scope);if(variable!==null&&variable===self)return false;const init=(0,eslint_devkit_1.unwrapTypeSyntax)(singleInit(variable));return init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||!isSafeCall(init,scope)}return true}function hasRawPart(node,scope,self){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some((expression,i)=>!isPlaceholderIndex(node.quasis[i].value.raw,expression)&&isRawValue(expression,scope,self))}const left=node.left;if(isPlaceholderIndex(trailingText(left),node.right)){return isRawValue(left,scope,self)}return isRawValue(left,scope,self)||isRawValue(node.right,scope,self)}function effectiveExpression(node,scope){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed&&prop.key.name==="text"||prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.key.value==="text"));return text===void 0?node:effectiveExpression(text.value,scope)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){const[first]=node.arguments;return first===void 0?node:effectiveExpression(first,scope)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=singleInit(resolveVariable(node.name,scope));return init!==null&&init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?effectiveExpression(init,scope):node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:returned}return node}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const last=body.body.at(-1);if(last?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||last.argument===null)return null;if(last.argument.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return last.argument;return body.body.length===1?returnedExpression(last.argument):null}return body.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||body.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||body.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?body:null}function leftmostOperand(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&¤t.operator==="+"){current=current.left}return current}exports.noUnsafeQuery={meta:{type:"problem",docs:{description:"Prevent SQL injection by disallowing string concatenation or unsafe template literals in queries.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-query.md",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{noUnsafeQuery:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:"CWE-89",owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Use parameterized queries ($1, $2) instead of string concatenation.",documentationLink:"https://node-postgres.com/features/queries#parameterized-queries"}),unsafeTemplateLiteral:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",fix:"Use parameterized queries ($1, $2) instead of interpolating values.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[]},defaultOptions:[],create(context){const{sourceCode}=context;if(!(0,utils_1.fileUsesPostgres)(sourceCode.ast))return{};const fragments=new Map;const keyFor=id=>resolveVariable(id.name,sourceCode.getScope(id))??`global:${id.name}`;const isBuilt=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0||node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+";const isStringish=node=>isBuilt(node)||node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||(0,eslint_devkit_1.staticString)(node)!==null;const reportIfUnsafe=(reportNode,parts,self)=>{const selfVariable=typeof self==="string"?null:self;let kind=null;let raw=false;let text="";for(const part of parts){text+=staticText(part);const scope=sourceCode.getScope(part);if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&part.operator==="+"){kind="concat";if(hasRawPart(part,scope,selfVariable))raw=true}else if(part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&part.expressions.length>0){kind="template";if(hasRawPart(part,scope,selfVariable))raw=true}}if(kind===null||!raw)return;if(!looksLikeSqlStatement(text))return;context.report({node:reportNode,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.init&&isStringish(node.init)){fragments.set(keyFor(node.id),[node.init])}},AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const key=keyFor(node.left);if(node.operator==="+="){const existing2=fragments.get(key);if(existing2===void 0)fragments.set(key,[node.right]);else existing2.push(node.right);return}if(node.operator!=="=")return;if(!isStringish(node.right)){fragments.delete(key);return}const head=leftmostOperand(node.right);const existing=fragments.get(key);if(existing!==void 0&&head.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&keyFor(head)===key){existing.push(node.right)}else{fragments.set(key,[node.right])}},CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!SQL_SINK_METHODS.has(node.callee.property.name)){return}const[queryArg]=node.arguments;if(queryArg===void 0||queryArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const scope=sourceCode.getScope(node);const expression=effectiveExpression(queryArg,scope);if(isBuilt(expression)){reportIfUnsafe(queryArg,[expression],null);return}if(expression.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const key=keyFor(expression);const parts=fragments.get(key);if(parts!==void 0)reportIfUnsafe(queryArg,parts,key)}}}}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeQuery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const cross_file_1=require("../../utils/cross-file");const SQL_SINK_METHODS=new Set(["query","execute","none","one","oneOrNone","many","manyOrNone","any","result","multi","multiResult","unsafe"]);const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i,/^\s*with\b[\s\S]*\bas\s*\(/i,/^\s*copy\b[\s\S]*\b(?:from|to)\b/i,/^\s*grant\b[\s\S]*\bon\b/i,/^\s*(create|drop|alter|truncate)\s+(table|index|view|schema|database|sequence|materialized|type|function|trigger|role|user|extension)\b/i,/^\s*select\s/i,/^\s*call\s+[\w".]+\s*\(/i,/^\s*(?:un)?listen\s+[\w"*]*\s*(?:;|$)/i,/^\s*notify\s+[\w"]*\s*(?:,|;|$)/i];const PG_ESCAPER_METHODS=new Set(["escapeIdentifier","escapeLiteral"]);const NUMBER_CONVERSIONS=new Set(["Number","parseInt","parseFloat"]);const NUMBER_NAMESPACES=new Set(["Math","Number"]);const PURE_TEXT_METHODS=new Set(["trim","trimStart","trimEnd","toLowerCase","toUpperCase","join","slice","substring","padStart","padEnd","toString","toFixed","concat"]);const MUTATING_METHODS=new Set(["push","unshift","splice","fill","copyWithin","set","add","assign"]);const MAX_VALUE_HOPS=8;const MAPPING_METHODS=new Set(["map","flatMap","from"]);function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}return(0,eslint_devkit_1.staticString)(node)??""}function trailingText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.at(-1).value.raw}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return trailingText(node.right)}return(0,eslint_devkit_1.staticString)(node)??""}function looksLikeSqlStatement(text){return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function isGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function singleInit(variable){if(variable===null)return null;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function endsWithPlaceholderPrefix(text){return text.endsWith("$")&&!text.endsWith("$$")}function isIndexShaped(node,scope){return isNumeric((0,eslint_devkit_1.unwrapTypeSyntax)(node),scope,new Set)}const INDEX_PARAMETER=new Map([["map",1],["flatMap",1],["forEach",1],["filter",1],["some",1],["every",1],["find",1],["findIndex",1],["findLast",1],["findLastIndex",1],["from",1],["reduce",2],["reduceRight",2]]);function isNumericParameter(name){if(name.typeAnnotation?.typeAnnotation.type===eslint_devkit_1.AST_NODE_TYPES.TSNumberKeyword)return true;const fn=name.parent;const call=fn?.parent;if(fn?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn?.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,eslint_devkit_1.propertyName)(call.callee);const index=method===null?void 0:INDEX_PARAMETER.get(method);return index!==void 0&&fn.params[index]===name}function enclosingParameter(node){for(let current=node.parent;current;current=current.parent){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){const param=current.params.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.name===node.name);if(param!==void 0)return param}}return null}const NUMERIC_OPERATORS=new Set(["-","*","%","**","|","&","^","<<",">>",">>>"]);function isNumeric(node,scope,seen){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.UpdateExpression:return true;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return node.operator==="+"||node.operator==="-"||node.operator==="~";case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return(0,eslint_devkit_1.propertyName)(node)==="length";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="push"||isNumberConversion(node,scope);case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:if(node.operator==="+"){return isNumeric(node.left,scope,seen)&&isNumeric(node.right,scope,seen)}return NUMERIC_OPERATORS.has(node.operator);case eslint_devkit_1.AST_NODE_TYPES.Identifier:return isNumericBinding(node,scope,seen);default:return false}}function isNumberConversion(call,scope){const{callee}=call;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return NUMBER_CONVERSIONS.has(callee.name)&&isGlobal(callee.name,scope)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&NUMBER_NAMESPACES.has(callee.object.name)&&isGlobal(callee.object.name,scope)}function isNumericBinding(node,scope,seen){const param=enclosingParameter(node);if(param!==null)return isNumericParameter(param);const variable=resolveVariable(node.name,scope);if(variable===null||variable.defs.length===0)return false;if(seen.has(variable))return true;seen.add(variable);const[def]=variable.defs;if(def.type==="Parameter")return isNumericParameter(def.name);if(def.type!=="Variable")return false;const declarator=def.node;if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&declarator.id.typeAnnotation?.typeAnnotation.type===eslint_devkit_1.AST_NODE_TYPES.TSNumberKeyword){return true}const loop=declarator.parent.parent;if(loop?.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||loop?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement){return false}const writes=variable.references.filter(reference=>reference.isWrite());return writes.length>0&&writes.every(write=>{const parent=write.identifier.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression)return true;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.operator!=="="){return parent.operator!=="+="||isNumeric(parent.right,write.from,seen)}return write.writeExpr!=null&&isNumeric((0,eslint_devkit_1.unwrapTypeSyntax)(write.writeExpr),write.from,seen)})}function isPlaceholderIndex(textBefore,expression,scope){return endsWithPlaceholderPrefix(textBefore)&&isIndexShaped(expression,scope)}function isPlaceholderOnly(node,scope){if((0,eslint_devkit_1.staticString)(node)!==null)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.every((expression,i)=>isPlaceholderIndex(node.quasis[i].value.raw,expression,scope))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=node.left;return isPlaceholderOnly(left,scope)&&(isPlaceholderOnly(node.right,scope)||isPlaceholderIndex(trailingText(left),node.right,scope))}return false}function callbackResult(fn){if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}if(fn.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return fn.body;const last=fn.body.body.at(-1);return last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement?last.argument:null}function isPlaceholderList(node,scope){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=(0,eslint_devkit_1.unwrapTypeSyntax)(singleInit(variable));if(init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return isPlaceholderList(init,scope);return variable!==null&&init?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&isFixedTextList(variable,init)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null||!MAPPING_METHODS.has(method))return false;const mapper=node.arguments.at(-1);const result=mapper===void 0?null:callbackResult(mapper);return result!==null&&isPlaceholderOnly(result,scope)}function isFixedText(node,scope){if((0,eslint_devkit_1.staticString)(node)!==null)return true;return(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&!hasRawPart(node,scope,null)}function isFixedTextList(variable,init){if(!init.elements.every(element=>element!==null&&element.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&isFixedText(element,variable.scope))){return false}return variable.references.every(reference=>{if(reference.isWrite())return true;const member=reference.identifier.parent;if(member?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.object!==reference.identifier){return false}const method=(0,eslint_devkit_1.propertyName)(member);if(method==="join"||method==="length")return true;const call=member.parent;return method==="push"&&call?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.arguments.every(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&isFixedText(argument,reference.from))})}function isFixedLoopElement(variable,scope){const def=variable.defs[0];if(def?.type!=="Variable")return false;const declaration=def.node.parent;const loop=declaration.parent;if(loop?.type!==eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.left!==declaration)return false;const right=(0,eslint_devkit_1.unwrapTypeSyntax)(loop.right);const list=right.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?(0,eslint_devkit_1.unwrapTypeSyntax)(singleInit(resolveVariable(right.name,scope))):right;return list?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&list.elements.every(element=>element!==null&&element.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&(0,eslint_devkit_1.isStaticExpression)({node:element,scope}))}function isSafeCall(call,scope,depth=0){const{callee}=call;const argsSafe=()=>call.arguments.every(a=>!isRawValue(a,scope,null,depth+1));if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(NUMBER_CONVERSIONS.has(callee.name)&&isGlobal(callee.name,scope))return true;if(callee.name==="String"&&isGlobal("String",scope)&&argsSafe())return true;if(call.arguments.length===0&&helperReturnsSafe(callee,scope,depth))return true}else if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(callee);if(method!==null&&PURE_TEXT_METHODS.has(method)&&!isRawValue(callee.object,scope,null,depth+1)&&argsSafe()){return true}if(method!==null&&PG_ESCAPER_METHODS.has(method))return true;if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&NUMBER_NAMESPACES.has(callee.object.name)&&isGlobal(callee.object.name,scope)){return true}if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee.object)==="as"){return true}if(method==="join"&&isPlaceholderList(callee.object,scope))return true}const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){if(binding.module==="pg-format")return true;const exported=binding.path.at(-1);if(exported!==void 0&&PG_ESCAPER_METHODS.has(exported))return true}return(0,eslint_devkit_1.isStaticExpression)({node:call,scope})}function returnExpressions(fn){const body=fn.body;if(body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return[body];const found=[];const visit=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){if(node.argument!==null)found.push(node.argument);return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return}for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(Array.isArray(child)){for(const c of child)if(c&&typeof c.type==="string")visit(c)}else if(child&&typeof child.type==="string"){visit(child)}}};visit(body);return found}function helperReturnsSafe(callee,scope,depth){if(depth>=MAX_VALUE_HOPS)return false;const variable=resolveVariable(callee.name,scope);if(variable===null)return false;const fn=functionImplementation(variable);if(fn===null||fn.async||fn.generator)return false;const returns=returnExpressions(fn);if(returns.length===0)return false;const inner=variable.scope.childScopes.flatMap(child=>[child,...child.childScopes]).find(child=>child.block===fn&&child.type==="function");return returns.every(r=>!isRawValue(r,inner,null,depth+1))}function writtenValues(variable){if(variable.defs.length!==1||variable.defs[0].type!=="Variable")return null;const declarator=variable.defs[0].node;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const values=[];for(const ref of variable.references){if(!ref.isWrite())continue;const parent=ref.identifier.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression)continue;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.operator!=="="&&parent.operator!=="+="){continue}values.push(ref.writeExpr)}const container=values.some(v=>{const u=(0,eslint_devkit_1.unwrapTypeSyntax)(v);return u.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||u.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression});if(container&&variable.references.some(ref=>!ref.isWrite()&&ref.identifier.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&changesOrEscapes(ref.identifier))){return null}return values}function changesOrEscapes(id){const parent=id.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===id){const outer=parent.parent;if(outer?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&outer.left===parent)return true;if(outer?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&outer.callee===parent){const method=(0,eslint_devkit_1.propertyName)(parent);return method===null||MUTATING_METHODS.has(method)}return false}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return parent.arguments.includes(id)}return parent.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement||parent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement}function isConstantMember(node,scope){const key=(0,eslint_devkit_1.propertyName)(node);if(key===null||node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=resolveVariable(node.object.name,scope);if(variable===null)return false;const enumDef=variable.defs.find(d=>d.type==="TSEnumName");if(enumDef!==void 0){const declaration=enumDef.node;const member=declaration.body.members.find(m=>m.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&m.id.name===key);return member!==void 0&&(member.initializer===void 0||member.initializer.type===eslint_devkit_1.AST_NODE_TYPES.Literal)}const init=(0,eslint_devkit_1.unwrapTypeSyntax)(singleInit(variable));if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;if(variable.references.some(ref=>!ref.isWrite()&&ref.identifier.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&changesOrEscapes(ref.identifier))){return false}const property=init.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(p)===key);return property!==void 0&&(0,eslint_devkit_1.isStaticExpression)({node:property.value,scope})}function isRawValue(value,scope,self,depth=0){const part=(0,eslint_devkit_1.unwrapTypeSyntax)(value);if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawPart(part,scope,self,depth)}if((0,eslint_devkit_1.isStaticExpression)({node:part,scope}))return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return!isSafeCall(part,scope,depth);if(part.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return part.elements.some(e=>e===null||e.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement||isRawValue(e,scope,null,depth+1))}if(part.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_1.propertyName)(part)==="length"&&!isRawValue(part.object,scope,null,depth+1)){return false}return!isConstantMember(part,scope)}if(part.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(part.name,scope);if(variable!==null&&variable===self)return false;if(variable!==null&&isFixedLoopElement(variable,scope))return false;const init=(0,eslint_devkit_1.unwrapTypeSyntax)(singleInit(variable));if(init!==null&&init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isSafeCall(init,scope,depth)){return false}if(variable===null||depth>=MAX_VALUE_HOPS)return true;const values=writtenValues(variable);if(values===null||values.length===0)return true;return values.some(w=>isRawValue(w,scope,variable,depth+1))}return true}function hasRawPart(node,scope,self,depth=0){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some((expression,i)=>!isPlaceholderIndex(node.quasis[i].value.raw,expression,scope)&&isRawValue(expression,scope,self,depth))}const left=node.left;if(isPlaceholderIndex(trailingText(left),node.right,scope)){return isRawValue(left,scope,self,depth)}return isRawValue(left,scope,self,depth)||isRawValue(node.right,scope,self,depth)}function effectiveExpression(node,scope){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed&&prop.key.name==="text"||prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.key.value==="text"));return text===void 0?node:effectiveExpression(text.value,scope)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){const[first]=node.arguments;return first===void 0?node:effectiveExpression(first,scope)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=singleInit(resolveVariable(node.name,scope));return init!==null&&init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?effectiveExpression(init,scope):node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:returned}return node}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const last=body.body.at(-1);if(last?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||last.argument===null)return null;if(last.argument.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return last.argument;return body.body.length===1?returnedExpression(last.argument):null}return body.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||body.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||body.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?body:null}function importedBuilderResult(node,scope,env){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}const variable=resolveVariable(node.callee.name,scope);const origin=variable===null?null:(0,cross_file_1.importOrigin)(variable,env);if(origin===null)return null;const exported=(0,cross_file_1.exportedValue)(origin.module,origin.name,env.parser);const fn=exported===null?null:(0,cross_file_1.follow)(exported);const returned=fn===null?null:(0,cross_file_1.returnedValue)(fn.node);return fn===null||returned===null?null:{node:returned,scope:fn.env.scopeOf(returned),env:fn.env}}function writtenFragments(variable){let parts=[];const writes=variable.references.filter(reference=>reference.isWrite()&&reference.writeExpr!=null).sort((a,b)=>a.identifier.range[0]-b.identifier.range[0]);for(const write of writes){const value=write.writeExpr;const assignment=write.identifier.parent;const appends=assignment?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&(assignment.operator==="+="||leftmostOperand(value)!==value&&isSameBinding(leftmostOperand(value),variable));if(!isStringText(value))parts=[];else if(appends)parts.push(value);else parts=[value]}return parts}function isSameBinding(node,variable){return variable.references.some(reference=>reference.identifier===node)}function isStringText(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"||(0,eslint_devkit_1.staticString)(node)!==null}function leftmostOperand(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&¤t.operator==="+"){current=current.left}return current}exports.noUnsafeQuery={meta:{type:"problem",docs:{description:"Prevent SQL injection by disallowing string concatenation or unsafe template literals in queries.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-query.md",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{noUnsafeQuery:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:"CWE-89",owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Use parameterized queries ($1, $2) instead of string concatenation.",documentationLink:"https://node-postgres.com/features/queries#parameterized-queries"}),unsafeTemplateLiteral:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",fix:"Use parameterized queries ($1, $2) instead of interpolating values.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[]},defaultOptions:[],create(context){const{sourceCode}=context;const env=(0,cross_file_1.envOf)(context);if(!(0,utils_1.usesPostgres)(context))return{};const fragments=new Map;const keyFor=id=>resolveVariable(id.name,sourceCode.getScope(id))??`global:${id.name}`;const isBuilt=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0||node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+";const isStringish=node=>isBuilt(node)||node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||(0,eslint_devkit_1.staticString)(node)!==null;const reportIfUnsafe=(reportNode,parts,self,scopeOf=node=>sourceCode.getScope(node))=>{const selfVariable=typeof self==="string"?null:self;let kind=null;let raw=false;let text="";for(const part of parts){text+=staticText(part);const scope=scopeOf(part);if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&part.operator==="+"){kind="concat";if(hasRawPart(part,scope,selfVariable))raw=true}else if(part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&part.expressions.length>0){kind="template";if(hasRawPart(part,scope,selfVariable))raw=true}}if(kind===null||!raw)return;if(!looksLikeSqlStatement(text))return;context.report({node:reportNode,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.init&&isStringish(node.init)){fragments.set(keyFor(node.id),[node.init])}},AssignmentExpression(node){if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const key=keyFor(node.left);if(node.operator==="+="){const existing2=fragments.get(key);if(existing2===void 0)fragments.set(key,[node.right]);else existing2.push(node.right);return}if(node.operator!=="=")return;if(!isStringish(node.right)){fragments.delete(key);return}const head=leftmostOperand(node.right);const existing=fragments.get(key);if(existing!==void 0&&head.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&keyFor(head)===key){existing.push(node.right)}else{fragments.set(key,[node.right])}},CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!SQL_SINK_METHODS.has((0,eslint_devkit_1.propertyName)(node.callee)??"")){return}const[queryArg]=node.arguments;if(queryArg===void 0||queryArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const scope=sourceCode.getScope(node);const imported=importedBuilderResult(queryArg,scope,env);if(imported!==null){const{node:result,env:builderEnv}=imported;if(isBuilt(result)){reportIfUnsafe(queryArg,[result],null,builderEnv.scopeOf)}else if(result.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(result.name,builderEnv.scopeOf(result));if(variable!==null){reportIfUnsafe(queryArg,writtenFragments(variable),variable,builderEnv.scopeOf)}}return}const expression=effectiveExpression(queryArg,scope);if(isBuilt(expression)){reportIfUnsafe(queryArg,[expression],null);return}if(expression.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const key=keyFor(expression);const parts=fragments.get(key);if(parts!==void 0)reportIfUnsafe(queryArg,parts,key)}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeSearchPath=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const connection_config_1=require("../../utils/connection-config");const sql_scan_1=require("../../utils/sql-scan");const SQL_SINK_METHODS=new Set(["query","execute"]);const SEARCH_PATH_STATEMENT=/^\s*set\s+(?:local\s+|session\s+)?search_path\b/i;const SET_CONFIG_SEARCH_PATH=/\bset_config\s*\(\s*'search_path'/i;const SEARCH_PATH_OPTION=/(?:^|\s)-c\s*search_path\s*=/i;function configProperty(object,name){const found=object.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(p)===name);return found?.value}const MAX_RESOLUTION_DEPTH=4;function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}return(0,eslint_devkit_1.staticString)(node)??""}function setsSearchPath(text){return(0,sql_scan_1.stripComments)(text).split(";").some(statement=>SEARCH_PATH_STATEMENT.test(statement))}function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const[only]=body.body;if(body.body.length!==1||only.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument===null?null:returnedExpression(only.argument)}return body.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||body.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||(0,eslint_devkit_1.staticString)(body)!==null?body:null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(tag)==="raw"}function singleAssignedInit(variable){if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;const init=def.node.init;return init??null}function effectiveExpression(node,scope,depth=0){if(depth>=MAX_RESOLUTION_DEPTH)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return isStringRawTag(node)?node.quasi:node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=variable===null?null:singleAssignedInit(variable);return init===null?node:effectiveExpression(init,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:effectiveExpression(returned,scope,depth+1)}return node}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(exitsUnconditionally)}return false}function isAssertionAbout(call,index,scope){if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=resolveVariable(call.callee.name,scope);const fn=variable===null?null:functionImplementation(variable);const predicate=fn?.returnType?.typeAnnotation;const param=fn?.params[index];return predicate?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypePredicate&&predicate.asserts&&predicate.parameterName.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶m?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶m.name===predicate.parameterName.name}function isAllowlistGuarded(variable,sink){return variable.references.some(ref=>{const call=ref.identifier.parent;if(call?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.range[1]<=sink.range[0]&&isAssertionAbout(call,call.arguments.indexOf(ref.identifier),ref.from)){return true}for(let current=ref.identifier;current!==void 0&¤t!==null;current=current.parent){const parent=current.parent;if(parent!==void 0&&parent!==null&&parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&parent.test===current){return parent.range[1]<=sink.range[0]&&exitsUnconditionally(parent.consequent)}}return false})}function isRawPart(part,scope,sink){if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawPart(part,scope,sink)}if((0,eslint_devkit_1.isStaticExpression)({node:part,scope}))return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(part.name,scope);if(variable!==null&&isAllowlistGuarded(variable,sink))return false}return true}function hasRawPart(node,scope,sink){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>isRawPart(part,scope,sink))}exports.noUnsafeSearchPath={meta:{type:"problem",docs:{description:"Prevent unsafe SET search_path usage with dynamic values, which can lead to schema hijacking.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-search-path.md",cwe:"CWE-426",cvss:7.5},messages:{noUnsafeSearchPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Schema Hijacking Risk",description:'Unsafe "SET search_path" detected.',severity:"CRITICAL",cwe:"CWE-426",owasp:"A05:2021",compliance:["SOC2","PCI-DSS"],effort:"low",fix:"Do not use dynamic values for search_path. Use static strings or strict validation.",documentationLink:"https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeSearchPath=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const connection_config_1=require("../../utils/connection-config");const cross_file_1=require("../../utils/cross-file");const sql_scan_1=require("../../utils/sql-scan");const SQL_SINK_METHODS=new Set(["query","execute"]);const SEARCH_PATH_STATEMENT=/^\s*set\s+(?:local\s+|session\s+)?search_path\b/i;const SET_CONFIG_SEARCH_PATH=/\bset_config\s*\(\s*'search_path'/i;const SEARCH_PATH_OPTION=/(?:^|\s)-c\s*search_path\s*=/i;function configProperty(object,name){const found=object.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(p)===name);return found?.value}const MAX_RESOLUTION_DEPTH=4;function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}return(0,eslint_devkit_1.staticString)(node)??""}function setsSearchPath(text){return(0,sql_scan_1.stripComments)(text).split(";").some(statement=>SEARCH_PATH_STATEMENT.test(statement))}function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function functionImplementation(variable){const def=variable.defs.find(d=>d.type==="FunctionName"||d.type==="Variable");if(def===void 0)return null;if(def.type==="FunctionName"){return def.node}if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const init=def.node.init;if(init===null||init===void 0||init.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&init.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}return init}function returnedExpression(body){if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const[only]=body.body;if(body.body.length!==1||only.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument===null?null:returnedExpression(only.argument)}return body.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||body.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||(0,eslint_devkit_1.staticString)(body)!==null?body:null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(tag)==="raw"}function singleAssignedInit(variable){if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;const init=def.node.init;return init??null}function effectiveExpression(node,scope,depth=0){if(depth>=MAX_RESOLUTION_DEPTH)return node;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){return isStringRawTag(node)?node.quasi:node}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);const init=variable===null?null:singleAssignedInit(variable);return init===null?node:effectiveExpression(init,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const fn=resolveVariable(node.callee.name,scope);const impl=fn===null?null:functionImplementation(fn);if(impl===null)return node;const returned=returnedExpression(impl.body);return returned===null?node:effectiveExpression(returned,scope,depth+1)}return node}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(exitsUnconditionally)}return false}function isAssertionAbout(call,index,scope){if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=resolveVariable(call.callee.name,scope);const fn=variable===null?null:functionImplementation(variable);const predicate=fn?.returnType?.typeAnnotation;const param=fn?.params[index];return predicate?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypePredicate&&predicate.asserts&&predicate.parameterName.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶m?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶m.name===predicate.parameterName.name}function isAllowlistGuarded(variable,sink){return variable.references.some(ref=>{const call=ref.identifier.parent;if(call?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&call.range[1]<=sink.range[0]&&isAssertionAbout(call,call.arguments.indexOf(ref.identifier),ref.from)){return true}for(let current=ref.identifier;current!==void 0&¤t!==null;current=current.parent){const parent=current.parent;if(parent!==void 0&&parent!==null&&parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&parent.test===current){return parent.range[1]<=sink.range[0]&&exitsUnconditionally(parent.consequent)}}return false})}function isRawPart(part,scope,sink){if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawPart(part,scope,sink)}if((0,eslint_devkit_1.isStaticExpression)({node:part,scope}))return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(part.name,scope);if(variable!==null&&isAllowlistGuarded(variable,sink))return false}return true}function hasRawPart(node,scope,sink){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>isRawPart(part,scope,sink))}exports.noUnsafeSearchPath={meta:{type:"problem",docs:{description:"Prevent unsafe SET search_path usage with dynamic values, which can lead to schema hijacking.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-search-path.md",cwe:"CWE-426",cvss:7.5},messages:{noUnsafeSearchPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Schema Hijacking Risk",description:'Unsafe "SET search_path" detected.',severity:"CRITICAL",cwe:"CWE-426",owasp:"A05:2021",compliance:["SOC2","PCI-DSS"],effort:"low",fix:"Do not use dynamic values for search_path. Use static strings or strict validation.",documentationLink:"https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))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||!SQL_SINK_METHODS.has(node.callee.property.name)){return}const[queryArg]=node.arguments;if(queryArg===void 0||queryArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const scope=context.sourceCode.getScope(node);const config=queryArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?queryArg:null;const textNode=config===null?queryArg:configProperty(config,"text");const valuesNode=config===null?node.arguments[1]:configProperty(config,"values");if(textNode!==void 0&&SET_CONFIG_SEARCH_PATH.test((0,sql_scan_1.stripComments)(staticText(textNode)))&&valuesNode?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&valuesNode.elements.some(element=>element!==null&&(element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement||isRawPart(element,scope,node)))){context.report({node:queryArg,messageId:"noUnsafeSearchPath"});return}const expression=effectiveExpression(queryArg,scope);if(expression.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const statement=expression.arguments.find(arg=>arg.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&setsSearchPath(staticText(arg)));if(statement===void 0)return;const dynamic=expression.arguments.some(arg=>arg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement||!(0,eslint_devkit_1.isStaticExpression)({node:arg,scope}));if(dynamic){context.report({node:queryArg,messageId:"noUnsafeSearchPath"})}return}if(expression.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&!(expression.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&expression.operator==="+")){return}if(!setsSearchPath(staticText(expression)))return;if(!hasRawPart(expression,scope,node))return;context.report({node:queryArg,messageId:"noUnsafeSearchPath"})},NewExpression(node){const scope=context.sourceCode.getScope(node);for(const argument of(0,connection_config_1.connectionConfigArguments)(node,scope)){const config=(0,cross_file_1.follow)({node:argument,scope,env:(0,cross_file_1.envOf)(context)}).node;if(config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;const options=configProperty(config,"options");if(options!==void 0&&(options.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||options.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&SEARCH_PATH_OPTION.test(staticText(options))&&hasRawPart(options,scope,node)){context.report({node:options,messageId:"noUnsafeSearchPath"})}}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.preferPoolQuery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const SESSION_STATEMENTS=[/^begin\b/i,/^start\s+transaction\b/i,/^commit\b/i,/^end\b/i,/^rollback\b/i,/^savepoint\b/i,/^release\s+savepoint\b/i,/^set\b/i,/^reset\b/i,/^discard\b/i,/^listen\b/i,/^unlisten\b/i,/^notify\b/i,/^declare\b/i,/^fetch\b/i,/^move\b/i,/^close\b/i,/^copy\b/i,/^prepare\b/i,/^execute\b/i,/^deallocate\b/i,/^lock\b/i];const SESSION_FUNCTIONS=/\bpg_(?:try_)?advisory_(?:xact_)?(?:un)?lock\w*\s*\(|\bpg_export_snapshot\s*\(/i;function needsSessionAffinity(text){const trimmed=text.trim();return SESSION_STATEMENTS.some(pattern=>pattern.test(trimmed))||SESSION_FUNCTIONS.test(trimmed)}function statementText(node){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.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.cooked).join(" 1 ")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!property.computed&&property.key.name==="text");return text===void 0?null:statementText(text.value)}return null}function isFunctionOrProgram(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.Program}function isLoop(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement}function owningScopeNode(node){let current=node;while(!isFunctionOrProgram(current)){current=current.parent}return current}function runsExactlyOnce(call,declarator){const owner=owningScopeNode(declarator);for(let node=call.parent;node&&node!==owner;node=node.parent){if(isLoop(node)||isFunctionOrProgram(node))return false}return true}exports.preferPoolQuery={meta:{type:"suggestion",docs:{description:"Prefer pool.query() over client.query() for single-shot queries.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/prefer-pool-query.md",cwe:"CWE-400"},messages:{preferPoolQuery:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"Prefer Pool Query",description:"Single-shot queries should use pool.query() directly.",severity:"MEDIUM",cwe:"CWE-400",effort:"low",fix:"Use pool.query(...) instead of manual client checkout/release for simple queries.",documentationLink:"https://node-postgres.com/features/pooling"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.preferPoolQuery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const SESSION_STATEMENTS=[/^begin\b/i,/^start\s+transaction\b/i,/^commit\b/i,/^end\b/i,/^rollback\b/i,/^savepoint\b/i,/^release\s+savepoint\b/i,/^set\b/i,/^reset\b/i,/^discard\b/i,/^listen\b/i,/^unlisten\b/i,/^notify\b/i,/^declare\b/i,/^fetch\b/i,/^move\b/i,/^close\b/i,/^copy\b/i,/^prepare\b/i,/^execute\b/i,/^deallocate\b/i,/^lock\b/i];const SESSION_FUNCTIONS=/\bpg_(?:try_)?advisory_(?:xact_)?(?:un)?lock\w*\s*\(|\bpg_export_snapshot\s*\(/i;function needsSessionAffinity(text){const trimmed=text.trim();return SESSION_STATEMENTS.some(pattern=>pattern.test(trimmed))||SESSION_FUNCTIONS.test(trimmed)}function statementText(node){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.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.cooked).join(" 1 ")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=node.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!property.computed&&property.key.name==="text");return text===void 0?null:statementText(text.value)}return null}function isFunctionOrProgram(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.Program}function isLoop(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement}function owningScopeNode(node){let current=node;while(!isFunctionOrProgram(current)){current=current.parent}return current}function runsExactlyOnce(call,declarator){const owner=owningScopeNode(declarator);for(let node=call.parent;node&&node!==owner;node=node.parent){if(isLoop(node)||isFunctionOrProgram(node))return false}return true}exports.preferPoolQuery={meta:{type:"suggestion",docs:{description:"Prefer pool.query() over client.query() for single-shot queries.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/prefer-pool-query.md",cwe:"CWE-400"},messages:{preferPoolQuery:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.PERFORMANCE,issueName:"Prefer Pool Query",description:"Single-shot queries should use pool.query() directly.",severity:"MEDIUM",cwe:"CWE-400",effort:"low",fix:"Use pool.query(...) instead of manual client checkout/release for simple queries.",documentationLink:"https://node-postgres.com/features/pooling"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};return{VariableDeclarator(node){if(!node.init||node.init.type!==eslint_devkit_1.AST_NODE_TYPES.AwaitExpression||node.init.argument.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.init.argument.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.init.argument.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.init.argument.callee.property.name!=="connect"){return}const[variable]=context.sourceCode.getDeclaredVariables(node);if(!variable)return;let queryCallCount=0;let releaseCallCount=0;let otherUsageCount=0;for(const ref of variable.references){if(ref.isWrite())continue;const id=ref.identifier;const access=id.parent;if(access===void 0||access.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||access.object!==id||access.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){otherUsageCount+=1;continue}if(access.property.name==="release"){releaseCallCount+=1;continue}if(access.property.name!=="query"){otherUsageCount+=1;continue}queryCallCount+=1;const call=access.parent;if(call===void 0||call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){otherUsageCount+=1;continue}if(!runsExactlyOnce(call,node))return;const[queryArg]=call.arguments;if(queryArg===void 0)return;const text=statementText(queryArg);if(text===null||needsSessionAffinity(text))return}if(queryCallCount===1&&releaseCallCount===1&&otherUsageCount===0){context.report({node,messageId:"preferPoolQuery"})}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.preventDoubleRelease=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");function findAncestor(node,predicate){let current=node?.parent;while(current){if(predicate(current))return current;current=current.parent}return null}function isInCatchBlock(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.CatchClause)}function isInFinallyBlock(node){const tryStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement);if(!tryStmt?.finalizer)return null;const nodeRange=node.range;const finalizerRange=tryStmt.finalizer.range;if(nodeRange[0]>=finalizerRange[0]&&nodeRange[1]<=finalizerRange[1]){return tryStmt}return null}function isInTryBlock(node){const tryStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement);if(!tryStmt)return null;const nodeRange=node.range;const blockRange=tryStmt.block.range;if(nodeRange[0]>=blockRange[0]&&nodeRange[1]<=blockRange[1]){return tryStmt}return null}function getContainingFunction(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||n.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||n.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)}function negatedFlagName(test){if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")return null;const arg=test.argument;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return arg.name;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!arg.computed&&arg.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return arg.property.name}return null}function assignsTrue(node,flag){let found=false;const walk=current=>{if(found)return;if(current.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&¤t.operator==="="&¤t.right.type===eslint_devkit_1.AST_NODE_TYPES.Literal&¤t.right.value===true){const{left}=current;if(left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.name===flag)found=true;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(left)===flag){found=true}}for(const key of Object.keys(current)){if(key==="parent")continue;const value=current[key];if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item)walk(item)}}else if(value&&typeof value==="object"&&"type"in value){walk(value)}}};walk(node);return found}function isGuardedByCondition(node){const ifStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(!ifStmt)return false;const flag=negatedFlagName(ifStmt.test);if(flag===null)return false;return assignsTrue(ifStmt.consequent,flag)}function areMutuallyExclusiveBranches(nodeA,nodeB){const ifA=findAncestor(nodeA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);const ifB=findAncestor(nodeB,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(!ifA||!ifB)return false;if(ifA===ifB){const nodeARange=nodeA.range;const nodeBRange=nodeB.range;const consequentRange=ifA.consequent.range;const alternateRange=ifA.alternate?.range;if(!alternateRange)return false;const aInConsequent=nodeARange[0]>=consequentRange[0]&&nodeARange[1]<=consequentRange[1];const bInConsequent=nodeBRange[0]>=consequentRange[0]&&nodeBRange[1]<=consequentRange[1];const aInAlternate=nodeARange[0]>=alternateRange[0]&&nodeARange[1]<=alternateRange[1];const bInAlternate=nodeBRange[0]>=alternateRange[0]&&nodeBRange[1]<=alternateRange[1];return aInConsequent&&bInAlternate||aInAlternate&&bInConsequent}return false}function hasExitBetween(block,startIdx,endIdx){for(let k=startIdx+1;k<endIdx;k++){const stmt=block.body[k];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true}return false}function caseHasExit(switchCase){for(const stmt of switchCase.consequent){if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.BreakStatement)return true}return false}function getSwitchCase(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.SwitchCase)}function getDirectIfStatement(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement)}function ifBranchHasExitAfterRelease(releaseNode,ifStmt){const releaseRange=releaseNode.range;const consequentRange=ifStmt.consequent.range;const inConsequent=releaseRange[0]>=consequentRange[0]&&releaseRange[1]<=consequentRange[1];let branchBlock=null;if(inConsequent&&ifStmt.consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){branchBlock=ifStmt.consequent}else if(!inConsequent&&ifStmt.alternate?.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){branchBlock=ifStmt.alternate}if(!branchBlock)return false;const releaseParentStmt=releaseNode.parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement?releaseNode.parent:null;if(!releaseParentStmt)return false;const releaseIdx=branchBlock.body.indexOf(releaseParentStmt);if(releaseIdx===-1)return false;for(let i=releaseIdx+1;i<branchBlock.body.length;i++){const stmt=branchBlock.body[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}}return false}function inOppositeBranches(a,b){const within=(node,container)=>container!=null&&node.range[0]>=container.range[0]&&node.range[1]<=container.range[1];for(let current=a.parent;current;current=current.parent){if(current.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement&¤t.type!==eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){continue}const{consequent,alternate}=current;if(within(a,consequent)&&within(b,alternate))return true}return false}function cannotThrow(node){if(node===null)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier||node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&cannotThrow(node.object)}function endsTryBlock(release,tryStatement){const statement=release.parent;const{body}=tryStatement.block;const index=body.indexOf(statement);if(index===-1)return false;return body.slice(index+1).every(s=>s.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&cannotThrow(s.argument))}exports.preventDoubleRelease={meta:{type:"problem",docs:{description:"Prevent releasing a pg client multiple times.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/prevent-double-release.md",cwe:"CWE-415",cweJustification:"CWE-415 (Double Free) \u2014 semantic equivalent for connection lifecycle: releasing a pooled client twice corrupts the pool's internal accounting and can hand the same connection to two callers.",confidence:"medium"},messages:{doubleRelease:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.QUALITY,issueName:"Double Release",description:"Client release() called multiple times on the same object.",severity:"HIGH",effort:"low",fix:"Ensure client.release() is called exactly once per acquisition, preferably in a finally block.",documentationLink:"https://node-postgres.com/api/client#clientrelease"}),doubleReleaseCallback:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.QUALITY,issueName:"Double Release (Callback)",description:"Connection release callback (done) called multiple times.",severity:"HIGH",effort:"low",fix:"Ensure done() or release callback is called exactly once per pool.connect() callback.",documentationLink:"https://node-postgres.com/api/pool#poolconnect"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.fileUsesPostgres)(context.sourceCode.ast))return{};return{"CallExpression > ArrowFunctionExpression, CallExpression > FunctionExpression"(callback){const call=callback.parent;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||call.callee.property.name!=="connect"){return}const doneParam=callback.params[2];if(doneParam===void 0||doneParam.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const calls=context.sourceCode.getDeclaredVariables(callback).filter(v=>v.name===doneParam.name).flatMap(v=>v.references.map(ref=>ref.identifier)).filter(id=>id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&id.parent.callee===id).map(id=>id.parent).sort((a,b)=>a.range[0]-b.range[0]);if(calls.length<2)return;const terminated=node=>{const statement=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement?node.parent:null;const block=statement?.parent;if(block===void 0||block===null||block.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return false}const index=block.body.indexOf(statement);return block.body.slice(index+1).some(s=>s.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||s.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)};if(calls.every((c,i)=>calls.slice(i+1).every(later=>terminated(c)||inOppositeBranches(c,later)))){return}context.report({node:calls[calls.length-1],messageId:"doubleReleaseCallback"})},VariableDeclarator(node){const declaredVariables=context.sourceCode.getDeclaredVariables(node);for(const variable of declaredVariables){const def=variable.defs[0];const isDestructuredRelease=def?.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&def.name.name==="release";const releaseCalls=[];variable.references.forEach(ref=>{const id=ref.identifier;if(isDestructuredRelease){if(id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&id.parent.callee===id){const callNode=id.parent;const guarded=isGuardedByCondition(callNode);releaseCalls.push({node:callNode,guarded})}}else{if(id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&id.parent.object===id&&(0,eslint_devkit_1.propertyName)(id.parent)==="release"&&id.parent.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callNode=id.parent.parent;const guarded=isGuardedByCondition(callNode);releaseCalls.push({node:callNode,guarded})}}});if(releaseCalls.length>=1&&def?.type==="Variable"){for(const call of releaseCalls){const loop=findAncestor(call.node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement);if(loop===null)continue;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier.range[0]>=loop.range[0]&&ref.identifier.range[1]<=loop.range[1])){continue}if(loop.range[0]<=def.node.range[0]&&def.node.range[1]<=loop.range[1]){continue}if(getContainingFunction(call.node)!==getContainingFunction(def.node))continue;context.report({node:call.node,messageId:"doubleRelease"})}}if(releaseCalls.length>1){releaseCalls.sort((a,b)=>a.node.range[0]-b.node.range[0]);const reported=new Set;for(let i=0;i<releaseCalls.length;i++){for(let j=i+1;j<releaseCalls.length;j++){const callA=releaseCalls[i];const callB=releaseCalls[j];if(reported.has(callB.node))continue;if(callA.guarded&&callB.guarded)continue;if(areMutuallyExclusiveBranches(callA.node,callB.node))continue;const funcA=getContainingFunction(callA.node);const funcB=getContainingFunction(callB.node);if(funcA!==funcB)continue;const tryA=isInTryBlock(callA.node);const catchB=isInCatchBlock(callB.node);if(tryA&&catchB&&catchB.parent===tryA){if(endsTryBlock(callA.node,tryA))continue;context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}const catchA=isInCatchBlock(callA.node);const tryB=isInTryBlock(callB.node);if(catchA&&tryB&&catchA.parent===tryB){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}const switchCaseA=getSwitchCase(callA.node);const switchCaseB=getSwitchCase(callB.node);if(switchCaseA&&switchCaseB&&switchCaseA!==switchCaseB){const switchA=findAncestor(switchCaseA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.SwitchStatement);const switchB=findAncestor(switchCaseB,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.SwitchStatement);if(switchA===switchB&&switchA){if(!caseHasExit(switchCaseA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}const ifA=getDirectIfStatement(callA.node);if(ifA&&!ifA.alternate){if(callB.node.range[0]>ifA.range[1]){const parentBlock=findAncestor(ifA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement);if(parentBlock){const bParentStmt=callB.node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement?callB.node.parent:null;if(bParentStmt&&parentBlock.body.includes(bParentStmt)){if(!ifBranchHasExitAfterRelease(callA.node,ifA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}}}const ifB=getDirectIfStatement(callB.node);if(ifA&&ifB&&ifA!==ifB&&!ifA.alternate&&!ifB.alternate){const parentBlockA=ifA.parent;const parentBlockB=ifB.parent;if(parentBlockA===parentBlockB&&parentBlockA?.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){if(!ifBranchHasExitAfterRelease(callA.node,ifA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}const parentA=callA.node.parent?.parent;const parentB=callB.node.parent?.parent;if(parentA&&parentB&&parentA===parentB&&parentA.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const block=parentA;const indexA=block.body.indexOf(callA.node.parent);const indexB=block.body.indexOf(callB.node.parent);if(indexB>indexA&&!hasExitBetween(block,indexA,indexB)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const catchAForFinally=isInCatchBlock(callA.node);const finallyB=isInFinallyBlock(callB.node);if(catchAForFinally&&finallyB){const tryOfCatch=catchAForFinally.parent;if(tryOfCatch===finallyB){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const tryAForFinally=isInTryBlock(callA.node);const finallyB2=isInFinallyBlock(callB.node);if(tryAForFinally&&finallyB2&&tryAForFinally===finallyB2){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}const finallyA=isInFinallyBlock(callA.node);if(finallyA){const tryEndPos=finallyA.range[1];if(callB.node.range[0]>tryEndPos){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const tryAWithOrWithout=isInTryBlock(callA.node);if(tryAWithOrWithout){const tryEndPos=tryAWithOrWithout.range[1];if(callB.node.range[0]>tryEndPos&&!isInFinallyBlock(callB.node)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const ifStmtA=findAncestor(callA.node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(ifStmtA&&finallyB){if(!ifBranchHasExitAfterRelease(callA.node,ifStmtA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const catchAForAfter=isInCatchBlock(callA.node);if(catchAForAfter){const tryOfCatchA=catchAForAfter.parent;const tryEndPos=tryOfCatchA.range[1];if(callB.node.range[0]>tryEndPos){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const isInExpression=exprNode=>{let current=exprNode.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression)return true;if(current.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression)return true;if(current.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement)break;if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement)break;current=current.parent}return false};if(isInExpression(callA.node)){let exprStmtA=callA.node;while(exprStmtA&&exprStmtA.type!==eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement){exprStmtA=exprStmtA.parent??null}if(exprStmtA&&callB.node.range[0]>exprStmtA.range[1]){const blockA=findAncestor(exprStmtA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement);const blockB=findAncestor(callB.node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement);if(blockA&&blockA===blockB){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}}}}}}}}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.preventDoubleRelease=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");function findAncestor(node,predicate){let current=node?.parent;while(current){if(predicate(current))return current;current=current.parent}return null}function isInCatchBlock(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.CatchClause)}function isInFinallyBlock(node){const tryStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement);if(!tryStmt?.finalizer)return null;const nodeRange=node.range;const finalizerRange=tryStmt.finalizer.range;if(nodeRange[0]>=finalizerRange[0]&&nodeRange[1]<=finalizerRange[1]){return tryStmt}return null}function isInTryBlock(node){const tryStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement);if(!tryStmt)return null;const nodeRange=node.range;const blockRange=tryStmt.block.range;if(nodeRange[0]>=blockRange[0]&&nodeRange[1]<=blockRange[1]){return tryStmt}return null}function getContainingFunction(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||n.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||n.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)}function negatedFlagName(test){if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")return null;const arg=test.argument;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return arg.name;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!arg.computed&&arg.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return arg.property.name}return null}function assignsTrue(node,flag){let found=false;const walk=current=>{if(found)return;if(current.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&¤t.operator==="="&¤t.right.type===eslint_devkit_1.AST_NODE_TYPES.Literal&¤t.right.value===true){const{left}=current;if(left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.name===flag)found=true;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(left)===flag){found=true}}for(const key of Object.keys(current)){if(key==="parent")continue;const value=current[key];if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item)walk(item)}}else if(value&&typeof value==="object"&&"type"in value){walk(value)}}};walk(node);return found}function isGuardedByCondition(node){const ifStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(!ifStmt)return false;const flag=negatedFlagName(ifStmt.test);if(flag===null)return false;return assignsTrue(ifStmt.consequent,flag)}function areMutuallyExclusiveBranches(nodeA,nodeB){const ifA=findAncestor(nodeA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);const ifB=findAncestor(nodeB,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(!ifA||!ifB)return false;if(ifA===ifB){const nodeARange=nodeA.range;const nodeBRange=nodeB.range;const consequentRange=ifA.consequent.range;const alternateRange=ifA.alternate?.range;if(!alternateRange)return false;const aInConsequent=nodeARange[0]>=consequentRange[0]&&nodeARange[1]<=consequentRange[1];const bInConsequent=nodeBRange[0]>=consequentRange[0]&&nodeBRange[1]<=consequentRange[1];const aInAlternate=nodeARange[0]>=alternateRange[0]&&nodeARange[1]<=alternateRange[1];const bInAlternate=nodeBRange[0]>=alternateRange[0]&&nodeBRange[1]<=alternateRange[1];return aInConsequent&&bInAlternate||aInAlternate&&bInConsequent}return false}function hasExitBetween(block,startIdx,endIdx){for(let k=startIdx+1;k<endIdx;k++){const stmt=block.body[k];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true}return false}function alwaysExits(block){return block.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}function caseHasExit(switchCase){for(const stmt of switchCase.consequent){if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.BreakStatement)return true}return false}function getSwitchCase(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.SwitchCase)}function getDirectIfStatement(node){return findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement)}function ifBranchHasExitAfterRelease(releaseNode,ifStmt){const releaseRange=releaseNode.range;const consequentRange=ifStmt.consequent.range;const inConsequent=releaseRange[0]>=consequentRange[0]&&releaseRange[1]<=consequentRange[1];let branchBlock=null;if(inConsequent&&ifStmt.consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){branchBlock=ifStmt.consequent}else if(!inConsequent&&ifStmt.alternate?.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){branchBlock=ifStmt.alternate}if(!branchBlock)return false;const releaseParentStmt=releaseNode.parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement?releaseNode.parent:null;if(!releaseParentStmt)return false;const releaseIdx=branchBlock.body.indexOf(releaseParentStmt);if(releaseIdx===-1)return false;for(let i=releaseIdx+1;i<branchBlock.body.length;i++){const stmt=branchBlock.body[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}}return false}function inOppositeBranches(a,b){const within=(node,container)=>container!=null&&node.range[0]>=container.range[0]&&node.range[1]<=container.range[1];for(let current=a.parent;current;current=current.parent){if(current.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement&¤t.type!==eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){continue}const{consequent,alternate}=current;if(within(a,consequent)&&within(b,alternate))return true}return false}function cannotThrow(node){if(node===null)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier||node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&cannotThrow(node.object)}function endsTryBlock(release,tryStatement){const statement=release.parent;const{body}=tryStatement.block;const index=body.indexOf(statement);if(index===-1)return false;return body.slice(index+1).every(s=>s.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&cannotThrow(s.argument))}exports.preventDoubleRelease={meta:{type:"problem",docs:{description:"Prevent releasing a pg client multiple times.",url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/prevent-double-release.md",cwe:"CWE-415",cweJustification:"CWE-415 (Double Free) \u2014 semantic equivalent for connection lifecycle: releasing a pooled client twice corrupts the pool's internal accounting and can hand the same connection to two callers.",confidence:"medium"},messages:{doubleRelease:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.QUALITY,issueName:"Double Release",description:"Client release() called multiple times on the same object.",severity:"HIGH",effort:"low",fix:"Ensure client.release() is called exactly once per acquisition, preferably in a finally block.",documentationLink:"https://node-postgres.com/api/client#clientrelease"}),doubleReleaseCallback:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.QUALITY,issueName:"Double Release (Callback)",description:"Connection release callback (done) called multiple times.",severity:"HIGH",effort:"low",fix:"Ensure done() or release callback is called exactly once per pool.connect() callback.",documentationLink:"https://node-postgres.com/api/pool#poolconnect"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.usesPostgres)(context))return{};return{"CallExpression > ArrowFunctionExpression, CallExpression > FunctionExpression"(callback){const call=callback.parent;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||call.callee.property.name!=="connect"){return}const doneParam=callback.params[2];if(doneParam===void 0||doneParam.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const calls=context.sourceCode.getDeclaredVariables(callback).filter(v=>v.name===doneParam.name).flatMap(v=>v.references.map(ref=>ref.identifier)).filter(id=>id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&id.parent.callee===id).map(id=>id.parent).sort((a,b)=>a.range[0]-b.range[0]);if(calls.length<2)return;const terminated=node=>{const statement=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement?node.parent:null;const block=statement?.parent;if(block===void 0||block===null||block.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return false}const index=block.body.indexOf(statement);return block.body.slice(index+1).some(s=>s.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||s.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)};if(calls.every((c,i)=>calls.slice(i+1).every(later=>terminated(c)||inOppositeBranches(c,later)))){return}context.report({node:calls[calls.length-1],messageId:"doubleReleaseCallback"})},VariableDeclarator(node){const declaredVariables=context.sourceCode.getDeclaredVariables(node);for(const variable of declaredVariables){const def=variable.defs[0];const isDestructuredRelease=def?.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&def.name.name==="release";const releaseCalls=[];variable.references.forEach(ref=>{const id=ref.identifier;if(isDestructuredRelease){if(id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&id.parent.callee===id){const callNode=id.parent;const guarded=isGuardedByCondition(callNode);releaseCalls.push({node:callNode,guarded})}}else{if(id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&id.parent.object===id&&(0,eslint_devkit_1.propertyName)(id.parent)==="release"&&id.parent.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callNode=id.parent.parent;const guarded=isGuardedByCondition(callNode);releaseCalls.push({node:callNode,guarded})}}});if(releaseCalls.length>=1&&def?.type==="Variable"){for(const call of releaseCalls){const loop=findAncestor(call.node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement);if(loop===null)continue;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier.range[0]>=loop.range[0]&&ref.identifier.range[1]<=loop.range[1])){continue}if(loop.range[0]<=def.node.range[0]&&def.node.range[1]<=loop.range[1]){continue}if(getContainingFunction(call.node)!==getContainingFunction(def.node))continue;context.report({node:call.node,messageId:"doubleRelease"})}}if(releaseCalls.length>1){releaseCalls.sort((a,b)=>a.node.range[0]-b.node.range[0]);const reported=new Set;for(let i=0;i<releaseCalls.length;i++){for(let j=i+1;j<releaseCalls.length;j++){const callA=releaseCalls[i];const callB=releaseCalls[j];if(reported.has(callB.node))continue;if(callA.guarded&&callB.guarded)continue;if(areMutuallyExclusiveBranches(callA.node,callB.node))continue;const funcA=getContainingFunction(callA.node);const funcB=getContainingFunction(callB.node);if(funcA!==funcB)continue;const tryA=isInTryBlock(callA.node);const catchB=isInCatchBlock(callB.node);if(tryA&&catchB&&catchB.parent===tryA){if(endsTryBlock(callA.node,tryA))continue;context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}const catchA=isInCatchBlock(callA.node);const tryB=isInTryBlock(callB.node);if(catchA&&tryB&&catchA.parent===tryB){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}const switchCaseA=getSwitchCase(callA.node);const switchCaseB=getSwitchCase(callB.node);if(switchCaseA&&switchCaseB&&switchCaseA!==switchCaseB){const switchA=findAncestor(switchCaseA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.SwitchStatement);const switchB=findAncestor(switchCaseB,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.SwitchStatement);if(switchA===switchB&&switchA){if(!caseHasExit(switchCaseA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}const ifA=getDirectIfStatement(callA.node);if(ifA&&!ifA.alternate){if(callB.node.range[0]>ifA.range[1]){const parentBlock=findAncestor(ifA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement);if(parentBlock){const bParentStmt=callB.node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement?callB.node.parent:null;if(bParentStmt&&parentBlock.body.includes(bParentStmt)){if(!ifBranchHasExitAfterRelease(callA.node,ifA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}}}const ifB=getDirectIfStatement(callB.node);if(ifA&&ifB&&ifA!==ifB&&!ifA.alternate&&!ifB.alternate){const parentBlockA=ifA.parent;const parentBlockB=ifB.parent;if(parentBlockA===parentBlockB&&parentBlockA?.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){if(!ifBranchHasExitAfterRelease(callA.node,ifA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}const parentA=callA.node.parent?.parent;const parentB=callB.node.parent?.parent;if(parentA&&parentB&&parentA===parentB&&parentA.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const block=parentA;const indexA=block.body.indexOf(callA.node.parent);const indexB=block.body.indexOf(callB.node.parent);if(indexB>indexA&&!hasExitBetween(block,indexA,indexB)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const catchAForFinally=isInCatchBlock(callA.node);const finallyB=isInFinallyBlock(callB.node);if(catchAForFinally&&finallyB){const tryOfCatch=catchAForFinally.parent;if(tryOfCatch===finallyB){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const tryAForFinally=isInTryBlock(callA.node);const finallyB2=isInFinallyBlock(callB.node);if(tryAForFinally&&finallyB2&&tryAForFinally===finallyB2){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}const finallyA=isInFinallyBlock(callA.node);if(finallyA){const tryEndPos=finallyA.range[1];if(callB.node.range[0]>tryEndPos){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const tryAWithOrWithout=isInTryBlock(callA.node);if(tryAWithOrWithout){const tryEndPos=tryAWithOrWithout.range[1];if(callB.node.range[0]>tryEndPos&&!isInFinallyBlock(callB.node)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const ifStmtA=findAncestor(callA.node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(ifStmtA&&finallyB){if(!ifBranchHasExitAfterRelease(callA.node,ifStmtA)){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const catchAForAfter=isInCatchBlock(callA.node);if(catchAForAfter&&!alwaysExits(catchAForAfter.body)){const tryOfCatchA=catchAForAfter.parent;const tryEndPos=tryOfCatchA.range[1];if(callB.node.range[0]>tryEndPos){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}const isInExpression=exprNode=>{let current=exprNode.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression)return true;if(current.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression)return true;if(current.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement)break;if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement)break;current=current.parent}return false};if(isInExpression(callA.node)){let exprStmtA=callA.node;while(exprStmtA&&exprStmtA.type!==eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement){exprStmtA=exprStmtA.parent??null}if(exprStmtA&&callB.node.range[0]>exprStmtA.range[1]){const blockA=findAncestor(exprStmtA,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement);const blockB=findAncestor(callB.node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement);if(blockA&&blockA===blockB){context.report({node:callB.node,messageId:"doubleRelease"});reported.add(callB.node);continue}}}}}}}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isPgClientConstructor=isPgClientConstructor;exports.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isPgClientConstructor=isPgClientConstructor;exports.connectionConfigArguments=connectionConfigArguments;exports.typedConnectionConfig=typedConnectionConfig;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");const pool_receiver_1=require("./pool-receiver");const PG_MODULE_SET=new Set(index_1.PG_MODULES);const PG_CONFIG_TYPES=new Set(["PoolConfig","ClientConfig","ConnectionConfig"]);function packageRoot(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function isPgClientConstructor(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding===void 0||!PG_MODULE_SET.has(packageRoot(binding.module)))return false;const[exported]=binding.path;return exported===void 0||exported==="Pool"||exported==="Client"}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return void 0}function singleInit(variable){if(variable===void 0)return null;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");return def===void 0?null:def.node.init??null}function isPgPromiseFactory(callee,scope){const init=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?singleInit(lookup(callee.name,scope)):callee;return init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&(0,eslint_devkit_1.resolveModuleBinding)(init.callee,scope)?.module==="pg-promise"}function connectionConfigArguments(node,scope){const args=node.arguments.filter(arg=>arg.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement);if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return isPgClientConstructor(node.callee,scope)?args.slice(0,1):[]}const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding?.module==="postgres"&&binding.path.length===0)return args;return isPgPromiseFactory(node.callee,scope)?args.slice(0,1):[]}function isPgConfigType(type,scope){const name=(0,pool_receiver_1.pgTypeName)(type,scope);return name!==null&&PG_CONFIG_TYPES.has(name)}function typedConnectionConfig(node,scope){if(node.init===null)return null;const annotated=node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isPgConfigType(node.id.typeAnnotation?.typeAnnotation,scope);const satisfied=node.init.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression&&isPgConfigType(node.init.typeAnnotation,scope);return annotated||satisfied?node.init:null}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}):function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||(function(){var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k in o2)if(Object.prototype.hasOwnProperty.call(o2,k))ar[ar.length]=k;return ar};return ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null){for(var k=ownKeys(mod),i=0;i<k.length;i++)if(k[i]!=="default")__createBinding(result,mod,k[i])}__setModuleDefault(result,mod);return result}})();Object.defineProperty(exports,"__esModule",{value:true});exports.envOf=envOf;exports.resolveRelative=resolveRelative;exports.parseModule=parseModule;exports.loadModule=loadModule;exports.scopeIn=scopeIn;exports.moduleEnv=moduleEnv;exports.lookup=lookup;exports.exportedValue=exportedValue;exports.findProperty=findProperty;exports.importOrigin=importOrigin;exports.returnedValue=returnedValue;exports.follow=follow;const fs=__importStar(require("node:fs"));const path=__importStar(require("node:path"));const node_module_1=require("node:module");const eslint_devkit_1=require("@interlace/eslint-devkit");const MAX_DEPTH=8;const EXTENSIONS=[".ts",".tsx",".js",".mjs",".cjs",".json"];const RELATIVE=/^\.{1,2}(?:\/|$)/;const JS_EXTENSION=/\.[cm]?js$/;const modules=new Map;function envOf(context){return{file:path.resolve(context.physicalFilename),parser:context.languageOptions?.parser,module:null,scopeOf:node=>context.sourceCode.getScope(node)}}function isFile(candidate){return fs.statSync(candidate,{throwIfNoEntry:false})?.isFile()===true}function resolveRelative(fromFile,specifier){if(!RELATIVE.test(specifier))return null;const base=path.resolve(path.dirname(fromFile),specifier);const candidates=[base,...EXTENSIONS.map(extension=>`${base}${extension}`),...EXTENSIONS.map(extension=>path.join(base,`index${extension}`))];if(JS_EXTENSION.test(base)){const stem=base.replace(JS_EXTENSION,"");candidates.push(`${stem}.ts`,`${stem}.tsx`)}return candidates.find(isFile)??null}function fallbackParser(){try{return(0,node_module_1.createRequire)(path.join(process.cwd(),"package.json"))("@typescript-eslint/parser")}catch{return null}}function linkParents(node,parent){node.parent=parent;for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(typeof child==="object"&&child!==null&&typeof child.type==="string"){linkParents(child,node)}}}}function parseModule(text,file,parser){for(const candidate of[parser,fallbackParser()]){const parseForESLint=candidate?.parseForESLint;if(typeof parseForESLint!=="function")continue;try{const result=parseForESLint(text,{filePath:file,sourceType:"module",ecmaVersion:"latest",range:true,loc:true});if(!result.scopeManager)continue;linkParents(result.ast,void 0);return{file,ast:result.ast,scopeManager:result.scopeManager}}catch{}}return null}function loadModule(file,parser){const stat=fs.statSync(file,{throwIfNoEntry:false});if(stat===void 0||!stat.isFile())return null;const cached=modules.get(file);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs)return cached.info;let info=null;try{const text=fs.readFileSync(file,"utf8");if(path.extname(file)===".json"){JSON.parse(text);info=parseModule(`export default (${text});`,`${file}.ts`,parser)}else{info=parseModule(text,file,parser)}}catch{info=null}modules.set(file,{mtimeMs:stat.mtimeMs,info});return info}function scopeIn(module,node){let current=node;for(;current.parent;current=current.parent){const scope=module.scopeManager.acquire(current,true);if(scope!==null)return scope}return module.scopeManager.acquire(current,true)}function moduleEnv(module,parser){return{file:module.file,parser,module,scopeOf:node=>scopeIn(module,node)}}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function requiredSpecifier(node){if(node?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require"){return null}const[argument]=node.arguments;return argument?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"?argument.value:null}function exportedValue(module,name,parser,depth=0){if(depth>MAX_DEPTH)return null;const env=moduleEnv(module,parser);const at=node=>({node,scope:env.scopeOf(node),env});for(const statement of module.ast.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ExportDefaultDeclaration){if(name==="default")return at(statement.declaration);continue}if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration){const declaration=statement.declaration;if(declaration?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){const declarator=declaration.declarations.find(d=>d.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&d.id.name===name);if(declarator?.init)return at(declarator.init)}else if(declaration?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&declaration.id?.name===name){return at(declaration)}for(const specifier of statement.specifiers){if(moduleExportName(specifier.exported)!==name)continue;const local=moduleExportName(specifier.local);if(statement.source!==null){const target=resolveRelative(module.file,String(statement.source.value));const next=target===null?null:loadModule(target,parser);return next===null?null:exportedValue(next,local,parser,depth+1)}const variable=lookup(local,env.scopeOf(module.ast));return variable===null?null:follow(at(variable.identifiers[0]),depth+1)}continue}if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement&&statement.expression.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&statement.expression.operator==="="){const{left,right}=statement.expression;const target=left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?memberChain(left):null;if(target==="module.exports"){if(name==="default")return at(right);const object=(0,eslint_devkit_1.unwrapTypeSyntax)(right);if(object.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const property=findProperty(object,name);if(property!==null)return at(property)}}else if(target===`module.exports.${name}`||target===`exports.${name}`){return at(right)}}}return null}function moduleExportName(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.name:node.value}function memberChain(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const key=(0,eslint_devkit_1.propertyName)(node);const head=memberChain(node.object);return key===null||head===null?null:`${head}.${key}`}function findProperty(object,key){for(const property of object.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)===key){return property.value}}return null}function importOrigin(variable,env){const def=variable.defs[0];if(def===void 0)return null;let specifier=null;let name="default";if(def.type==="ImportBinding"){const declaration=def.parent;specifier=String(declaration.source.value);if(def.node.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){name=moduleExportName(def.node.imported)}else if(def.node.type===eslint_devkit_1.AST_NODE_TYPES.ImportNamespaceSpecifier){name="*"}}else if(def.type==="Variable"){const declarator=def.node;specifier=requiredSpecifier(declarator.init);if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){const property=declarator.id.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.value.name===variable.name);name=property===void 0?"":(0,eslint_devkit_1.objectKeyName)(property)??""}else{name="*"}}if(specifier===null||name==="")return null;const file=resolveRelative(env.file,specifier);const module=file===null?null:loadModule(file,env.parser);return module===null?null:{module,name}}function returnedValue(fn){if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return null}if(fn.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return fn.body;const last=fn.body.body.at(-1);return last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement?last.argument:null}function singleWrite(variable){if(variable.defs.some(def=>def.type==="Parameter"))return null;const writes=variable.references.filter(reference=>reference.isWrite());if(writes.length!==1)return null;const[write]=writes;return write.writeExpr??null}function follow(start,depth=0,seen=new Set){if(depth>MAX_DEPTH||seen.has(start.node))return start;seen.add(start.node);const{scope,env}=start;const node=(0,eslint_devkit_1.unwrapTypeSyntax)(start.node);const next=(target,nextEnv=env)=>follow({node:target,scope:nextEnv.scopeOf(target),env:nextEnv},depth+1,seen);if(node!==start.node)return next(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression)return next(node.argument);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=lookup(node.name,scope);if(variable===null)return start;if(variable.defs[0]?.type==="FunctionName")return next(variable.defs[0].node);const origin=importOrigin(variable,env);if(origin!==null){const commonJs=origin.name==="*"&&variable.defs[0]?.type==="Variable"?exportedValue(origin.module,"default",env.parser,depth+1):null;if(commonJs!==null)return follow(commonJs,depth+1,seen);if(origin.name==="*"){const namespace=moduleEnv(origin.module,env.parser);return{node:origin.module.ast,scope:namespace.scopeOf(origin.module.ast),env:namespace}}const exported=exportedValue(origin.module,origin.name,env.parser,depth+1);return exported===null?start:follow(exported,depth+1,seen)}const def=variable.defs[0];if(def?.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){const property=def.node.id.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.value.name===node.name);const key=property===void 0?null:(0,eslint_devkit_1.objectKeyName)(property);if(key===null||def.node.init===null)return start;const object=next(def.node.init);if(object.node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return start;const value=findProperty(object.node,key);return value===null?start:next(value,object.env)}const written=singleWrite(variable);return written===null?start:next(written)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const key=(0,eslint_devkit_1.propertyName)(node);if(key===null)return start;const object=next(node.object);if(object.node.type===eslint_devkit_1.AST_NODE_TYPES.Program&&object.env.module!==null){const exported=exportedValue(object.env.module,key,env.parser,depth+1);return exported===null?start:follow(exported,depth+1,seen)}if(object.node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return start;const value=findProperty(object.node,key);return value===null?start:next(value,object.env)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=next(node.callee);const returned=returnedValue(callee.node);if(returned===null)return start;return next(returned,callee.env)}return start}
|
package/src/utils/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PG_MODULES=void 0;exports.fileUsesPostgres=fileUsesPostgres;const eslint_devkit_1=require("@interlace/eslint-devkit");const constants_1=require("../constants");exports.PG_MODULES=["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite"];const PG_MODULE_SET=new Set(exports.PG_MODULES);function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);if(deno)return deno[1];return specifier}function isPgSpecifier(specifier){specifier=normalizeSpecifier(specifier);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return PG_MODULE_SET.has(root)}function isImportEqualsLoad(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.TSImportEqualsDeclaration&&node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference&&node.moduleReference.expression.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.moduleReference.expression.value==="string"&&isPgSpecifier(node.moduleReference.expression.value)}function isPgDynamicImport(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ImportExpression&&node.source.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&isPgSpecifier(node.source.value)}function isPgRequire(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require"){return false}const[arg]=node.arguments;return arg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&isPgSpecifier(arg.value)}function isPgConnectionString(node){const value=node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"?node.value:node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?node.quasis[0].value.cooked??node.quasis[0].value.raw:void 0;return value!==void 0&&constants_1.PG_PROTOCOLS.some(protocol=>value.startsWith(protocol))}function bindsRequire(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return node.params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Program||node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}const cache=new WeakMap;function fileUsesPostgres(ast){const cached=cache.get(ast);if(cached!==void 0)return cached;const result=computeUsesPostgres(ast);cache.set(ast,result);return result}function computeUsesPostgres(ast){let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&isPgSpecifier(node.source.value)){found=true;return}if(isImportEqualsLoad(node)||isPgDynamicImport(node)||!requireIsShadowed&&isPgRequire(node)||isPgConnectionString(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(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(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value.type==="string"&&typeof value==="object"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PG_MODULES=void 0;exports.fileUsesPostgres=fileUsesPostgres;exports.usesPostgres=usesPostgres;const eslint_devkit_1=require("@interlace/eslint-devkit");const constants_1=require("../constants");const cross_file_1=require("./cross-file");exports.PG_MODULES=["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite"];const PG_MODULE_SET=new Set(exports.PG_MODULES);function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);if(deno)return deno[1];return specifier}function isPgSpecifier(specifier){specifier=normalizeSpecifier(specifier);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return PG_MODULE_SET.has(root)}function isImportEqualsLoad(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.TSImportEqualsDeclaration&&node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference&&node.moduleReference.expression.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.moduleReference.expression.value==="string"&&isPgSpecifier(node.moduleReference.expression.value)}function isPgDynamicImport(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ImportExpression&&node.source.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&isPgSpecifier(node.source.value)}function isPgRequire(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require"){return false}const[arg]=node.arguments;return arg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&isPgSpecifier(arg.value)}function isPgConnectionString(node){const value=node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"?node.value:node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?node.quasis[0].value.cooked??node.quasis[0].value.raw:void 0;return value!==void 0&&constants_1.PG_PROTOCOLS.some(protocol=>value.startsWith(protocol))}function bindsRequire(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return node.params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Program||node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}const cache=new WeakMap;function fileUsesPostgres(ast){const cached=cache.get(ast);if(cached!==void 0)return cached;const result=computeUsesPostgres(ast);cache.set(ast,result);return result}function computeUsesPostgres(ast,withDsn=true){let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&isPgSpecifier(node.source.value)){found=true;return}if(isImportEqualsLoad(node)||isPgDynamicImport(node)||!requireIsShadowed&&isPgRequire(node)||withDsn&&isPgConnectionString(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(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(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value.type==="string"&&typeof value==="object"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found}function specifiersIn(ast){const found=[];const literal=node=>{const text=(0,eslint_devkit_1.staticString)(node);if(text!==null)found.push(text)};const visit=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportAllDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration){literal(node.source)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ImportExpression){literal(node.source)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){literal(node.arguments[0])}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSImportEqualsDeclaration&&node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){literal(node.moduleReference.expression)}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(typeof child==="object"&&child!==null&&typeof child.type==="string"){visit(child)}}}};visit(ast);return found}const MAX_MODULE_HOPS=3;function relativeModuleUsesPostgres(ast,file,parser,hops,visited){if(hops>MAX_MODULE_HOPS)return false;for(const specifier of specifiersIn(ast)){const target=(0,cross_file_1.resolveRelative)(file,specifier);if(target===null||visited.has(target))continue;visited.add(target);const module=(0,cross_file_1.loadModule)(target,parser);if(module===null)continue;if(computeUsesPostgres(module.ast,false)||relativeModuleUsesPostgres(module.ast,target,parser,hops+1,visited)){return true}}return false}const relativeCache=new WeakMap;function usesPostgres(context){const{ast}=context.sourceCode;if(fileUsesPostgres(ast))return true;const cached=relativeCache.get(ast);if(cached!==void 0)return cached;const env=(0,cross_file_1.envOf)(context);const result=relativeModuleUsesPostgres(ast,env.file,env.parser,1,new Set);relativeCache.set(ast,result);return result}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isPgPoolType=isPgPoolType;exports.isDeclaredPgPool=isDeclaredPgPool;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");const PG_MODULE_SET=new Set(index_1.PG_MODULES);function packageRoot(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function isPgPoolType(annotation,scope){const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isPgPoolType=isPgPoolType;exports.pgTypeName=pgTypeName;exports.isDeclaredPgPool=isDeclaredPgPool;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");const PG_MODULE_SET=new Set(index_1.PG_MODULES);function packageRoot(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function isPgPoolType(annotation,scope){const target=pgTypeName(annotation?.typeAnnotation,scope);return target===""||target==="Pool"}function pgTypeName(type,scope){let module=null;let name=null;if(type?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference){const{typeName}=type;if(typeName.type===eslint_devkit_1.AST_NODE_TYPES.TSQualifiedName){module=typeName.left;name=typeName.right.name}else{module=typeName}}else if(type?.type===eslint_devkit_1.AST_NODE_TYPES.TSIndexedAccessType&&type.objectType.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference&&type.indexType.type===eslint_devkit_1.AST_NODE_TYPES.TSLiteralType){module=type.objectType.typeName;name=(0,eslint_devkit_1.staticString)(type.indexType.literal)}const binding=module===null?void 0:(0,eslint_devkit_1.resolveModuleBinding)(module,scope);if(binding===void 0||!PG_MODULE_SET.has(packageRoot(binding.module))){return null}return name??binding.path.at(-1)??""}function isDeclaredPgPool(receiver,scope){if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){for(let current=scope;current;current=current.upper){const variable=current.set.get(receiver.name);if(variable===void 0)continue;return variable.defs.some(def=>(def.type==="Parameter"||def.type==="Variable")&&def.name.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isPgPoolType(def.name.typeAnnotation,scope))}return false}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||receiver.object.type!==eslint_devkit_1.AST_NODE_TYPES.ThisExpression){return false}const field=(0,eslint_devkit_1.propertyName)(receiver);let body=receiver.parent;while(body&&body.type!==eslint_devkit_1.AST_NODE_TYPES.ClassBody)body=body.parent;if(field===null||!body)return false;return body.body.some(member=>{if(member.type===eslint_devkit_1.AST_NODE_TYPES.PropertyDefinition){return(0,eslint_devkit_1.objectKeyName)(member)===field&&isPgPoolType(member.typeAnnotation,scope)}if(member.type!==eslint_devkit_1.AST_NODE_TYPES.MethodDefinition||member.kind!=="constructor"){return false}return member.value.params.some(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.TSParameterProperty&¶m.parameter.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶m.parameter.name===field&&isPgPoolType(param.parameter.typeAnnotation,scope))})}
|