eslint-plugin-postgresql-security 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,7 @@
18
18
  <a href="https://opensource.org/licenses/MIT" target="_blank"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="Package License" /></a>
19
19
  <a href="https://app.codecov.io/gh/ofri-peretz/eslint/components?components%5B0%5D=eslint-plugin-postgresql-security" target="_blank"><img src="https://codecov.io/gh/ofri-peretz/eslint/graph/badge.svg?component=eslint-plugin-postgresql-security" alt="Codecov" /></a>
20
20
  <a href="https://github.com/ofri-peretz/eslint" target="_blank"><img src="https://img.shields.io/badge/Since-Dec_2025-blue?logo=rocket&logoColor=white" alt="Since Dec 2025" /></a>
21
+ <a href="https://scorecard.dev/viewer/?uri=github.com/ofri-peretz/eslint" target="_blank"><img src="https://api.securityscorecards.dev/projects/github.com/ofri-peretz/eslint/badge" alt="OpenSSF Scorecard" /></a>
21
22
  </p>
22
23
 
23
24
  > ⭐ If this plugin caught a real bug for you, [**star the repo**](https://github.com/ofri-peretz/eslint) — it's the signal that keeps these rules maintained.
@@ -34,6 +35,45 @@ A generic SQL injection linter can flag string concatenation wherever it appears
34
35
 
35
36
  **Interlace** fosters **strength through integration**. Instead of stacking isolated rules, we **interlace** security directly into your workflow to create a resilient fabric of code. We believe tools should **guide rather than gatekeep**, providing educational feedback that strengthens the developer with every interaction.
36
37
 
38
+ <!-- AUTO-GENERATED:DOCTRINE:START - Do not edit manually -->
39
+
40
+ ## Why these rules are quiet
41
+
42
+ **Noise creates apathy, and apathy is not a security posture.** A linter that reports
43
+ a thousand things a week gets switched off in a month, and the real finding goes with
44
+ it. So every rule here is built to be worth reading: we would rather miss a finding
45
+ than spend your attention on one that was never real.
46
+
47
+ That is a trade, and it is made deliberately. It costs recall, and we measure what it
48
+ costs rather than assuming it is free.
49
+
50
+ ## How the rules decide
51
+
52
+ **Evidence, not names.** A rule fires on what the code *does*, resolved through the
53
+ AST and ESLint's own scope analysis — not on an identifier that happens to contain
54
+ `query`, a method called `setItem`, or a file whose path contains `key`. Every one of
55
+ those was a real false positive in this ecosystem, found by reading our own output on
56
+ open-source projects and fixed with a test that fails on the unfixed rule.
57
+
58
+ Where a rule has known false-positive shapes, its page carries a **Not a finding**
59
+ section: what it deliberately stays quiet on, and what to check first when it fires
60
+ and you disagree.
61
+
62
+ ## What you get
63
+
64
+ The rules below. Security rules carry a CWE mapping and, where one is assigned, a
65
+ CVSS score; every rule carries a fix on its message — in prose for a human and as
66
+ structured JSON for an agent. Install it, enable
67
+ `recommended`, and read the findings. If one of them is wrong,
68
+ [open an issue](https://github.com/ofri-peretz/eslint/issues) — a false positive is a
69
+ bug here, not a tuning exercise for you.
70
+
71
+ How that is measured, on which projects, and where it falls short:
72
+ [benchmark methodology](https://github.com/ofri-peretz/eslint/blob/main/BENCHMARK-METHODOLOGY.md)
73
+ and [results](https://github.com/ofri-peretz/eslint/blob/main/BENCHMARK-RESULTS.md).
74
+
75
+ <!-- AUTO-GENERATED:DOCTRINE:END -->
76
+
37
77
  ## Getting Started
38
78
 
39
79
  - To check out the [guide](https://eslint.interlace.tools/docs/security/plugin-pg?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security), visit [eslint.interlace.tools](https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security). 📚
@@ -115,19 +155,19 @@ See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md)
115
155
  <!-- AUTO-GENERATED:RULES_TABLE:START - Do not edit manually -->
116
156
  | Rule | CWE | OWASP | CVSS | Description | 🧠 | 💼 | ⚠️ | 🔧 | 💡 | 🚫 |
117
157
  | :--- | :---: | :---: | :---: | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
118
- | [check-query-params](https://eslint.interlace.tools/docs/security/plugin-pg/rules/check-query-params?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-89 | | | Ensures the number of placeholders in SQL queries matches the provided parameters. | 🟢 | | ⚠️ | | | |
119
- | [no-batch-insert-loop](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-batch-insert-loop?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-400 | | | Prevents INSERT/UPDATE/DELETE queries inside loops (N+1 query anti-pattern). | 🟢 | | ⚠️ | | | |
120
- | [no-floating-query](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-floating-query?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-252 | | | Ensures query promises are awaited or handled. | 🟢 | 💼 | | | | |
121
- | [no-hardcoded-credentials](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-hardcoded-credentials?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-798 | | | Prevents hardcoded passwords and connection strings in PostgreSQL client initialization. | 🟢 | 💼 | | | | |
122
- | [no-insecure-ssl](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-insecure-ssl?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-295 | | | Prevents disabling SSL certificate validation in PostgreSQL connections. | 🟢 | 💼 | | | | |
123
- | [no-missing-client-release](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-missing-client-release?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-772 | | | Ensures acquired pool clients are released back to the pool. | 🟢 | 💼 | | | | |
124
- | [no-select-all](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-select-all?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-693 | | | Discourages SELECT in favor of explicit column lists. | 🟢 | | ⚠️ | | | |
125
- | [no-transaction-on-pool](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-transaction-on-pool?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-362 | | | Prevents running transaction commands directly on pool (must use dedicated client). | 🟢 | 💼 | | | | |
126
- | [no-unsafe-copy-from](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-unsafe-copy-from?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-73 | A03:2021 | | Prevents COPY FROM with file paths (should use STDIN for safe client-side data loading). | 🟢 | 💼 | | | | |
127
- | [no-unsafe-query](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-unsafe-query?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-89 | | | SQL injection is one of the most critical security vulnerabilities | 🟢 | 💼 | | | | |
128
- | [no-unsafe-search-path](https://eslint.interlace.tools/docs/security/plugin-pg/rules/no-unsafe-search-path?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-426 | | | Prevents dynamic SET searchpath queries that could enable schema hijacking. | 🟢 | 💼 | | | | |
129
- | [prefer-pool-query](https://eslint.interlace.tools/docs/security/plugin-pg/rules/prefer-pool-query?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-693 | | | Suggests using pool.query() for single-shot queries instead of manual connect/release. | 🟢 | | ⚠️ | | | |
130
- | [prevent-double-release](https://eslint.interlace.tools/docs/security/plugin-pg/rules/prevent-double-release?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-415 | | | Prevents calling client.release() multiple times on the same client. | 🟢 | 💼 | | | | |
158
+ | [check-query-params](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/check-query-params?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-89 | | | Ensures the number of placeholders in SQL queries matches the provided parameters. | 🟢 | | ⚠️ | | | |
159
+ | [no-batch-insert-loop](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-batch-insert-loop?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-400 | | | Prevents INSERT/UPDATE/DELETE queries inside loops (N+1 query anti-pattern). | 🟢 | | ⚠️ | | | |
160
+ | [no-floating-query](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-floating-query?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-252 | | | Ensures query promises are awaited or handled. | 🟢 | 💼 | | | | |
161
+ | [no-hardcoded-credentials](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-hardcoded-credentials?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-798 | | | Prevents hardcoded passwords and connection strings in PostgreSQL client initialization. | 🟢 | 💼 | | | | |
162
+ | [no-insecure-ssl](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-insecure-ssl?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-295 | | | Prevents disabling SSL certificate validation in PostgreSQL connections. | 🟢 | 💼 | | | | |
163
+ | [no-missing-client-release](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-missing-client-release?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-772 | | | Ensures acquired pool clients are released back to the pool. | 🟢 | 💼 | | | | |
164
+ | [no-select-all](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-select-all?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-693 | | | Discourages SELECT in favor of explicit column lists. | 🟢 | | ⚠️ | | | |
165
+ | [no-transaction-on-pool](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-transaction-on-pool?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-362 | | | Prevents running transaction commands directly on pool (must use dedicated client). | 🟢 | 💼 | | | | |
166
+ | [no-unsafe-copy-from](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-unsafe-copy-from?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-73 | A03:2021 | | Prevents COPY FROM with file paths (should use STDIN for safe client-side data loading). | 🟢 | 💼 | | | | |
167
+ | [no-unsafe-query](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-unsafe-query?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-89 | | | SQL injection is one of the most critical security vulnerabilities | 🟢 | 💼 | | | | |
168
+ | [no-unsafe-search-path](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/no-unsafe-search-path?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-426 | | | Prevents dynamic SET searchpath queries that could enable schema hijacking. | 🟢 | 💼 | | | | |
169
+ | [prefer-pool-query](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/prefer-pool-query?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-693 | | | Suggests using pool.query() for single-shot queries instead of manual connect/release. | 🟢 | | ⚠️ | | | |
170
+ | [prevent-double-release](https://eslint.interlace.tools/docs/security/plugin-postgresql-security/rules/prevent-double-release?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-postgresql-security) | CWE-415 | | | Prevents calling client.release() multiple times on the same client. | 🟢 | 💼 | | | | |
131
171
  <!-- AUTO-GENERATED:RULES_TABLE:END -->
132
172
  ## 🔗 Related ESLint Plugins
133
173
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-postgresql-security",
3
- "version": "2.1.0",
3
+ "version": "2.2.1",
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.12.0"
79
+ "@interlace/eslint-devkit": "^1.17.2"
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;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}};exports.plugin={meta:{name:"eslint-plugin-postgresql-security",version:"2.1.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":"error","postgresql-security/no-floating-query":"error","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
+ "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.2.1"},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":"error","postgresql-security/no-floating-query":"error","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 SINGLE_QUOTE_REGEX=/'(?:[^']|'')*'/g;const DOUBLE_QUOTE_REGEX=/"(?:[^"]|"")*"/g;const LINE_COMMENT_REGEX=/--.*/g;const BLOCK_COMMENT_REGEX=/\/\*[\s\S]*?\*\//g;const PARAM_REGEX=/\$\d+/g;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.",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.fileUsesPostgres)(context.sourceCode.ast))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 args=node.arguments;if(args.length<2)return;const queryArg=args[0];const valuesArg=args[1];if(queryArg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof queryArg.value!=="string"){return}if(valuesArg.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return}const queryText=queryArg.value;const cleanText=queryText.replace(SINGLE_QUOTE_REGEX,"").replace(DOUBLE_QUOTE_REGEX,"").replace(LINE_COMMENT_REGEX,"").replace(BLOCK_COMMENT_REGEX,"");const matches=cleanText.match(PARAM_REGEX);let maxParamIndex=0;if(matches){const indices=matches.map(m=>parseInt(m.substring(1),10));maxParamIndex=Math.max(0,...indices)}const providedArgCount=valuesArg.elements.length;if(providedArgCount<maxParamIndex){context.report({node:valuesArg,messageId:"parameterCountMismatch",data:{expected:maxParamIndex.toString(),actual:providedArgCount.toString()}})}}}}};
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_SINK_METHODS=new Set(["query","execute"]);const NON_PLACEHOLDER_TEXT=/'(?:[^']|'')*'|"(?:[^"]|"")*"|--[^\n]*|\/\*[\s\S]*?\*\/|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$/g;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.computed&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.property.name==="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;return node.quasis[0].value.cooked}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=text.replace(NON_PLACEHOLDER_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 propertyName(property){if(property.computed){return property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null}if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return property.key.name;if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"){return property.key.value}return null}function 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=propertyName(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.",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.fileUsesPostgres)(context.sourceCode.ast))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");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.fileUsesPostgres)(context.sourceCode.ast))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 args=node.arguments;if(args.length>0&&args[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof args[0].value==="string"){const query=args[0].value.toUpperCase();if(!query.includes("INSERT")&&!query.includes("UPDATE")){return}}let ancestor=node.parent;while(ancestor){if(ancestor.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||ancestor.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||ancestor.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||ancestor.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||ancestor.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement){context.report({node,messageId:"noBatchInsertLoop"});break}if(ancestor.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||ancestor.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(ancestor.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&ancestor.parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&ancestor.parent.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["map","forEach","reduce","filter"].includes(ancestor.parent.callee.property.name)){context.report({node,messageId:"noBatchInsertLoop"});break}if(ancestor.parent?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){break}}ancestor=ancestor.parent}}}}};
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 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 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){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(method!=="iife"&&!TRANSPARENT_METHODS.has(method))return null}return null}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 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)}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.fileUsesPostgres)(context.sourceCode.ast))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 iteration=iterationContext(node);if(iteration===null)return;const[queryArg]=node.arguments;if(queryArg!==void 0&&isPagination(statementText(queryArg),iteration))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");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.fileUsesPostgres)(context.sourceCode.ast))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 parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement){context.report({node,messageId:"noFloatingQuery"})}}}}};
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 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.fileUsesPostgres)(context.sourceCode.ast))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{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");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.fileUsesPostgres)(context.sourceCode.ast))return{};return{NewExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!["Client","Pool"].includes(node.callee.name)){return}if(node.arguments.length===0)return;const configArg=node.arguments[0];if(configArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof configArg.value==="string"){if(constants_1.PG_PROTOCOLS.some(protocol=>configArg.value.includes(protocol))){context.report({node:configArg,messageId:"noHardcodedCredentials"});return}}if(configArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of configArg.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property||prop.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}if(prop.key.name==="password"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal){context.report({node:prop.value,messageId:"noHardcodedCredentials"})}continue}if(prop.key.name==="connectionString"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal){context.report({node:prop.value,messageId:"noHardcodedCredentials"})}}}}}}}};
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 PG_MODULE_SET=new Set(utils_1.PG_MODULES);function isPgClientConstructor(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"||exported==="Client"}function effectiveValue(node,scope,depth=0){if(depth>4)return node;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return effectiveValue(bare,scope,depth+1);if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;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 node;const def=variable.defs.find(d=>d.type==="Variable");const init=def===void 0?null:def.node.init;return init==null?node:effectiveValue(init,scope,depth+1)}return node}function propertyKeyName(prop){if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}function property(object,name){return object.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&propertyKeyName(prop)===name)}function stringValue(node,scope){const value=effectiveValue(node,scope);return value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"?value.value:null}function dsnPassword(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.password}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.fileUsesPostgres)(context.sourceCode.ast))return{};return{NewExpression(node){const scope=context.sourceCode.getScope(node);if(!isPgClientConstructor(node.callee,scope))return;const[firstArgument]=node.arguments;if(firstArgument===void 0)return;const config=effectiveValue(firstArgument,scope);if(config.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof config.value==="string"){if(dsnPassword(config.value)!==null){context.report({node:firstArgument,messageId:"noHardcodedCredentials"})}return}if(config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const connectionString=property(config,"connectionString");if(connectionString!==void 0){const dsn=stringValue(connectionString.value,scope);if(dsn!==null&&dsnPassword(dsn)!==null){context.report({node:connectionString.value,messageId:"noHardcodedCredentials"})}}const password=property(config,"password");if(password!==void 0){const secret=stringValue(password.value,scope);if(secret!==null&&secret!==""){context.report({node:password.value,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");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.fileUsesPostgres)(context.sourceCode.ast))return{};return{NewExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.name!=="Client"&&node.callee.name!=="Pool"){return}const configArg=node.arguments[0];if(!configArg||configArg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return}const sslProp=configArg.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="ssl");if(!sslProp)return;if(sslProp.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const rejectUnauthorized=sslProp.value.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="rejectUnauthorized");if(rejectUnauthorized&&rejectUnauthorized.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&rejectUnauthorized.value.value===false){context.report({node:rejectUnauthorized,messageId:"noInsecureSsl"})}}}}}};
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 PG_MODULE_SET=new Set(utils_1.PG_MODULES);function isPgClientConstructor(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"||exported==="Client"}function effectiveValue(node,scope,depth=0){if(depth>4)return node;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return effectiveValue(bare,scope,depth+1);if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;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 node;const def=variable.defs.find(d=>d.type==="Variable");const init=def===void 0?null:def.node.init;return init==null?node:effectiveValue(init,scope,depth+1)}return node}function propertyKeyName(prop){if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed){return prop.key.name}if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}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(node,scope){const value=effectiveValue(node,scope);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.fileUsesPostgres)(context.sourceCode.ast))return{};return{NewExpression(node){const scope=context.sourceCode.getScope(node);if(!isPgClientConstructor(node.callee,scope))return;const[firstArgument]=node.arguments;if(firstArgument===void 0)return;const config=effectiveValue(firstArgument,scope);if(config.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof config.value==="string"){if(dsnSkipsVerification(config.value)){context.report({node:firstArgument,messageId:"noInsecureSsl"})}return}if(config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const connectionString=property(config,"connectionString");if(connectionString!==void 0){const dsn=effectiveValue(connectionString.value,scope);if(dsn.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof dsn.value==="string"&&dsnSkipsVerification(dsn.value)){context.report({node:connectionString.value,messageId:"noInsecureSsl"});return}}const ssl=property(config,"ssl");if(ssl===void 0)return;const sslValue=effectiveValue(ssl.value,scope);if(sslValue.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const rejectUnauthorized=property(sslValue,"rejectUnauthorized");if(rejectUnauthorized===void 0)return;if(disablesVerification(rejectUnauthorized.value,scope)){context.report({node:rejectUnauthorized,messageId:"noInsecureSsl"})}}}}};
@@ -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");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"},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:"A05: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"})},schema:[]},defaultOptions:[],create(context){if(!(0,utils_1.fileUsesPostgres)(context.sourceCode.ast))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!=="connect"){return}let currentNode=node;if(node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){currentNode=node.parent}if(currentNode.parent?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return}const declarator=currentNode.parent;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return}const variable=context.sourceCode.getDeclaredVariables(declarator)[0];if(!variable)return;const references=variable.references;const hasReleaseCall=references.some(ref=>{const id=ref.identifier;return id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&id.parent.object===id&&id.parent.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&id.parent.property.name==="release"&&id.parent.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression});if(!hasReleaseCall){context.report({node:declarator,messageId:"missingClientRelease"})}}}}};
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 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&&!receiver.computed&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return poolProperties.has(receiver.property.name)}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||member.computed||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||member.property.name!=="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&&current.parent.finalizer===current){return true}}return false}function transfersOwnership(identifier){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 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"},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:"A05: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:"A05: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.fileUsesPostgres)(context.sourceCode.ast))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||node.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.property.name!=="connect"){return}if(!isPgPool(node.callee.object,context.sourceCode.getScope(node),poolProperties)){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));if(uses.some(id=>transfersOwnership(id)))return;const releases=uses.filter(id=>isReleaseCall(id));if(releases.length===0){context.report({node:declarator,messageId:"missingClientRelease"});return}if(!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 COUNT_STAR_REGEX=/COUNT\s*\(\s*\*\s*\)/g;const SELECT_STAR_REGEX=/\bSELECT\s+\*/;const COMMA_STAR_REGEX=/,\s*\*/;const SELECT_KEYWORD_REGEX=/\bSELECT\b/;const UNNEST_PATTERN_REGEX=/\bSELECT\s+\*\s+FROM\s+UNNEST\s*\(/;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.fileUsesPostgres)(context.sourceCode.ast))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 args=node.arguments;if(args.length===0)return;const queryArg=args[0];if(queryArg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof queryArg.value!=="string"){return}const queryText=queryArg.value;const upperQuery=queryText.toUpperCase();const cleanedQuery=upperQuery.replace(COUNT_STAR_REGEX,"COUNT_ALL");if(SELECT_STAR_REGEX.test(cleanedQuery)||COMMA_STAR_REGEX.test(cleanedQuery)){if(SELECT_KEYWORD_REGEX.test(cleanedQuery)){if(UNNEST_PATTERN_REGEX.test(cleanedQuery)){return}context.report({node:queryArg,messageId:"noSelectAll"})}}}}}};
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}function selectsEveryColumn(sql){const cleaned=stripSqlNoise(sql).replace(EXISTS_STAR,"EXISTS ( SELECT 1").replace(SELECT_STAR_FROM_FUNCTION,"SELECT 1 FROM f(");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.fileUsesPostgres)(context.sourceCode.ast))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 TRANSACTION_KEYWORDS=new Set(["BEGIN","COMMIT","ROLLBACK"]);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.fileUsesPostgres)(context.sourceCode.ast))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 args=node.arguments;if(args.length===0)return;const queryArg=args[0];if(queryArg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof queryArg.value!=="string"){return}const queryText=queryArg.value.toUpperCase().trim();const firstWord=queryText.split(/[;\s]/)[0];if(TRANSACTION_KEYWORDS.has(firstWord)){if(node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(node.callee.object.name==="pool"||node.callee.object.name.toLowerCase().includes("pool"))){context.report({node:queryArg,messageId:"noTransactionOnPool"})}}}}}};
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 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){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value.trim()}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length===0){return node.quasis.map(q=>q.value.cooked).join("").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))}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.fileUsesPostgres)(context.sourceCode.ast))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&&!receiver.computed&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return poolProperties.has(receiver.property.name)}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){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||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=statementText(queryArg);if(text===null||!isTransactionStatement(text))return;if(isPool(node.callee.object,context.sourceCode.getScope(node))){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 COPY_FROM_REGEX=/\bCOPY\b.*\bFROM\b/i;const STDIN_REGEX=/\bFROM\s+STDIN\b/i;const FILE_PATH_REGEX=/FROM\s+['"]([^'"]+)['"]/i;const hasCopyFrom=str=>COPY_FROM_REGEX.test(str)&&!STDIN_REGEX.test(str);const extractFilePath=str=>{const match=FILE_PATH_REGEX.exec(str);return match?match[1]:null};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"}),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.fileUsesPostgres)(context.sourceCode.ast))return{};const options=context.options[0]??{};const allowHardcodedPaths=options.allowHardcodedPaths??false;const allowedPaths=(options.allowedPaths??[]).map(p=>new RegExp(p));const isPathAllowed=filePath=>{return 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||node.callee.property.name!=="query"){return}const args=node.arguments;if(args.length===0)return;const queryArg=args[0];if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof queryArg.value==="string"){if(hasCopyFrom(queryArg.value)){const filePath=extractFilePath(queryArg.value);if(filePath&&isPathAllowed(filePath)){return}if(allowHardcodedPaths){return}context.report({node:queryArg,messageId:"hardcodedPath"})}return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const staticText=queryArg.quasis.map(q=>q.value.raw).join(" ");if(hasCopyFrom(staticText)){if(queryArg.expressions.length>0){context.report({node:queryArg,messageId:"dynamicPath"})}else{const filePath=extractFilePath(staticText);if(filePath&&isPathAllowed(filePath)){return}if(!allowHardcodedPaths){context.report({node:queryArg,messageId:"hardcodedPath"})}}}return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const parts=[];let hasDynamicPart=false;const stack=[queryArg];for(let curr=stack.pop();curr!==void 0;curr=stack.pop()){if(curr.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&curr.operator==="+"){stack.push(curr.right);stack.push(curr.left)}else if(curr.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof curr.value==="string"){parts.push(curr.value)}else{hasDynamicPart=true}}const staticText=parts.join(" ");if(hasCopyFrom(staticText)){if(hasDynamicPart){context.report({node:queryArg,messageId:"dynamicPath"})}else{const filePath=extractFilePath(staticText);if(filePath&&isPathAllowed(filePath)){return}if(!allowHardcodedPaths){context.report({node:queryArg,messageId:"hardcodedPath"})}}}return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier||queryArg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return}}}}};
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_SINK_METHODS=new Set(["query","execute"]);const SQL_COMMENTS=/--[^\n]*|\/\*[\s\S]*?\*\//g;const QUOTED_SOURCE=/from\s+['"]([^'"]+)['"]/i;const FROM_STDIN=/^\s*stdin\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).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function copySourceClause(text){const stripped=text.replace(SQL_COMMENTS,"");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||direction[1].toLowerCase()!=="from")continue;return statement.slice(index+direction.index+direction[1].length)}return null}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||body.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof body.value==="string"?body:null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!tag.computed&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.property.name==="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"}),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.fileUsesPostgres)(context.sourceCode.ast))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 source=copySourceClause(staticText(expression));if(source===null)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");function isUnsafeStringConstruction(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return"concat"}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){return"template"}return false}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){if(!(0,utils_1.fileUsesPostgres)(context.sourceCode.ast))return{};const taintedVariables=new Map;return{VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.init){const unsafe=isUnsafeStringConstruction(node.init);if(unsafe){taintedVariables.set(node.id.name,unsafe)}}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const unsafe=isUnsafeStringConstruction(node.right);if(unsafe){taintedVariables.set(node.left.name,unsafe)}}},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 args=node.arguments;if(args.length===0)return;const queryArg=args[0];if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&queryArg.operator==="+"){context.report({node:queryArg,messageId:"noUnsafeQuery"});return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&queryArg.expressions.length>0){context.report({node:queryArg,messageId:"unsafeTemplateLiteral"});return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const taint=taintedVariables.get(queryArg.name);if(taint){context.report({node:queryArg,messageId:taint==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})}}}}}};
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"]);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]*\bfrom\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];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)}`}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function looksLikeSqlStatement(text){return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function hasRawPart(node,scope){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawPart(part,scope)}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}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 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.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return node;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return node;const def=variable.defs.find(d=>d.type==="Variable");const init=def===void 0?null:def.node.init;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[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?body:null}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){if(!(0,utils_1.fileUsesPostgres)(context.sourceCode.ast))return{};const fragments=new Map;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||node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string";const reportIfUnsafe=(reportNode,parts,scope)=>{let kind=null;let raw=false;let text="";for(const part of parts){text+=staticText(part);if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&part.operator==="+"){kind="concat";if(hasRawPart(part,scope))raw=true}else if(part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&part.expressions.length>0){kind="template";if(hasRawPart(part,scope))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(node.id.name,[node.init])}},AssignmentExpression(node){if(node.operator!=="+="||node.left.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return}const existing=fragments.get(node.left.name);if(existing===void 0){fragments.set(node.left.name,[node.right]);return}existing.push(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=context.sourceCode.getScope(node);const expression=effectiveExpression(queryArg,scope);if(isBuilt(expression)){reportIfUnsafe(queryArg,[expression],scope);return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const parts=fragments.get(queryArg.name);if(parts!==void 0)reportIfUnsafe(queryArg,parts,scope)}}}}};
@@ -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 hasSearchPath=str=>str.toLowerCase().includes("set search_path");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.fileUsesPostgres)(context.sourceCode.ast))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 args=node.arguments;if(args.length===0)return;const queryArg=args[0];if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&queryArg.operator==="+"){}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal){if(typeof queryArg.value==="string"&&hasSearchPath(queryArg.value)){return}}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const rawText=queryArg.quasis.map(q=>q.value.raw).join(" ");if(hasSearchPath(rawText)){if(queryArg.expressions.length>0){context.report({node:queryArg,messageId:"noUnsafeSearchPath"})}}return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const parts=[];const stack=[queryArg];for(let curr=stack.pop();curr!==void 0;curr=stack.pop()){if(curr.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&curr.operator==="+"){stack.push(curr.right);stack.push(curr.left)}else if(curr.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof curr.value==="string"){parts.push(curr.value)}}const combined=parts.join(" ");if(hasSearchPath(combined)){context.report({node:queryArg,messageId:"noUnsafeSearchPath"})}return}if(queryArg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(queryArg.arguments.length>0&&queryArg.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof queryArg.arguments[0].value==="string"&&hasSearchPath(queryArg.arguments[0].value)){const allLiterals=queryArg.arguments.every(arg=>arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal);if(allLiterals)return;context.report({node:queryArg,messageId:"noUnsafeSearchPath"})}}}}}};
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 SQL_SINK_METHODS=new Set(["query","execute"]);const SEARCH_PATH_STATEMENT=/^\s*set\s+(?:local\s+|session\s+)?search_path\b/i;const SQL_COMMENTS=/--[^\n]*|\/\*[\s\S]*?\*\//g;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).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function setsSearchPath(text){return text.replace(SQL_COMMENTS,"").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||body.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof body.value==="string"?body:null}function isStringRawTag(node){const{tag}=node;return tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!tag.computed&&tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.object.name==="String"&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&tag.property.name==="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 isAllowlistGuarded(variable,sink){return variable.references.some(ref=>{for(let current=ref.identifier;current!==void 0&&current!==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.fileUsesPostgres)(context.sourceCode.ast))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 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"})}}}};
@@ -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");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"},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.fileUsesPostgres)(context.sourceCode.ast))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)[0];if(!variable)return;const references=variable.references;let queryCallCount=0;let releaseCallCount=0;let otherUsageCount=0;for(const ref of references){if(ref.isWrite())continue;const id=ref.identifier;if(id.parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&id.parent.object===id&&id.parent.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const method=id.parent.property.name;if(method==="query"){queryCallCount++;if(id.parent.parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const call=id.parent.parent;if(call.arguments.length>0&&call.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof call.arguments[0].value==="string"){const q=call.arguments[0].value.toUpperCase().trim();if(q.startsWith("BEGIN")||q.startsWith("COMMIT")||q.startsWith("ROLLBACK")){return}}}}else if(method==="release"){releaseCallCount++}else{otherUsageCount++}}else{otherUsageCount++}}if(queryCallCount===1&&releaseCallCount===1&&otherUsageCount===0){context.report({node,messageId:"preferPoolQuery"})}}}}};
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"},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.fileUsesPostgres)(context.sourceCode.ast))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 isGuardedByCondition(node){const ifStmt=findAncestor(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement);if(!ifStmt)return false;const conditionText=ifStmt.test;if(conditionText.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&conditionText.operator==="!"){const arg=conditionText.argument;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=arg.name.toLowerCase();return name.includes("released")||name.includes("done")||name.includes("closed")}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&arg.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=arg.property.name.toLowerCase();return name.includes("released")||name.includes("done")||name.includes("closed")}}return false}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}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{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&&id.parent.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&id.parent.property.name==="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){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){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&&current.operator==="="&&current.right.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&current.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&&!left.computed&&left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.property.name===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}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.slice(0,-1).every(c=>terminated(c)))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&&id.parent.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&id.parent.property.name==="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===void 0||loop===null)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){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}}}}}}}}}}};