loadwise 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -5,6 +5,7 @@ import { ts } from '../performance/engine/compiler.js';
5
5
  import { calleeName } from '../performance/analysis/call-syntax.js';
6
6
  import { walkNodes } from './walk.js';
7
7
  import { isIgnoredSource } from './source-helpers.js';
8
+ import { checkIntervals, enclosingFunction, isIntervalCall } from './resource-leak-intervals.js';
8
9
  const typeormPackage = /[\\/]node_modules[\\/]typeorm[\\/]/;
9
10
  const noMethods = new Set();
10
11
  const fileHandleMessage = {
@@ -22,50 +23,41 @@ const browserMessage = {
22
23
  consequence: 'its browser process keeps running',
23
24
  remedy: 'Close it in a finally block.',
24
25
  };
26
+ const pgPoolPackages = /[\\/]node_modules[\\/](?:@types[\\/])?(?:pg|pg-pool)[\\/]/;
27
+ const mysqlPromisePoolPackage = /[\\/]node_modules[\\/]mysql2[\\/]promise\.d\.[cm]?ts$/;
28
+ const pgPoolRelease = new Set(['release']);
29
+ const mysqlPoolRelease = new Set(['release', 'destroy']);
30
+ function poolReleaseMethods(call, checker) {
31
+ const method = calleeName(call);
32
+ if (call.arguments.length !== 0 || (method !== 'connect' && method !== 'getConnection'))
33
+ return;
34
+ const declaration = checker.getResolvedSignature(call)?.declaration;
35
+ if (!declaration)
36
+ return;
37
+ const owner = declaration.parent;
38
+ if (!ts.isClassLike(owner) && !ts.isInterfaceDeclaration(owner))
39
+ return;
40
+ const file = declaration.getSourceFile().fileName;
41
+ if (method === 'connect' && owner.name?.text === 'Pool' && pgPoolPackages.test(file))
42
+ return pgPoolRelease;
43
+ if (method === 'getConnection' && owner.name?.text === 'Pool' && mysqlPromisePoolPackage.test(file))
44
+ return mysqlPoolRelease;
45
+ }
46
+ function poolAcquisition(declaration, releaseMethods) {
47
+ return {
48
+ ruleId: 'db-pool-client-not-released',
49
+ declaration,
50
+ releaseMethods,
51
+ handoffMethods: noMethods,
52
+ what: 'a checked-out database connection',
53
+ consequence: 'the checkout stays occupied and the pool can run out of connections',
54
+ remedy: 'Call `release()` in a finally block, or transfer ownership to a caller that releases the connection.',
55
+ };
56
+ }
25
57
  const playwrightModules = new Set(['playwright', 'playwright-core']);
26
58
  const puppeteerModules = new Set(['puppeteer', 'puppeteer-core']);
27
59
  const playwrightEngines = new Set(['chromium', 'firefox', 'webkit']);
28
60
  const playwrightLaunchers = new Set(['launch', 'launchPersistentContext']);
29
- const frontendFramework = /^(?:react|preact|vue|@vue\/.+|svelte|solid-js|@angular\/core)$/;
30
- const frontendLifecycleCallbacks = new Set([
31
- 'useEffect',
32
- 'useLayoutEffect',
33
- 'useInsertionEffect',
34
- 'onMounted',
35
- 'onBeforeMount',
36
- 'onUpdated',
37
- 'onActivated',
38
- 'watch',
39
- 'watchEffect',
40
- 'watchPostEffect',
41
- ]);
42
- const frontendLifecycleMethods = new Set([
43
- 'setup',
44
- 'mounted',
45
- 'created',
46
- 'beforeMount',
47
- 'componentDidMount',
48
- 'componentDidUpdate',
49
- 'ngOnInit',
50
- 'ngOnChanges',
51
- 'ngAfterViewInit',
52
- 'ngAfterContentInit',
53
- ]);
54
- const startupFunctionNames = new Set(['main', 'bootstrap']);
55
- // A background timer started here is the singleton timer of the service, not one per call.
56
- const singletonInitializerNames = new Set([
57
- 'onModuleInit',
58
- 'onApplicationBootstrap',
59
- 'init',
60
- 'initialize',
61
- 'start',
62
- 'setup',
63
- 'register',
64
- 'listen',
65
- ]);
66
- // A callback of these runs once when the program starts, like top-level code.
67
- const startupCallbackOwners = new Set(['listen', 'once', 'then', 'whenReady', 'ready']);
68
- const reactHookName = /^use[A-Z]/;
69
61
  const comparisonOperators = new Set([
70
62
  ts.SyntaxKind.EqualsEqualsToken,
71
63
  ts.SyntaxKind.EqualsEqualsEqualsToken,
@@ -74,7 +66,7 @@ const comparisonOperators = new Set([
74
66
  ]);
75
67
  // The only calls an acquisition rule starts from (`fs.open`, `launch`, `connect`, `createQueryRunner`), so a file
76
68
  // without these words has nothing to check.
77
- const acquisitionWords = /open|launch|connect|createQueryRunner/;
69
+ const acquisitionWords = /open|launch|connect|getConnection|createQueryRunner/;
78
70
  function withoutNodePrefix(moduleName) {
79
71
  return moduleName.startsWith('node:') ? moduleName.slice('node:'.length) : moduleName;
80
72
  }
@@ -176,8 +168,25 @@ function createsTypeormQueryRunner(call, checker) {
176
168
  const declaration = checker.getResolvedSignature(call)?.declaration;
177
169
  return declaration !== undefined && typeormPackage.test(declaration.getSourceFile().fileName);
178
170
  }
171
+ function isRuntimeImport(statement) {
172
+ const clause = statement.importClause;
173
+ if (!clause)
174
+ return true;
175
+ if (clause.isTypeOnly)
176
+ return false;
177
+ if (clause.name)
178
+ return true;
179
+ const bindings = clause.namedBindings;
180
+ if (!bindings)
181
+ return false;
182
+ if (ts.isNamespaceImport(bindings))
183
+ return true;
184
+ // An empty `import {}` is kept at runtime under verbatimModuleSyntax.
185
+ return bindings.elements.length === 0 || bindings.elements.some((element) => !element.isTypeOnly);
186
+ }
179
187
  function importsModule(sourceFile, matches) {
180
188
  return sourceFile.statements.some((statement) => ts.isImportDeclaration(statement) &&
189
+ isRuntimeImport(statement) &&
181
190
  ts.isStringLiteralLike(statement.moduleSpecifier) &&
182
191
  matches(statement.moduleSpecifier.text));
183
192
  }
@@ -189,6 +198,9 @@ function acquisitionOf(declaration, checker, isPlaywrightTestFile) {
189
198
  const call = ts.skipOuterExpressions(initializer.expression);
190
199
  if (!ts.isCallExpression(call))
191
200
  return;
201
+ const releasesPoolCheckout = poolReleaseMethods(call, checker);
202
+ if (releasesPoolCheckout)
203
+ return poolAcquisition(declaration, releasesPoolCheckout);
192
204
  const reference = importedReference(call.expression, checker);
193
205
  if (!reference)
194
206
  return;
@@ -296,6 +308,60 @@ const releaseKindByPlacement = {
296
308
  catch: 'release-in-catch',
297
309
  plain: 'release-elsewhere',
298
310
  };
311
+ // A stream kept in a local binding may be returned or passed on later, so its ownership stays manual.
312
+ function isBoundToVariable(call) {
313
+ let node = call;
314
+ while (ts.isParenthesizedExpression(node.parent) || ts.isNonNullExpression(node.parent))
315
+ node = node.parent;
316
+ return ts.isVariableDeclaration(node.parent) && node.parent.initializer === node;
317
+ }
318
+ function autoCloseOfValue(initializer) {
319
+ const { kind } = ts.skipOuterExpressions(initializer);
320
+ if (kind === ts.SyntaxKind.TrueKeyword)
321
+ return 'true';
322
+ if (kind === ts.SyntaxKind.FalseKeyword)
323
+ return 'false';
324
+ return 'unknown';
325
+ }
326
+ // What one object-literal member does to the running `autoClose` setting.
327
+ function autoCloseAfter(setting, prop) {
328
+ if (ts.isSpreadAssignment(prop))
329
+ return 'unknown';
330
+ if (!ts.isShorthandPropertyAssignment(prop) && !ts.isPropertyAssignment(prop))
331
+ return setting;
332
+ if (ts.isComputedPropertyName(prop.name))
333
+ return 'unknown';
334
+ if (!ts.isIdentifier(prop.name) && !ts.isStringLiteralLike(prop.name))
335
+ return setting;
336
+ if (prop.name.text !== 'autoClose')
337
+ return setting;
338
+ return ts.isPropertyAssignment(prop) ? autoCloseOfValue(prop.initializer) : 'unknown';
339
+ }
340
+ // The effective `autoClose` option, read in evaluation order so a later spread or computed value is 'unknown'.
341
+ function autoCloseSetting(call) {
342
+ if (!call.arguments[0])
343
+ return 'omitted';
344
+ const options = ts.skipOuterExpressions(call.arguments[0]);
345
+ if (!ts.isObjectLiteralExpression(options))
346
+ return 'unknown';
347
+ return options.properties.reduce(autoCloseAfter, 'omitted');
348
+ }
349
+ const streamOpeningMethods = new Set([
350
+ 'readableWebStream',
351
+ 'createReadStream',
352
+ 'createWriteStream',
353
+ ]);
354
+ // A stream opener hands ownership on unless the call keeps autoClose off (or, for readableWebStream, leaves it at its default).
355
+ function streamOpenerKind(method, call, access) {
356
+ if (!ts.isCallExpression(call) || call.expression !== access)
357
+ return 'handoff';
358
+ if (ts.findAncestor(call, ts.isReturnStatement) || isBoundToVariable(call))
359
+ return 'handoff';
360
+ const autoClose = autoCloseSetting(call);
361
+ if (method === 'readableWebStream' && autoClose === 'omitted')
362
+ return 'use';
363
+ return autoClose === 'false' ? 'use' : 'handoff';
364
+ }
299
365
  function referenceKind(reference, container, releaseMethods, handoffMethods) {
300
366
  if (insideNestedFunction(reference, container))
301
367
  return 'handoff';
@@ -307,7 +373,7 @@ function referenceKind(reference, container, releaseMethods, handoffMethods) {
307
373
  return inspectsOnly(node) ? 'use' : 'handoff';
308
374
  const method = access.name.text;
309
375
  if (handoffMethods.has(method))
310
- return 'handoff';
376
+ return streamOpeningMethods.has(method) ? streamOpenerKind(method, access.parent, access) : 'handoff';
311
377
  if (!releaseMethods.has(method))
312
378
  return 'use';
313
379
  const call = access.parent;
@@ -316,6 +382,85 @@ function referenceKind(reference, container, releaseMethods, handoffMethods) {
316
382
  const placement = releasePlacement(call, container);
317
383
  return placement === 'function' ? 'handoff' : releaseKindByPlacement[placement];
318
384
  }
385
+ function isCaughtThrow(node, container) {
386
+ for (let child = node, parent = node.parent; parent && parent !== container; child = parent, parent = parent.parent) {
387
+ if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause)
388
+ return true;
389
+ }
390
+ return false;
391
+ }
392
+ function releaseStatements(references, kinds) {
393
+ return references.flatMap((reference, index) => {
394
+ if (kinds[index] !== 'release-elsewhere')
395
+ return [];
396
+ const access = outermostWrapper(reference).parent;
397
+ const call = access.parent;
398
+ const expression = ts.isAwaitExpression(call.parent) ? call.parent : call;
399
+ return ts.isExpressionStatement(expression.parent) ? [expression.parent] : [];
400
+ });
401
+ }
402
+ function releasedBeforeExit(exit, cleanup, container) {
403
+ for (let child = exit; child !== container && child.parent; child = child.parent) {
404
+ if (!ts.isBlock(child.parent))
405
+ continue;
406
+ if (cleanup.some((release) => release.parent === child.parent && release.end <= child.getStart()))
407
+ return true;
408
+ }
409
+ return false;
410
+ }
411
+ // An exit in the other branch of an if that holds the acquisition runs only when no checkout happened.
412
+ function inSiblingBranch(exit, statement) {
413
+ for (let child = exit, parent = exit.parent; parent; child = parent, parent = parent.parent) {
414
+ if (!ts.isIfStatement(parent))
415
+ continue;
416
+ const { thenStatement, elseStatement } = parent;
417
+ const exitBranch = child === thenStatement || child === elseStatement ? child : undefined;
418
+ if (!exitBranch)
419
+ continue;
420
+ const other = exitBranch === thenStatement ? elseStatement : thenStatement;
421
+ if (other && statement.pos >= other.pos && statement.end <= other.end)
422
+ return true;
423
+ }
424
+ return false;
425
+ }
426
+ function exitsBeforeRelease(statement, release, container, alternateCleanups) {
427
+ const start = statement.end;
428
+ const end = release.getStart();
429
+ let exits = false;
430
+ walkNodes(container, (node) => {
431
+ if (exits || node.pos < start || node.end > end)
432
+ return;
433
+ const abrupt = ts.isReturnStatement(node) || (ts.isThrowStatement(node) && !isCaughtThrow(node, container));
434
+ if (abrupt &&
435
+ !insideNestedFunction(node, container) &&
436
+ !inSiblingBranch(node, statement) &&
437
+ !releasedBeforeExit(node, alternateCleanups, container))
438
+ exits = true;
439
+ });
440
+ return exits;
441
+ }
442
+ function cleanupScope(release, container) {
443
+ let protection = release;
444
+ for (let child = release, parent = child.parent; parent && parent !== container; child = parent, parent = parent.parent) {
445
+ if (ts.isTryStatement(parent) && parent.finallyBlock === child)
446
+ protection = parent;
447
+ }
448
+ return protection;
449
+ }
450
+ function finallyCanBeSkipped(statement, references, kinds, container) {
451
+ const alternateCleanups = releaseStatements(references, kinds);
452
+ return references
453
+ .filter((_reference, position) => kinds[position] === 'release-in-finally')
454
+ .every((reference) => exitsBeforeRelease(statement, cleanupScope(reference, container), container, alternateCleanups));
455
+ }
456
+ function ownedPoolScope(statement) {
457
+ if (statement.declarationList.flags & ts.NodeFlags.BlockScoped)
458
+ return statement.parent;
459
+ const owner = enclosingFunction(statement);
460
+ if (owner && ts.isFunctionLike(owner) && 'body' in owner && owner.body && ts.isBlock(owner.body))
461
+ return owner.body;
462
+ return statement.getSourceFile();
463
+ }
319
464
  // undefined means the resource is released safely, or its ownership moved on.
320
465
  function leakState(acquisition, checker) {
321
466
  const { declaration, releaseMethods, handoffMethods } = acquisition;
@@ -323,19 +468,34 @@ function leakState(acquisition, checker) {
323
468
  if (!statement || isUsingDeclaration(declaration))
324
469
  return;
325
470
  // A module-level resource is a singleton that lives as long as the process.
326
- if (ts.isSourceFile(statement.parent))
471
+ const databasePool = acquisition.ruleId === 'db-pool-client-not-released';
472
+ const container = databasePool ? ownedPoolScope(statement) : statement.parent;
473
+ if (ts.isSourceFile(container))
474
+ return;
475
+ const references = referencesTo(declaration, container, checker);
476
+ const kinds = references.map((reference) => referenceKind(reference, container, releaseMethods, handoffMethods));
477
+ if (kinds.includes('handoff'))
327
478
  return;
328
- const kinds = referencesTo(declaration, statement.parent, checker).map((reference) => referenceKind(reference, statement.parent, releaseMethods, handoffMethods));
329
- if (kinds.includes('handoff') || kinds.includes('release-in-finally'))
479
+ if (kinds.includes('release-in-finally')) {
480
+ if (databasePool && finallyCanBeSkipped(statement, references, kinds, container))
481
+ return 'released-outside-finally';
330
482
  return;
483
+ }
331
484
  const releasedInCatch = kinds.includes('release-in-catch');
332
485
  // Closed on the success path and in a catch: every path gives it back.
333
486
  if (releasedInCatch && kinds.includes('release-elsewhere'))
334
487
  return;
335
488
  if (!releasedInCatch && !kinds.includes('release-elsewhere'))
336
489
  return 'never-released';
490
+ if (databasePool) {
491
+ const release = references[kinds.indexOf('release-elsewhere')];
492
+ if (release && exitsBeforeRelease(statement, release, container, releaseStatements(references, kinds)))
493
+ return 'released-outside-finally';
494
+ }
337
495
  // Acquired and released with nothing done in between leaves no step that could fail.
338
- return kinds.includes('use') ? 'released-outside-finally' : undefined;
496
+ const lastRelease = references[kinds.lastIndexOf('release-elsewhere')];
497
+ const usedBeforeRelease = references.some((reference, position) => kinds[position] === 'use' && (!lastRelease || reference.pos < lastRelease.pos));
498
+ return usedBeforeRelease ? 'released-outside-finally' : undefined;
339
499
  }
340
500
  function acquisitionMessage(acquisition, state) {
341
501
  const { declaration, what, consequence, remedy, releaseMethods } = acquisition;
@@ -343,160 +503,14 @@ function acquisitionMessage(acquisition, state) {
343
503
  const [release] = releaseMethods;
344
504
  if (state === 'never-released')
345
505
  return `\`${name}\` is ${what} and \`${name}.${release}()\` is never called, so ${consequence}. ${remedy}`;
506
+ if (acquisition.ruleId === 'db-pool-client-not-released')
507
+ return `An early return or error can bypass \`${name}.${release}()\`, so ${consequence}. Cover the whole checkout with a finally block.`;
346
508
  return `\`${name}.${release}()\` is not in a finally block, so an error before it leaves ${what} unreleased and ${consequence}. ${remedy}`;
347
509
  }
348
510
  function findingAt(sourceFile, file, node, ruleId, message) {
349
511
  const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
350
512
  return { file, line: position.line + 1, column: position.character + 1, ruleId, message };
351
513
  }
352
- function functionNameOf(functionNode) {
353
- if ((ts.isMethodDeclaration(functionNode) ||
354
- ts.isFunctionDeclaration(functionNode) ||
355
- ts.isFunctionExpression(functionNode)) &&
356
- functionNode.name &&
357
- ts.isIdentifier(functionNode.name))
358
- return functionNode.name.text;
359
- if (!ts.isArrowFunction(functionNode) && !ts.isFunctionExpression(functionNode))
360
- return;
361
- const owner = functionNode.parent;
362
- if ((ts.isPropertyAssignment(owner) || ts.isVariableDeclaration(owner)) && ts.isIdentifier(owner.name))
363
- return owner.name.text;
364
- }
365
- // A callback handed directly to a call, as opposed to one stored under a name.
366
- function callbackOwner(functionNode) {
367
- const call = functionNode.parent;
368
- return ts.isCallExpression(call) && call.arguments.some((argument) => argument === functionNode) ? call : undefined;
369
- }
370
- // React, Vue and Angular lifecycles are covered by the frontend cleanup rules.
371
- function insideFrontendLifecycle(node) {
372
- for (let current = node.parent; current; current = current.parent) {
373
- if (!ts.isFunctionLike(current))
374
- continue;
375
- const name = functionNameOf(current);
376
- if (name !== undefined && (frontendLifecycleMethods.has(name) || reactHookName.test(name)))
377
- return true;
378
- const owner = callbackOwner(current);
379
- const ownerName = owner && calleeName(owner);
380
- if (ownerName !== undefined && frontendLifecycleCallbacks.has(ownerName))
381
- return true;
382
- }
383
- return false;
384
- }
385
- // `main()`, an immediately invoked function or a `listen(...)` callback runs once at startup, where a
386
- // timer that lives as long as the process is intended.
387
- function isStartupFunction(functionNode) {
388
- const name = functionNameOf(functionNode);
389
- if (name !== undefined && startupFunctionNames.has(name))
390
- return true;
391
- const call = ts.isFunctionExpression(functionNode) || ts.isArrowFunction(functionNode)
392
- ? outermostWrapper(functionNode).parent
393
- : undefined;
394
- if (call && ts.isCallExpression(call) && ts.skipOuterExpressions(call.expression) === functionNode)
395
- return true;
396
- const owner = callbackOwner(functionNode);
397
- const ownerName = owner && calleeName(owner);
398
- return ownerName !== undefined && startupCallbackOwners.has(ownerName);
399
- }
400
- // A constructor or lifecycle hook runs once per instance of a singleton service, so a timer it
401
- // starts without keeping the handle is the service's background timer.
402
- function isSingletonInitializer(functionNode) {
403
- if (ts.isConstructorDeclaration(functionNode))
404
- return true;
405
- const name = functionNameOf(functionNode);
406
- return name !== undefined && singletonInitializerNames.has(name);
407
- }
408
- function enclosingFunction(node) {
409
- for (let current = node.parent; current; current = current.parent)
410
- if (ts.isFunctionLike(current))
411
- return current;
412
- }
413
- function nameOfHandle(expression) {
414
- const handle = ts.skipOuterExpressions(expression);
415
- if (ts.isIdentifier(handle))
416
- return handle.text;
417
- return ts.isPropertyAccessExpression(handle) ? handle.name.text : undefined;
418
- }
419
- function collectHandledNames(sourceFile) {
420
- const handled = { cleared: new Set(), unreferenced: new Set() };
421
- walkNodes(sourceFile, (node) => {
422
- if (!ts.isCallExpression(node))
423
- return;
424
- const callee = ts.skipOuterExpressions(node.expression);
425
- const calledName = calleeName(node);
426
- if (calledName === 'clearInterval' || calledName === 'clearTimeout') {
427
- const name = node.arguments[0] && nameOfHandle(node.arguments[0]);
428
- if (name !== undefined)
429
- handled.cleared.add(name);
430
- }
431
- else if (calledName === 'unref' && ts.isPropertyAccessExpression(callee)) {
432
- const name = nameOfHandle(callee.expression);
433
- if (name !== undefined)
434
- handled.unreferenced.add(name);
435
- }
436
- });
437
- return handled;
438
- }
439
- function isIntervalCall(call, checker) {
440
- const callee = ts.skipOuterExpressions(call.expression);
441
- if (ts.isPropertyAccessExpression(callee)) {
442
- const receiver = ts.skipOuterExpressions(callee.expression);
443
- return (callee.name.text === 'setInterval' &&
444
- ts.isIdentifier(receiver) &&
445
- ['window', 'globalThis'].includes(receiver.text));
446
- }
447
- if (!ts.isIdentifier(callee) || callee.text !== 'setInterval')
448
- return false;
449
- const origin = importedReference(callee, checker);
450
- if (origin)
451
- return origin.moduleName === 'timers' && sameMembers(origin.members, ['setInterval']);
452
- // A local function that happens to be named setInterval is not the timer.
453
- const declarations = checker.getSymbolAtLocation(callee)?.declarations ?? [];
454
- return declarations.every((declaration) => declaration.getSourceFile().isDeclarationFile);
455
- }
456
- function isDiscarded(node) {
457
- const parent = node.parent;
458
- if (ts.isExpressionStatement(parent))
459
- return true;
460
- return ts.isVoidExpression(parent) && ts.isExpressionStatement(parent.parent);
461
- }
462
- function intervalLeaks(call, checker, handled) {
463
- const node = outermostWrapper(call);
464
- const parent = node.parent;
465
- if (isDiscarded(node))
466
- return true;
467
- if (ts.isVariableDeclaration(parent) && parent.initializer === node && ts.isIdentifier(parent.name)) {
468
- const statement = declaringStatement(parent);
469
- if (!statement)
470
- return false;
471
- // Anything beyond reading a property of the handle, clearing or returning it, ends the search.
472
- return referencesTo(parent, statement.parent, checker).every((reference) => referenceKind(reference, statement.parent, noMethods, new Set(['unref'])) === 'use');
473
- }
474
- if (!ts.isBinaryExpression(parent) ||
475
- parent.right !== node ||
476
- parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
477
- return false;
478
- const name = nameOfHandle(parent.left);
479
- return name !== undefined && !handled.cleared.has(name) && !handled.unreferenced.has(name);
480
- }
481
- function checkIntervals(sourceFile, file, checker, findings) {
482
- if (!sourceFile.text.includes('setInterval'))
483
- return;
484
- if (importsModule(sourceFile, (moduleName) => frontendFramework.test(moduleName)))
485
- return;
486
- const handled = collectHandledNames(sourceFile);
487
- walkNodes(sourceFile, (node) => {
488
- if (!ts.isCallExpression(node) || !isIntervalCall(node, checker))
489
- return;
490
- const owner = enclosingFunction(node);
491
- if (!owner || isStartupFunction(owner) || insideFrontendLifecycle(node))
492
- return;
493
- if (isDiscarded(outermostWrapper(node)) && isSingletonInitializer(owner))
494
- return;
495
- if (!intervalLeaks(node, checker, handled))
496
- return;
497
- findings.push(findingAt(sourceFile, file, node, 'interval-not-cleared', 'This setInterval handle is discarded or never passed to clearInterval, so the timer keeps running after its owner is gone and each call adds another. Keep the handle and clear it when the owner stops.'));
498
- });
499
- }
500
514
  function checkAcquisitions(sourceFile, file, checker, findings) {
501
515
  if (!acquisitionWords.test(sourceFile.text))
502
516
  return;
@@ -520,4 +534,4 @@ function checkResourceLeaks(sourceFile, file, checker) {
520
534
  }
521
535
  export { checkResourceLeaks };
522
536
  // Shared with the child-process rule, which resolves imports and finds uses of a local the same way.
523
- export { findingAt, insideNestedFunction, isIntervalCall, isUsingDeclaration, outermostWrapper, referenceKind, referencesTo, };
537
+ export { declaringStatement, findingAt, importedReference, importsModule, noMethods, insideNestedFunction, isIntervalCall, isUsingDeclaration, outermostWrapper, referenceKind, referencesTo, sameMembers, };
@@ -10,6 +10,7 @@ const sourceRules = [
10
10
  'check-then-update-race',
11
11
  'child-process-without-error-listener',
12
12
  'crlf-unsafe-line-split',
13
+ 'db-pool-client-not-released',
13
14
  'discarded-error-result',
14
15
  'drizzle-unfiltered-write',
15
16
  'drizzle-write-preflight',
@@ -28,6 +29,8 @@ const sourceRules = [
28
29
  'next-server-env-in-client',
29
30
  'parse-failure-resets-file',
30
31
  'payment-missing-idempotency-key',
32
+ 'pg-advisory-lock-session',
33
+ 'pg-listen-session',
31
34
  'pg-transaction-on-pool',
32
35
  'pool-without-connection-timeout',
33
36
  'prisma-dependent-writes',
@@ -117,6 +120,7 @@ const impactByRule = {
117
120
  'crlf-unsafe-line-split': 'medium',
118
121
  'csharp-async-void': 'high',
119
122
  'csharp-disposable-without-using': 'medium',
123
+ 'db-pool-client-not-released': 'high',
120
124
  'discarded-error-result': 'high',
121
125
  'drizzle-unfiltered-write': 'critical',
122
126
  'drizzle-write-preflight': 'medium',
@@ -153,6 +157,8 @@ const impactByRule = {
153
157
  'next-server-env-in-client': 'high',
154
158
  'parse-failure-resets-file': 'high',
155
159
  'payment-missing-idempotency-key': 'high',
160
+ 'pg-advisory-lock-session': 'high',
161
+ 'pg-listen-session': 'high',
156
162
  'pg-transaction-on-pool': 'critical',
157
163
  'pool-without-connection-timeout': 'medium',
158
164
  'prisma-dependent-writes': 'high',
@@ -204,6 +210,7 @@ const descriptionByRule = {
204
210
  'crlf-unsafe-line-split': 'Splitting file text on a bare newline leaves carriage returns on CRLF lines and can change exact comparisons.',
205
211
  'csharp-async-void': 'An async void method cannot be awaited and can crash the process on unhandled exceptions.',
206
212
  'csharp-disposable-without-using': 'A C# stream, connection or other IDisposable is created without using, so an exception leaks it.',
213
+ 'db-pool-client-not-released': 'A locally checked-out database connection can leave its scope without being released.',
207
214
  'discarded-error-result': 'A call discards a typed Either or Result that can carry a failure as a value.',
208
215
  'drizzle-unfiltered-write': 'A Drizzle update or delete executes without an effective where clause.',
209
216
  'drizzle-write-preflight': 'A separate existence check before a Drizzle write can race with another request.',
@@ -240,6 +247,8 @@ const descriptionByRule = {
240
247
  'next-server-env-in-client': "A 'use client' file reads a process.env variable without the NEXT_PUBLIC_ prefix, so it is unavailable in the browser by default.",
241
248
  'parse-failure-resets-file': 'A write after a read or parse failure can replace unreadable contents at the same path.',
242
249
  'payment-missing-idempotency-key': 'A Stripe call that moves money has no idempotency key, so a retry can charge or pay out twice.',
250
+ 'pg-advisory-lock-session': 'A PostgreSQL session can return to the pool while it holds an advisory lock.',
251
+ 'pg-listen-session': 'A PostgreSQL listener connection can return to the pool while it is still subscribed.',
243
252
  'pg-transaction-on-pool': 'A transaction statement is sent to a pool, so its statements can run on different connections.',
244
253
  'pool-without-connection-timeout': 'A pg Pool or Client sets no connectionTimeoutMillis, so its default of 0 waits for a connection forever.',
245
254
  'prisma-dependent-writes': 'Adjacent Prisma creates pass a value from the first record into the next write.',
@@ -271,6 +280,6 @@ const descriptionByRule = {
271
280
  'unguarded-boundary-access': 'A nested property is read from outside input or a lookup that can be missing, so absent data throws a TypeError.',
272
281
  'unreachable-code': 'Statements follow a return, throw, break or continue in the same block and never run.',
273
282
  'upload-without-size-limit': 'A multer or Nest upload interceptor has no file size limit.',
274
- 'webhook-missing-idempotency-check': 'A webhook route inserts rows without first checking whether the event was already processed.',
283
+ 'webhook-missing-idempotency-check': 'A webhook route inserts rows without visible atomic deduplication by event ID.',
275
284
  };
276
285
  export { sourceRules, migrationRules, contractRules, polyglotRules, knownRules, impactByRule, descriptionByRule };
@@ -69,6 +69,18 @@ function releaseStatementOf(call) {
69
69
  const statement = ts.isAwaitExpression(parent) ? parent.parent : parent;
70
70
  return ts.isExpressionStatement(statement) ? statement : undefined;
71
71
  }
72
+ // A strict-mode function declaration moved into try is no longer visible to earlier calls
73
+ // or closures. The acquisition itself may reference it too.
74
+ function hidesHoistedFunction(statements, boundary) {
75
+ const names = new Set(statements
76
+ .slice(boundary)
77
+ .flatMap((statement) => (ts.isFunctionDeclaration(statement) && statement.name ? [statement.name.text] : [])));
78
+ if (!names.size)
79
+ return false;
80
+ const referencesName = (node) => (ts.isIdentifier(node) && names.has(node.text)) ||
81
+ (ts.forEachChild(node, (child) => referencesName(child) || undefined) ?? false);
82
+ return statements.slice(0, boundary).some(referencesName);
83
+ }
72
84
  function wrapInFinally({ finding, node, sourceFile, text }) {
73
85
  if (!node || !sourceFile || text === undefined)
74
86
  return;
@@ -83,7 +95,10 @@ function wrapInFinally({ finding, node, sourceFile, text }) {
83
95
  const block = statement.parent;
84
96
  if (!ts.isBlock(block))
85
97
  return;
86
- const following = block.statements.slice(block.statements.indexOf(statement) + 1);
98
+ const boundary = block.statements.indexOf(statement) + 1;
99
+ if (hidesHoistedFunction(block.statements, boundary))
100
+ return;
101
+ const following = block.statements.slice(boundary);
87
102
  const last = following.at(-1);
88
103
  const spec = releaseSpecFor(finding.ruleId, declaration);
89
104
  if (!last || !spec || following.some(declaresVar) || !isAsyncContext(statement))