loadwise 0.5.1 → 0.6.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.
Files changed (132) hide show
  1. package/PERFORMANCE.md +31 -6
  2. package/README.md +580 -1024
  3. package/bin/loadwise.js +4 -0
  4. package/lib/accessibility/frontend-detect.js +2 -1
  5. package/lib/accessibility/rule-ids.js +12 -9
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +9 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +6 -0
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +25 -17
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -204,7 +204,7 @@ function transactionOnPool({ node, sourceFile, text }) {
204
204
  return wrapPoolTransaction(region, usage.poolText, client, sourceFile, text);
205
205
  }
206
206
  // ---- pool-created-per-request-or-item ----
207
- const closingMethods = new Set(['end', 'close', 'quit', 'disconnect', '$disconnect']);
207
+ const closingMethods = new Set(['end', 'close', 'quit', 'disconnect', '$disconnect', 'destroy']);
208
208
  const declarationKinds = new Set([
209
209
  ts.SyntaxKind.VariableDeclaration,
210
210
  ts.SyntaxKind.Parameter,
@@ -290,12 +290,26 @@ function wholeLines(text, statement) {
290
290
  return;
291
291
  return { start: start - (text[start - 2] === '\r' ? 2 : 1), end };
292
292
  }
293
+ function redeclaresName(node, name) {
294
+ const opensScope = ts.isFunctionLike(node) ||
295
+ ts.isClassLike(node) ||
296
+ ts.isBlock(node) ||
297
+ ts.isCaseBlock(node) ||
298
+ ts.isCatchClause(node) ||
299
+ ts.isIterationStatement(node, false);
300
+ return opensScope && bindingNamesWithin(node).has(name);
301
+ }
293
302
  function closingStatements(scope, name) {
294
303
  const statements = [];
295
304
  let usable = true;
296
305
  (function visit(child) {
297
306
  if (!usable)
298
307
  return;
308
+ // A nested scope that redeclares the name closes a different resource, so no fix is offered.
309
+ if (child !== scope && redeclaresName(child, name)) {
310
+ usable = false;
311
+ return;
312
+ }
299
313
  if (ts.isIdentifier(child) && child.text === name && isReference(child)) {
300
314
  const access = child.parent;
301
315
  const call = access.parent;
@@ -44,20 +44,32 @@ function projectConfigs(input) {
44
44
  const config = resolveConfig(input);
45
45
  const isFolder = fs.statSync(path.resolve(input)).isDirectory();
46
46
  const scope = isFolder ? path.resolve(input) : path.dirname(config);
47
- const configs = [{ config, scope }];
48
- const jsconfig = path.join(path.dirname(config), 'jsconfig.json');
49
- if (isFolder && path.basename(config) === 'tsconfig.json' && fs.existsSync(jsconfig)) {
50
- configs.push({ config: jsconfig, scope, companion: true });
51
- }
47
+ const configs = [{ config, scope, ...(!isFolder && { explicit: true }) }];
48
+ const companion = companionOf(config);
49
+ if (isFolder && companion)
50
+ configs.push({ config: companion, scope, companion: true });
52
51
  return configs;
53
52
  }
53
+ function companionOf(config) {
54
+ const jsconfig = path.join(path.dirname(config), 'jsconfig.json');
55
+ return path.basename(config) === 'tsconfig.json' && fs.existsSync(jsconfig) ? jsconfig : undefined;
56
+ }
57
+ // A workspace package's tsconfig gets its sibling jsconfig as a companion too, keeping the
58
+ // workspace's cross-package scope.
59
+ function workspaceEntries(configs) {
60
+ return configs.flatMap((input) => {
61
+ const config = resolveConfig(input);
62
+ const companion = companionOf(config);
63
+ return companion ? [{ config }, { config: companion, companion: true }] : [{ config }];
64
+ });
65
+ }
54
66
  // `project` is one `-p` input, or the configs of the selected packages of a monorepo. Those report
55
67
  // every file they
56
68
  // include: the workspace root that was scanned contains them, and a file shared by two packages
57
69
  // reports once.
58
70
  function scanEntries(project) {
59
71
  if (Array.isArray(project))
60
- return project.map((config) => ({ config: resolveConfig(config) }));
72
+ return workspaceEntries(project);
61
73
  return projectConfigs(project ?? '.');
62
74
  }
63
75
  function isInScope(scope, filename) {
@@ -1,29 +1,76 @@
1
- // A tsconfig without `allowJs` leaves the project's JavaScript out of the performance and security
2
- // checks, while the maintainability check still reads it. The project inventory names those files,
3
- // so they are never skipped silently.
1
+ // A tsconfig without `allowJs` leaves the project's JavaScript out of its program, while the
2
+ // maintainability check still reads it. A config the scan found itself has those files checked in a
3
+ // program of their own, so a missing `allowJs` never hides code from the performance and security
4
+ // checks; a config named on the command line is scanned exactly, and a note names what it leaves out.
4
5
  import path from 'node:path';
6
+ import ts from 'typescript';
5
7
  import { listFiles } from '../maintainability/inputs.js';
8
+ import { isVendoredMinified } from '../shared/execution-context.js';
9
+ import { isWithin } from '../shared/workspaces.js';
6
10
  const javaScript = /\.[cm]?jsx?$/i;
11
+ const javaScriptExtensions = ['.js', '.jsx', '.cjs', '.mjs'];
7
12
  // Tool configs such as eslint.config.js or .prettierrc.cjs are rarely in a tsconfig and hold no
8
13
  // application code.
9
14
  const toolConfig = /(?:^|\/)(?:[^/]*\.config|\.[^/]*rc)\.[cm]?js$/i;
10
15
  const shownExamples = 3;
11
16
  const notedScopes = new Set();
12
- // `scopes` are the folders scanned with a config that has `allowJs` off; `isScanned` takes an
13
- // absolute file name.
14
- function noteUnscannedJavaScript(scopes, isScanned) {
15
- for (const scope of scopes) {
16
- if (notedScopes.has(scope))
17
- continue;
18
- notedScopes.add(scope);
19
- const unscanned = listFiles(scope).filter((file) => javaScript.test(file) && !toolConfig.test(file) && !isScanned(path.resolve(scope, file)));
20
- if (!unscanned.length)
21
- continue;
22
- const folder = path.relative(process.cwd(), scope).split(path.sep).join('/') || '.';
23
- const examples = unscanned.slice(0, shownExamples).join(', ') + (unscanned.length > shownExamples ? ', ...' : '');
24
- console.error(`Note: the performance and security checks skip ${unscanned.length} JavaScript file(s) in ${folder} ` +
25
- `(${examples}) because the project config does not set "allowJs". ` +
26
- 'Set "allowJs": true or add a jsconfig.json beside the tsconfig.json to check them.');
17
+ const canonical = (filename) => {
18
+ const resolved = path.resolve(filename);
19
+ return ts.sys.useCaseSensitiveFileNames ? resolved : resolved.toLowerCase();
20
+ };
21
+ // A config's `include` usually names only its TypeScript, so only its `exclude` marks JavaScript its author left
22
+ // out on purpose. Listing the files under the config's folder through a config that extends it applies that
23
+ // `exclude`, inherited ones included. Each extension is listed on its own, because a wildcard drops a file when a
24
+ // sibling has a higher-priority extension (`foo.js` beside `foo.d.ts`), which is not an exclusion.
25
+ function excludedBy(config) {
26
+ const folder = path.dirname(config);
27
+ const kept = new Set();
28
+ for (const extension of javaScriptExtensions) {
29
+ const listed = ts.parseJsonConfigFileContent({
30
+ extends: './' + path.basename(config),
31
+ files: [],
32
+ include: [`**/*${extension}`],
33
+ compilerOptions: { allowJs: true },
34
+ }, ts.sys, folder, undefined, path.join(folder, 'loadwise-left-out.json'));
35
+ listed.fileNames.forEach((filename) => kept.add(canonical(filename)));
27
36
  }
37
+ return (filename) => isWithin(folder, filename) && !kept.has(canonical(filename));
28
38
  }
29
- export { noteUnscannedJavaScript };
39
+ // `isScanned` takes an absolute file name; `onlyFiles` limits the scan to changed or not ignored files.
40
+ // Returns the absolute names to check, and a note to print once they are checked.
41
+ function unscannedJavaScript(scopes, isScanned, onlyFiles) {
42
+ const toCheck = new Set();
43
+ const notes = [];
44
+ for (const [scope, { configs, checksLeftOut }] of scopes) {
45
+ const exclusions = configs.map(excludedBy);
46
+ const leftOut = listFiles(scope)
47
+ .filter((file) => javaScript.test(file) && !toolConfig.test(file))
48
+ .map((file) => path.resolve(scope, file))
49
+ .filter((filename) => !isScanned(filename) &&
50
+ !isVendoredMinified(filename) &&
51
+ (!onlyFiles || onlyFiles(filename)) &&
52
+ !exclusions.some((isExcluded) => isExcluded(filename)));
53
+ if (checksLeftOut)
54
+ leftOut.forEach((filename) => toCheck.add(filename));
55
+ notes.push(() => noteLeftOutJavaScript(scope, leftOut, checksLeftOut));
56
+ }
57
+ return { files: [...toCheck], note: () => notes.forEach((note) => note()) };
58
+ }
59
+ function noteLeftOutJavaScript(scope, filenames, checked) {
60
+ // Watch mode scans repeatedly, so each note prints once per process.
61
+ const key = `${scope}\0${checked}`;
62
+ if (!filenames.length || notedScopes.has(key))
63
+ return;
64
+ notedScopes.add(key);
65
+ const relative = filenames.map((filename) => path.relative(scope, filename).split(path.sep).join('/'));
66
+ const folder = path.relative(process.cwd(), scope).split(path.sep).join('/') || '.';
67
+ const examples = relative.slice(0, shownExamples).join(', ') + (relative.length > shownExamples ? ', ...' : '');
68
+ const files = `${filenames.length} JavaScript file(s) (${examples})`;
69
+ console.error(checked
70
+ ? `Note: the project config in ${folder} does not set "allowJs", so ${files} were checked with standalone ` +
71
+ 'settings (ES2022, NodeNext). Set "allowJs": true or add a jsconfig.json beside the tsconfig.json to ' +
72
+ "check them with the project's settings."
73
+ : `Note: the performance and security checks skip ${files} in ${folder} because the project config does not ` +
74
+ 'set "allowJs". Set "allowJs": true or add a jsconfig.json beside the tsconfig.json to check them.');
75
+ }
76
+ export { unscannedJavaScript };
@@ -5,6 +5,12 @@ import { checkInsertTerminators } from './sql-insert-terminator.js';
5
5
  import { checkSuspiciousLogic } from './suspicious-logic.js';
6
6
  import { checkBoundaryAccess } from './boundary-access.js';
7
7
  import { checkResourceLeaks } from './resource-leaks.js';
8
+ import { checkChildProcesses } from './child-process.js';
9
+ import { checkErrorValues } from './error-values.js';
10
+ import { checkReactBugs } from './react-bugs.js';
11
+ import { checkSwitchExhaustive } from './switch-exhaustive.js';
12
+ import { checkPoolTimeout } from './pool-timeout.js';
13
+ import { checkUncaughtException } from './uncaught-exception.js';
8
14
  import { isVendoredMinified } from '../shared/execution-context.js';
9
15
  import { relativeToProject, reviewedReason, reviewMarkers } from '../performance/review-context.js';
10
16
  function analyzeFile(program, sourceFile) {
@@ -19,6 +25,12 @@ function analyzeFile(program, sourceFile) {
19
25
  ...checkSuspiciousLogic(sourceFile, file, program.getCompilerOptions()),
20
26
  ...checkBoundaryAccess(sourceFile, file, checker),
21
27
  ...checkResourceLeaks(sourceFile, file, checker),
28
+ ...checkChildProcesses(sourceFile, file, checker),
29
+ ...checkErrorValues(sourceFile, file),
30
+ ...checkReactBugs(sourceFile, file, checker, program.getCompilerOptions().jsxImportSource),
31
+ ...checkSwitchExhaustive(sourceFile, file, checker),
32
+ ...checkPoolTimeout(sourceFile, file, checker),
33
+ ...checkUncaughtException(sourceFile, file, checker),
22
34
  ];
23
35
  const hasReviewComments = reviewMarkers.some((marker) => sourceFile.text.includes(marker));
24
36
  return findings.map((finding) => {
@@ -0,0 +1,106 @@
1
+ // A child process whose spawn fails (missing binary, no permission, out of memory) emits 'error' on the next tick.
2
+ // With no listener the parent process crashes, so every spawned process needs one or must be handed to code that
3
+ // has one.
4
+ import { ts } from '../performance/compiler.js';
5
+ import { walkNodes } from './walk.js';
6
+ import { isIgnoredSource } from './source-helpers.js';
7
+ import { findingAt, importedReference, outermostWrapper, referencesTo } from './resource-leaks.js';
8
+ // exec and execFile report a failed spawn through their callback, so only the callback-free form is a risk.
9
+ const alwaysEmitting = new Set(['spawn', 'fork']);
10
+ const callbackAccepting = new Set(['exec', 'execFile']);
11
+ const listenerMethods = new Set(['on', 'once', 'addListener', 'prependListener', 'prependOnceListener']);
12
+ function spawnedMember(call, checker) {
13
+ const origin = importedReference(call.expression, checker);
14
+ if (origin?.moduleName !== 'child_process' || origin.members.length !== 1)
15
+ return;
16
+ const [member] = origin.members;
17
+ if (alwaysEmitting.has(member))
18
+ return member;
19
+ // The first argument is the command or file, never the callback; a later identifier or property (`handlers.done`) may be the callback.
20
+ const hasCallback = call.arguments.some((argument, index) => ts.isFunctionLike(argument) ||
21
+ (index > 0 && (ts.isIdentifier(argument) || ts.isPropertyAccessExpression(argument))));
22
+ return callbackAccepting.has(member) && !hasCallback ? member : undefined;
23
+ }
24
+ // `child.on('error', ...)`, or any listener call whose event name is not a literal, which could be this one.
25
+ function registersErrorListener(call) {
26
+ const [eventName] = call.arguments;
27
+ if (!eventName)
28
+ return false;
29
+ return !ts.isStringLiteralLike(eventName) || eventName.text === 'error';
30
+ }
31
+ function useOf(reference) {
32
+ const node = outermostWrapper(reference);
33
+ const access = node.parent;
34
+ if (!ts.isPropertyAccessExpression(access) || access.expression !== node)
35
+ return 'escapes';
36
+ const call = access.parent;
37
+ if (!listenerMethods.has(access.name.text))
38
+ return 'plain';
39
+ if (!ts.isCallExpression(call) || call.expression !== access)
40
+ return 'plain';
41
+ if (registersErrorListener(call))
42
+ return 'listener';
43
+ // Listener methods return the emitter, so `child.on('close', f).on('error', g)` still registers one.
44
+ const chained = outermostWrapper(call).parent;
45
+ if (ts.isPropertyAccessExpression(chained))
46
+ return useOf(call);
47
+ // The chain's value is the process itself: passed to a call, returned or stored in an alias, it has been handed on.
48
+ return ts.isCallExpression(chained) ||
49
+ ts.isNewExpression(chained) ||
50
+ ts.isReturnStatement(chained) ||
51
+ ts.isVariableDeclaration(chained) ||
52
+ ts.isBinaryExpression(chained)
53
+ ? 'escapes'
54
+ : 'plain';
55
+ }
56
+ function declarationLacksErrorListener(declaration, checker) {
57
+ const statement = declaration.parent.parent;
58
+ if (!ts.isVariableStatement(statement) || !ts.isIdentifier(declaration.name))
59
+ return false;
60
+ return referencesTo(declaration, statement.parent, checker).every((reference) => useOf(reference) === 'plain');
61
+ }
62
+ // `spawn(...)` on its own, or `spawn(...).unref()`: nothing can have attached a listener.
63
+ function resultIsUnheld(call) {
64
+ const node = outermostWrapper(call);
65
+ const parent = node.parent;
66
+ if (ts.isExpressionStatement(parent) || (ts.isVoidExpression(parent) && ts.isExpressionStatement(parent.parent)))
67
+ return true;
68
+ if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node)
69
+ return false;
70
+ const outer = parent.parent;
71
+ if (!ts.isCallExpression(outer) || outer.expression !== parent)
72
+ return false;
73
+ if (listenerMethods.has(parent.name.text))
74
+ return !registersErrorListener(outer) && resultIsUnheld(outer);
75
+ return parent.name.text === 'unref' && isStatement(outer);
76
+ }
77
+ function isStatement(call) {
78
+ return ts.isExpressionStatement(call.parent);
79
+ }
80
+ function lacksErrorListener(call, checker) {
81
+ const parent = outermostWrapper(call).parent;
82
+ if (ts.isVariableDeclaration(parent) && parent.initializer === outermostWrapper(call))
83
+ return declarationLacksErrorListener(parent, checker);
84
+ return resultIsUnheld(call);
85
+ }
86
+ // exec and execFile keep an internal 'error' listener, so a failed spawn goes unnoticed instead of crashing.
87
+ function failureMessage(member) {
88
+ if (callbackAccepting.has(member))
89
+ return `This ${member}() call has no callback and no 'error' listener, so a failed spawn (a missing binary, no permission) goes unnoticed. Pass a callback or add child.on('error', ...).`;
90
+ return `This ${member}() child process has no 'error' listener. If the spawn fails (a missing binary, no permission), Node emits 'error' and, with no listener, the parent process crashes. Add child.on('error', ...) or wait with events.once(child, 'exit').`;
91
+ }
92
+ function checkChildProcesses(sourceFile, file, checker) {
93
+ if (!sourceFile.text.includes('child_process') || isIgnoredSource(sourceFile, file))
94
+ return [];
95
+ const findings = [];
96
+ walkNodes(sourceFile, (node) => {
97
+ if (!ts.isCallExpression(node))
98
+ return;
99
+ const member = spawnedMember(node, checker);
100
+ if (!member || !lacksErrorListener(node, checker))
101
+ return;
102
+ findings.push(findingAt(sourceFile, file, node, 'child-process-without-error-listener', failureMessage(member)));
103
+ });
104
+ return findings;
105
+ }
106
+ export { checkChildProcesses };
@@ -0,0 +1,177 @@
1
+ // Rules about what a catch block or a throw does with an error: a replacement error that drops the original, a thrown
2
+ // value that is not an Error, and a log line that keeps the message but loses the stack.
3
+ import { ts } from '../performance/compiler.js';
4
+ import { walkNodes } from './walk.js';
5
+ import { isIgnoredSource } from './source-helpers.js';
6
+ import { findingAt, insideNestedFunction, outermostWrapper } from './resource-leaks.js';
7
+ // Only the built-in error classes: a domain or HTTP error (AppError, NotFoundException) usually translates a failure on
8
+ // purpose, while a plain Error thrown from a catch block is just a worse copy of the original.
9
+ const builtInError = /^(?:Error|TypeError|RangeError|SyntaxError|ReferenceError|EvalError|URIError|AggregateError)$/;
10
+ // A failure level: a warning that drops the stack is usually a deliberate downgrade of an expected failure.
11
+ const failureLogMethods = new Set(['error', 'fatal']);
12
+ // Fixtures, end-to-end helpers, test utilities and one-off migrations throw and log loosely on purpose.
13
+ const looseFolder = /(?:^|\/)(?:__fixtures__|__mocks__|fixtures?|e2e|migrations?|tests?|__tests__|testing|test[-_][\w-]*|[\w-]*[-_]tests?)\//i;
14
+ const globalObjectName = /^(?:globalThis|global|window|self)$/;
15
+ const loggerName = /^(?:console|_?logger|_?log)$/i;
16
+ // Statements of the catch block itself, not of callbacks declared inside it.
17
+ function ownNodes(block, visit) {
18
+ walkNodes(block, (node) => {
19
+ if (node !== block && !insideNestedFunction(node, block))
20
+ visit(node);
21
+ });
22
+ }
23
+ function caughtName(clause) {
24
+ const binding = clause.variableDeclaration?.name;
25
+ return binding && ts.isIdentifier(binding) ? binding.text : undefined;
26
+ }
27
+ function mentions(root, name) {
28
+ let found = false;
29
+ walkNodes(root, (node) => {
30
+ const isPropertyName = ts.isPropertyAccessExpression(node.parent) && node.parent.name === node;
31
+ if (ts.isIdentifier(node) && node.text === name && !isPropertyName)
32
+ found = true;
33
+ });
34
+ return found;
35
+ }
36
+ function constructedName(thrown) {
37
+ // `throw Error('x')` constructs the same error as `throw new Error('x')`; parentheses change nothing.
38
+ const expression = ts.skipOuterExpressions(thrown);
39
+ if (!ts.isNewExpression(expression) && !ts.isCallExpression(expression))
40
+ return;
41
+ const callee = ts.skipOuterExpressions(expression.expression);
42
+ if (ts.isIdentifier(callee))
43
+ return callee.text;
44
+ // Only `globalThis.Error` is certainly the built-in; `domain.Error` is a domain constructor.
45
+ if (!ts.isPropertyAccessExpression(callee))
46
+ return;
47
+ const owner = ts.skipOuterExpressions(callee.expression);
48
+ return ts.isIdentifier(owner) && globalObjectName.test(owner.text) ? callee.name.text : undefined;
49
+ }
50
+ // `new Error('x', { cause: previous })` already keeps a cause, just not the caught one.
51
+ function carriesCause(thrown) {
52
+ const expression = ts.skipOuterExpressions(thrown);
53
+ if (!ts.isNewExpression(expression) && !ts.isCallExpression(expression))
54
+ return false;
55
+ return (expression.arguments ?? []).some((argument) => ts.isObjectLiteralExpression(argument) &&
56
+ argument.properties.some((property) => property.name?.getText() === 'cause'));
57
+ }
58
+ function checkRethrowWithoutCause(clause, sourceFile, file, findings) {
59
+ const name = caughtName(clause);
60
+ // An underscore name says the value is unused on purpose; any other use in the block means the code looked at it.
61
+ if (name === undefined || name.startsWith('_') || mentions(clause.block, name))
62
+ return;
63
+ // A block that does anything besides throw (reports to the user, cleans up) is translating the failure on purpose.
64
+ const [statement] = clause.block.statements;
65
+ if (clause.block.statements.length !== 1 || !ts.isThrowStatement(statement) || !statement.expression)
66
+ return;
67
+ const created = constructedName(statement.expression);
68
+ if (created !== undefined && builtInError.test(created) && !carriesCause(statement.expression))
69
+ findings.push(findingAt(sourceFile, file, statement, 'error-rethrown-without-cause', `This throws a new ${created} from a catch block without the caught error, so the original message and stack are lost. Pass it as \`{ cause: ${name} }\`.`));
70
+ }
71
+ function isErrorValue(expression) {
72
+ const value = ts.skipOuterExpressions(expression);
73
+ if (ts.isStringLiteralLike(value) || ts.isTemplateExpression(value))
74
+ return 'a string';
75
+ if (ts.isNumericLiteral(value) || ts.isBigIntLiteral(value))
76
+ return 'a number';
77
+ if (ts.isPrefixUnaryExpression(value) && isErrorValue(value.operand) === 'a number')
78
+ return 'a number';
79
+ if (ts.isIdentifier(value) && value.text === 'undefined')
80
+ return 'undefined';
81
+ if (ts.isObjectLiteralExpression(value))
82
+ return 'an object literal';
83
+ if (ts.isArrayLiteralExpression(value))
84
+ return 'an array';
85
+ if (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword)
86
+ return 'a boolean';
87
+ if (value.kind === ts.SyntaxKind.NullKeyword)
88
+ return 'null';
89
+ if (ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.PlusToken)
90
+ return isErrorValue(value.left) === 'a string' || isErrorValue(value.right) === 'a string' ? 'a string' : undefined;
91
+ return undefined;
92
+ }
93
+ function checkThrowNonError(node, sourceFile, file, findings) {
94
+ const kind = node.expression && isErrorValue(node.expression);
95
+ if (!kind)
96
+ return;
97
+ findings.push(findingAt(sourceFile, file, node, 'throw-non-error', `This throws ${kind}, which has no stack trace and fails \`instanceof Error\` checks. Throw an Error (or a subclass) instead.`));
98
+ }
99
+ function isFailureLog(node) {
100
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
101
+ return false;
102
+ if (!failureLogMethods.has(node.expression.name.text))
103
+ return false;
104
+ let receiver = ts.skipOuterExpressions(node.expression.expression);
105
+ while (ts.isPropertyAccessExpression(receiver)) {
106
+ if (loggerName.test(receiver.name.text))
107
+ return true;
108
+ receiver = ts.skipOuterExpressions(receiver.expression);
109
+ }
110
+ return ts.isIdentifier(receiver) && loggerName.test(receiver.text);
111
+ }
112
+ // `err instanceof Error` only inspects the value, so it neither logs nor hands the error on.
113
+ function isTypeGuard(reference) {
114
+ const value = outermostWrapper(reference);
115
+ const guard = value.parent;
116
+ return (ts.isBinaryExpression(guard) && guard.operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword && guard.left === value);
117
+ }
118
+ function isMessageRead(reference) {
119
+ const value = outermostWrapper(reference);
120
+ const access = value.parent;
121
+ return ts.isPropertyAccessExpression(access) && access.expression === value && access.name.text === 'message';
122
+ }
123
+ function enclosingFailureLog(reference, block) {
124
+ for (let current = reference; current && current !== block; current = current.parent)
125
+ if (isFailureLog(current))
126
+ return current;
127
+ }
128
+ function exitsOrThrows(block) {
129
+ let exits = false;
130
+ ownNodes(block, (node) => {
131
+ if (ts.isThrowStatement(node))
132
+ exits = true;
133
+ if (ts.isCallExpression(node) && node.expression.getText() === 'process.exit')
134
+ exits = true;
135
+ });
136
+ return exits;
137
+ }
138
+ // A nested catch that reuses the name declares its own binding, so its references are not the outer error.
139
+ function isShadowedByNestedCatch(node, name, outer) {
140
+ for (let current = node; current && current !== outer.block; current = current.parent)
141
+ if (ts.isCatchClause(current) && caughtName(current) === name)
142
+ return true;
143
+ return false;
144
+ }
145
+ function checkLoggedWithoutStack(clause, sourceFile, file, findings) {
146
+ const name = caughtName(clause);
147
+ if (name === undefined || exitsOrThrows(clause.block))
148
+ return;
149
+ const references = [];
150
+ walkNodes(clause.block, (node) => {
151
+ const isPropertyName = ts.isPropertyAccessExpression(node.parent) && node.parent.name === node;
152
+ if (ts.isIdentifier(node) && node.text === name && !isPropertyName && !isShadowedByNestedCatch(node, name, clause))
153
+ references.push(node);
154
+ });
155
+ const logReads = references.filter((reference) => !isTypeGuard(reference));
156
+ if (!logReads.length || !logReads.every(isMessageRead))
157
+ return;
158
+ const logged = logReads.map((reference) => enclosingFailureLog(reference, clause.block)).find(Boolean);
159
+ if (!logged)
160
+ return;
161
+ findings.push(findingAt(sourceFile, file, logged, 'error-logged-without-stack', `This catch block logs only ${name}.message and carries on, so the stack trace and any cause are lost. Log the error itself (for example \`logger.error({ err: ${name} }, ...)\`) or rethrow it.`));
162
+ }
163
+ function checkErrorValues(sourceFile, file) {
164
+ if (isIgnoredSource(sourceFile, file) || looseFolder.test(file.replaceAll('\\', '/')))
165
+ return [];
166
+ const findings = [];
167
+ walkNodes(sourceFile, (node) => {
168
+ if (ts.isCatchClause(node)) {
169
+ checkRethrowWithoutCause(node, sourceFile, file, findings);
170
+ checkLoggedWithoutStack(node, sourceFile, file, findings);
171
+ }
172
+ else if (ts.isThrowStatement(node))
173
+ checkThrowNonError(node, sourceFile, file, findings);
174
+ });
175
+ return findings;
176
+ }
177
+ export { checkErrorValues };
@@ -0,0 +1,79 @@
1
+ // A `pg` pool or client created without `connectionTimeoutMillis`. node-postgres defaults it to 0, which waits for a
2
+ // connection forever, so a saturated pool or an unreachable database hangs every request instead of failing. Libraries
3
+ // whose defaults already time out (mysql2 and mysql `connectTimeout`, knex `acquireConnectionTimeout`, mongodb,
4
+ // ioredis, mssql, Sequelize, postgres.js) are deliberately left out.
5
+ import { ts } from '../performance/compiler.js';
6
+ import { walkNodes } from './walk.js';
7
+ import { isIgnoredSource } from './source-helpers.js';
8
+ const pgPackage = /[\\/]node_modules[\\/](?:@types[\\/])?pg(?:-pool)?[\\/]/;
9
+ const pgClassNames = new Set(['Pool', 'Client']);
10
+ const timeoutOption = 'connectionTimeoutMillis';
11
+ // The constructor is identified by the class it resolves to, so an import alias (`Pool as PgPool`) is still checked
12
+ // and an unrelated local class named `Pool` is not.
13
+ function isPgConstruction(node, checker) {
14
+ const declaration = checker.getResolvedSignature(node)?.declaration;
15
+ if (declaration === undefined || !pgPackage.test(declaration.getSourceFile().fileName))
16
+ return false;
17
+ const owner = declaration.parent;
18
+ return ts.isClassLike(owner) && owner.name !== undefined && pgClassNames.has(owner.name.text);
19
+ }
20
+ function propertyName(property) {
21
+ const name = property.name;
22
+ if (name === undefined)
23
+ return;
24
+ if (ts.isComputedPropertyName(name))
25
+ return ts.isStringLiteralLike(name.expression) ? name.expression.text : undefined;
26
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? name.text : undefined;
27
+ }
28
+ // `connectionTimeoutMillis: 0` and `undefined` are the default, so they do not bound the wait.
29
+ function disablesTimeout(value) {
30
+ const expression = ts.skipOuterExpressions(value);
31
+ if (ts.isIdentifier(expression))
32
+ return expression.text === 'undefined';
33
+ return ts.isNumericLiteral(expression) && Number(expression.text) === 0;
34
+ }
35
+ // A later property overrides an earlier one, so the last spread or `connectionTimeoutMillis` property decides. A spread
36
+ // may supply the timeout, so it counts as setting it.
37
+ function setsTimeout(properties) {
38
+ for (const property of properties.toReversed()) {
39
+ if (ts.isSpreadAssignment(property))
40
+ return true;
41
+ if (propertyName(property) !== timeoutOption)
42
+ continue;
43
+ return !ts.isPropertyAssignment(property) || !disablesTimeout(property.initializer);
44
+ }
45
+ return false;
46
+ }
47
+ // Whether the configuration visibly lacks the option. A configuration held elsewhere (a variable, a spread) may set it.
48
+ // A connection string never sets it: pg reads the timer from the `connectionTimeoutMillis` property of the argument, so
49
+ // a query parameter in the URL does not enable it.
50
+ function lacksTimeout(node) {
51
+ const [config] = node.arguments ?? [];
52
+ if (config === undefined)
53
+ return true;
54
+ const expression = ts.skipOuterExpressions(config);
55
+ if (ts.isStringLiteralLike(expression))
56
+ return true;
57
+ if (!ts.isObjectLiteralExpression(expression))
58
+ return false;
59
+ return !setsTimeout(expression.properties);
60
+ }
61
+ function checkPoolTimeout(sourceFile, file, checker) {
62
+ if (!sourceFile.text.includes('new ') || isIgnoredSource(sourceFile, file))
63
+ return [];
64
+ const findings = [];
65
+ walkNodes(sourceFile, (node) => {
66
+ if (!ts.isNewExpression(node) || !isPgConstruction(node, checker) || !lacksTimeout(node))
67
+ return;
68
+ const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
69
+ findings.push({
70
+ file,
71
+ line: position.line + 1,
72
+ column: position.character + 1,
73
+ ruleId: 'pool-without-connection-timeout',
74
+ message: 'This pg connection is created without connectionTimeoutMillis, whose default of 0 waits forever, so an exhausted pool or unreachable database hangs the caller. Set connectionTimeoutMillis to a few seconds.',
75
+ });
76
+ });
77
+ return findings;
78
+ }
79
+ export { checkPoolTimeout };