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.
- package/README.md +23 -15
- package/dist/bin/loadwise.js +12 -24
- package/dist/lib/accessibility/analyze.js +5 -3
- package/dist/lib/accessibility/angular-inline.js +9 -11
- package/dist/lib/accessibility/angular-literal.js +39 -0
- package/dist/lib/accessibility/form-context.js +36 -0
- package/dist/lib/accessibility/frame-head.js +92 -0
- package/dist/lib/accessibility/frame-viewport.js +149 -0
- package/dist/lib/accessibility/jsx-elements.js +13 -3
- package/dist/lib/accessibility/markup-files.js +7 -2
- package/dist/lib/accessibility/rule-ids.js +3 -0
- package/dist/lib/accessibility/rules.js +128 -41
- package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
- package/dist/lib/accessibility/template-attributes.js +5 -3
- package/dist/lib/accessibility/template-elements.js +25 -6
- package/dist/lib/accessibility/template-file.js +40 -25
- package/dist/lib/editor/accessibility-examples.js +6 -1
- package/dist/lib/editor/actions.js +46 -7
- package/dist/lib/editor/apply-fix.js +69 -4
- package/dist/lib/editor/configured-setup.js +5 -3
- package/dist/lib/editor/diagnostics.js +206 -17
- package/dist/lib/editor/dismissals.js +85 -26
- package/dist/lib/editor/editor-document.js +5 -2
- package/dist/lib/editor/editor-launcher.js +7 -2
- package/dist/lib/editor/language-server.js +64 -25
- package/dist/lib/editor/native-setup.js +3 -2
- package/dist/lib/editor/perf-watch.js +8 -6
- package/dist/lib/editor/reliability-examples.js +15 -0
- package/dist/lib/editor/scan-session.js +29 -8
- package/dist/lib/editor/server-commands.js +36 -9
- package/dist/lib/editor/setup-server.js +1 -1
- package/dist/lib/editor/setup-vim.js +6 -4
- package/dist/lib/editor/workspace-files.js +61 -7
- package/dist/lib/editor/workspace-paths.js +41 -1
- package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
- package/dist/lib/maintainability/architecture/architecture.js +4 -4
- package/dist/lib/maintainability/cli/changed-lines.js +20 -2
- package/dist/lib/maintainability/cli/inputs.js +9 -1
- package/dist/lib/maintainability/cli.js +4 -0
- package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
- package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
- package/dist/lib/maintainability/quality/functions.js +9 -6
- package/dist/lib/maintainability/quality/limits.js +19 -0
- package/dist/lib/maintainability/quality/size-limits.js +8 -2
- package/dist/lib/maintainability/quality/stray-console.js +62 -1
- package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
- package/dist/lib/maintainability/scan-changed.js +4 -1
- package/dist/lib/maintainability/scan-worker.js +6 -2
- package/dist/lib/maintainability/scan.js +21 -8
- package/dist/lib/maintainability/unused/module-usage.js +43 -21
- package/dist/lib/maintainability/unused/unused-modules.js +5 -10
- package/dist/lib/performance/analysis/source-inputs.js +7 -2
- package/dist/lib/performance/analysis/source-options.js +7 -6
- package/dist/lib/performance/analyze.js +16 -3
- package/dist/lib/performance/cli/cli-output.js +1 -0
- package/dist/lib/performance/cli/cli-scan.js +21 -2
- package/dist/lib/performance/cli.js +8 -3
- package/dist/lib/performance/collections/memory-growth.js +55 -12
- package/dist/lib/performance/contracts/openapi.js +13 -4
- package/dist/lib/performance/datastores/pg-integrity.js +61 -22
- package/dist/lib/performance/datastores/pg-session-release.js +114 -0
- package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
- package/dist/lib/performance/datastores/pooling.js +56 -2
- package/dist/lib/performance/datastores/redis.js +94 -18
- package/dist/lib/performance/datastores/session-store.js +2 -1
- package/dist/lib/performance/db/checks.js +19 -8
- package/dist/lib/performance/db/gateway.js +3 -1
- package/dist/lib/performance/db/plan-estimates.js +4 -4
- package/dist/lib/performance/engine/native.js +11 -7
- package/dist/lib/performance/evidence/plans.js +7 -5
- package/dist/lib/performance/evidence/traces.js +21 -1
- package/dist/lib/performance/frontend/angular-teardown.js +96 -0
- package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
- package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
- package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
- package/dist/lib/performance/frontend/frontend-perf.js +72 -57
- package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
- package/dist/lib/performance/migrations/extract-code.js +13 -5
- package/dist/lib/performance/migrations/extract-sql.js +82 -38
- package/dist/lib/performance/migrations/operations.js +56 -13
- package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
- package/dist/lib/performance/migrations/postgres-registry.js +127 -26
- package/dist/lib/performance/migrations/postgres-settings.js +78 -0
- package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
- package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
- package/dist/lib/performance/migrations/rules-postgres.js +88 -39
- package/dist/lib/performance/orm/offset-pagination.js +6 -4
- package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
- package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
- package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
- package/dist/lib/performance/polyglot.js +111 -14
- package/dist/lib/performance/projects.js +3 -3
- package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
- package/dist/lib/performance/request/backend-mastery.js +151 -42
- package/dist/lib/performance/request/mongoose-lean.js +175 -10
- package/dist/lib/performance/request/phase5-rules.js +74 -13
- package/dist/lib/performance/request/sql-select-star.js +150 -0
- package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
- package/dist/lib/performance/request/upload-limits.js +5 -1
- package/dist/lib/performance/site-fix.js +4 -4
- package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
- package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
- package/dist/lib/performance/site-fixes/migration-context.js +8 -1
- package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
- package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
- package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
- package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
- package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
- package/dist/lib/performance/sql/mysql-tokens.js +38 -12
- package/dist/lib/reliability/boundary-access.js +114 -57
- package/dist/lib/reliability/react-bugs.js +18 -4
- package/dist/lib/reliability/resource-leak-intervals.js +258 -0
- package/dist/lib/reliability/resource-leaks.js +209 -195
- package/dist/lib/reliability/rule-ids.js +10 -1
- package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
- package/dist/lib/reliability/swallowed-errors.js +107 -21
- package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
- package/dist/lib/reliability/walk.js +3 -2
- package/dist/lib/security/auth-crypto/hashing.js +24 -8
- package/dist/lib/security/auth-crypto/jwt.js +21 -6
- package/dist/lib/security/auth-crypto/secrets.js +44 -1
- package/dist/lib/security/auth-crypto/shared.js +3 -1
- package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
- package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
- package/dist/lib/security/cli.js +6 -2
- package/dist/lib/security/cookie-credentials.js +115 -0
- package/dist/lib/security/cookie-csrf.js +241 -0
- package/dist/lib/security/deps/advisory.js +50 -109
- package/dist/lib/security/deps/cli.js +1 -1
- package/dist/lib/security/deps/cvss-score.js +14 -0
- package/dist/lib/security/deps/fixed-version.js +97 -0
- package/dist/lib/security/deps/lockfiles.js +135 -74
- package/dist/lib/security/deps/osv.js +11 -3
- package/dist/lib/security/deps/scan.js +47 -20
- package/dist/lib/security/deps/yarn-lock.js +158 -0
- package/dist/lib/security/examples/injection.cjs +4 -0
- package/dist/lib/security/exposure/cookies.js +17 -2
- package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
- package/dist/lib/security/exposure/frontend-security.js +21 -14
- package/dist/lib/security/exposure/jsx-url.js +18 -33
- package/dist/lib/security/exposure/logging.js +49 -10
- package/dist/lib/security/exposure/prototype-pollution.js +126 -56
- package/dist/lib/security/exposure/react-html.js +26 -0
- package/dist/lib/security/exposure/reflected-xss.js +34 -5
- package/dist/lib/security/files/compose.js +126 -1
- package/dist/lib/security/files/dockerfile.js +62 -4
- package/dist/lib/security/files/index.js +1 -1
- package/dist/lib/security/injection/command.js +46 -18
- package/dist/lib/security/injection/index.js +2 -0
- package/dist/lib/security/injection/ldap.js +86 -0
- package/dist/lib/security/injection/nosql.js +28 -4
- package/dist/lib/security/injection/redos.js +1 -1
- package/dist/lib/security/injection/rule-ids.js +1 -0
- package/dist/lib/security/injection/shared.js +5 -1
- package/dist/lib/security/injection/sql.js +28 -13
- package/dist/lib/security/lexical-declaration.js +113 -0
- package/dist/lib/security/pg-dynamic-query.js +28 -1
- package/dist/lib/security/pg-identifier-guards.js +107 -3
- package/dist/lib/security/phase5-rules.js +26 -135
- package/dist/lib/security/polyglot.js +2 -2
- package/dist/lib/security/redirect-settings.js +98 -0
- package/dist/lib/security/request-forgery/open-redirect.js +18 -5
- package/dist/lib/security/request-forgery/path-traversal.js +84 -6
- package/dist/lib/security/request-forgery/shared.js +1 -7
- package/dist/lib/security/request-forgery/ssrf.js +176 -14
- package/dist/lib/security/rule-descriptions.js +5 -1
- package/dist/lib/security/rule-ids.js +7 -0
- package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
- package/dist/lib/security/site-fixes/exposure.js +21 -3
- package/dist/lib/security/site-fixes/files.js +11 -13
- package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
- package/dist/lib/security/site-fixes/injection.js +17 -4
- package/dist/lib/security/site-fixes/jwt.js +1 -20
- package/dist/lib/security/site-fixes/request-forgery.js +37 -29
- package/dist/lib/security/taint/binding-inputs.js +236 -0
- package/dist/lib/security/taint/filename-guard.js +45 -45
- package/dist/lib/security/taint/guards.js +14 -8
- package/dist/lib/security/taint/index.js +126 -154
- package/dist/lib/security/taint/propagate.js +43 -9
- package/dist/lib/security/taint/record-writes.js +161 -0
- package/dist/lib/security/taint/resolution-cache.js +13 -7
- package/dist/lib/security/taint/sanitizers.js +89 -5
- package/dist/lib/security/taint/trace-nodes.js +61 -0
- package/dist/lib/security/taint/validators.js +89 -9
- package/dist/lib/shared/agent/agent-init.js +2 -1
- package/dist/lib/shared/agent/agent-verify.js +4 -1
- package/dist/lib/shared/agent/git-hook.js +17 -6
- package/dist/lib/shared/agent/review-mcp.js +8 -2
- package/dist/lib/shared/analysis/ast-semantics.js +2 -2
- package/dist/lib/shared/analysis/scan-cache.js +96 -12
- package/dist/lib/shared/cli-dispatch.js +17 -0
- package/dist/lib/shared/config.js +27 -10
- package/dist/lib/shared/explain.js +1 -1
- package/dist/lib/shared/fix/fix-convergence.js +5 -3
- package/dist/lib/shared/fix/fix-imports.js +4 -171
- package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
- package/dist/lib/shared/fix/fix-presentation.js +5 -3
- package/dist/lib/shared/fix/fix-safety.js +7 -1
- package/dist/lib/shared/fix/fix-typecheck.js +8 -4
- package/dist/lib/shared/fix/import-text-edits.js +148 -0
- package/dist/lib/shared/fix.js +31 -7
- package/dist/lib/shared/formats/finding-location.js +4 -1
- package/dist/lib/shared/formats/github.js +3 -3
- package/dist/lib/shared/formats/sarif.js +9 -3
- package/dist/lib/shared/report-fp.js +6 -2
- package/dist/lib/shared/reporting/baseline.js +7 -5
- package/dist/lib/shared/reporting/pillars.js +9 -3
- package/dist/lib/shared/reporting/source-report.js +1 -0
- package/dist/lib/shared/system/glob.js +34 -8
- package/dist/lib/shared/system/sentry.js +26 -7
- package/dist/lib/shared/workspaces.js +15 -3
- package/package.json +5 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/hooks/check-edited-file.mjs +27 -5
- package/polyglot/performance/rules/csharp.yml +34 -5
- package/polyglot/performance/rules/java.yml +24 -1
- package/polyglot/performance/rules/python.yml +74 -2
- package/polyglot/performance/sgconfig.yml +1 -0
- package/polyglot/reliability/rules/csharp.yml +12 -6
- package/polyglot/reliability/rules/go.yml +86 -6
- package/polyglot/reliability/rules/java.yml +22 -1
- package/polyglot/reliability/sgconfig.yml +1 -0
- package/polyglot/security/rules/go.yml +100 -22
- package/polyglot/security/rules/python.yml +74 -6
- package/polyglot/security/rules/rust.yml +65 -0
- package/polyglot/security/sgconfig.yml +1 -0
- package/schema/loadwise.config.schema.json +554 -76
- /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
|
@@ -51,20 +51,15 @@ function queueReexportDependencies(wanted, reexport, pending) {
|
|
|
51
51
|
else if (reexport.star && wanted !== 'default')
|
|
52
52
|
pending.push([reexport.to, wanted]);
|
|
53
53
|
}
|
|
54
|
-
const
|
|
55
|
-
|
|
54
|
+
const sourceFileExtensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
|
|
55
|
+
// Directory indexes keep the long-standing .ts, .tsx, .js precedence ahead of the later-added extensions.
|
|
56
|
+
const indexExtensions = [
|
|
56
57
|
'.ts',
|
|
57
58
|
'.tsx',
|
|
58
|
-
'.mts',
|
|
59
|
-
'.cts',
|
|
60
59
|
'.js',
|
|
61
|
-
'.
|
|
62
|
-
'.mjs',
|
|
63
|
-
'.cjs',
|
|
64
|
-
'/index.ts',
|
|
65
|
-
'/index.tsx',
|
|
66
|
-
'/index.js',
|
|
60
|
+
...sourceFileExtensions.filter((extension) => !['.ts', '.tsx', '.js'].includes(extension)),
|
|
67
61
|
];
|
|
62
|
+
const sourceSuffixes = ['', ...sourceFileExtensions, ...indexExtensions.map((extension) => `/index${extension}`)];
|
|
68
63
|
// Finds the project file a workspace package name points at when TypeScript could not (dependencies
|
|
69
64
|
// not installed). Packages that are named but not found are collected, because usage inside them is
|
|
70
65
|
// then incomplete.
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { coveringConfig, isWithin } from '../../shared/workspaces.js';
|
|
4
|
+
const declarationFile = /\.d\.[cm]?ts$/i;
|
|
4
5
|
function isSourceInput(filename) {
|
|
5
|
-
return /\.[cm]?[jt]sx?$/i.test(filename) &&
|
|
6
|
+
return /\.[cm]?[jt]sx?$/i.test(filename) && !declarationFile.test(filename);
|
|
7
|
+
}
|
|
8
|
+
// Unimported declarations can contribute globals and module augmentations to selected sources.
|
|
9
|
+
function scopedProjectRoots(roots, onlyFiles) {
|
|
10
|
+
return onlyFiles ? roots.filter((file) => declarationFile.test(file) || onlyFiles(file)) : roots;
|
|
6
11
|
}
|
|
7
12
|
function compareFindings(left, right) {
|
|
8
13
|
return ((left.file ?? '').localeCompare(right.file ?? '') ||
|
|
@@ -80,4 +85,4 @@ function isInScope(scope, filename) {
|
|
|
80
85
|
function relativeToWorkingDirectory(filename) {
|
|
81
86
|
return path.relative(process.cwd(), filename).split(path.sep).join('/');
|
|
82
87
|
}
|
|
83
|
-
export { compareFindings, isInScope, isSourceInput, mergeFinding, relativeToWorkingDirectory, resolveConfig, scanEntries, };
|
|
88
|
+
export { compareFindings, isInScope, isSourceInput, scopedProjectRoots, mergeFinding, relativeToWorkingDirectory, resolveConfig, scanEntries, };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CliUsageError } from '../../shared/system/sentry.js';
|
|
1
2
|
import { parseMinImpact } from '../../shared/reporting/impact-levels.js';
|
|
2
3
|
import { resolveFormat } from '../../shared/formats/index.js';
|
|
3
4
|
import { registeredRuleIds } from '../../shared/reporting/pillar-rules.js';
|
|
@@ -30,14 +31,14 @@ const sourceCheckOptions = {
|
|
|
30
31
|
};
|
|
31
32
|
function sourceEngine(values, positionals) {
|
|
32
33
|
if (values.native && (values.engine ?? 'native') !== 'native')
|
|
33
|
-
throw new
|
|
34
|
+
throw new CliUsageError('--native is an alias for --engine native.');
|
|
34
35
|
const engine = values.native ? 'native' : (values.engine ?? 'auto');
|
|
35
36
|
if (!['auto', 'native', 'js'].includes(engine))
|
|
36
|
-
throw new
|
|
37
|
+
throw new CliUsageError('--engine must be auto, native or js.');
|
|
37
38
|
if (values.watch && engine === 'native')
|
|
38
|
-
throw new
|
|
39
|
+
throw new CliUsageError('--native supports one-shot checks. Use --watch with the incremental JS compiler.');
|
|
39
40
|
if (values.watch && positionals.length)
|
|
40
|
-
throw new
|
|
41
|
+
throw new CliUsageError('--watch requires a project config.');
|
|
41
42
|
return engine;
|
|
42
43
|
}
|
|
43
44
|
function selectedFixIds(values, baselineOptions) {
|
|
@@ -46,9 +47,9 @@ function selectedFixIds(values, baselineOptions) {
|
|
|
46
47
|
.map((id) => id.trim())
|
|
47
48
|
.filter(Boolean);
|
|
48
49
|
if (values.only.length && !values.fix)
|
|
49
|
-
throw new
|
|
50
|
+
throw new CliUsageError('--only is only valid with --fix.');
|
|
50
51
|
if (values.only.length && !onlyIds.length)
|
|
51
|
-
throw new
|
|
52
|
+
throw new CliUsageError('--only needs at least one finding id.');
|
|
52
53
|
if (values.fix && values.watch)
|
|
53
54
|
throw new Error('--fix cannot be combined with --watch.');
|
|
54
55
|
if ((baselineOptions.baseline || baselineOptions.writeBaseline) && (values.fix || values.watch)) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
1
2
|
import { ts } from './engine/compiler.js';
|
|
2
3
|
import { withPrismaPackageInventory } from './schema/prisma-owners.js';
|
|
3
4
|
import { check as checkServiceLoops } from './query-loops/service-loops.js';
|
|
@@ -135,15 +136,19 @@ function scanFile(program, sourceFile, policy, forEachSourceCandidate) {
|
|
|
135
136
|
const pendingBlockingCalls = checker.getSymbolsAtLocations ? [] : undefined;
|
|
136
137
|
const checkTransactionLoop = createTransactionLoopCheck(sourceFile, checker);
|
|
137
138
|
const snapshot = currentSnapshot();
|
|
138
|
-
const compilerOptions =
|
|
139
|
+
const compilerOptions = program.getCompilerOptions();
|
|
139
140
|
const repeatedCache = new WeakMap();
|
|
140
141
|
let hasReviewComments;
|
|
142
|
+
const relativeFile = policy?.projectDirectory
|
|
143
|
+
? path.relative(policy.projectDirectory, sourceFile.fileName).replaceAll('\\', '/')
|
|
144
|
+
: sourceFile.fileName.replaceAll('\\', '/');
|
|
141
145
|
const context = {
|
|
142
146
|
checker,
|
|
143
147
|
program,
|
|
144
|
-
strictNullChecks:
|
|
145
|
-
verbatimModuleSyntax:
|
|
148
|
+
strictNullChecks: Boolean(compilerOptions?.strictNullChecks ?? compilerOptions?.strict),
|
|
149
|
+
verbatimModuleSyntax: Boolean(compilerOptions?.verbatimModuleSyntax),
|
|
146
150
|
fireAndForgetNames: new Set(policy?.fireAndForget),
|
|
151
|
+
ruleOptions: (ruleId) => policy?.ruleOptions?.(ruleId, relativeFile),
|
|
147
152
|
isRepeated(node) {
|
|
148
153
|
let repeated = repeatedCache.get(node);
|
|
149
154
|
if (repeated === undefined) {
|
|
@@ -153,6 +158,14 @@ function scanFile(program, sourceFile, policy, forEachSourceCandidate) {
|
|
|
153
158
|
return repeated;
|
|
154
159
|
},
|
|
155
160
|
isPackageType: createPackageTypeChecker(checker),
|
|
161
|
+
ruleOption(ruleId, option) {
|
|
162
|
+
if (!policy?.ruleOptions)
|
|
163
|
+
return undefined;
|
|
164
|
+
const rel = policy.projectDirectory
|
|
165
|
+
? path.relative(policy.projectDirectory, sourceFile.fileName).split(path.sep).join('/')
|
|
166
|
+
: sourceFile.fileName;
|
|
167
|
+
return policy.ruleOptions(ruleId, rel)?.[option];
|
|
168
|
+
},
|
|
156
169
|
// details carries optional suggestion and related links, which index rules attach.
|
|
157
170
|
report(node, ruleId, message, contextualReason, details) {
|
|
158
171
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
@@ -72,6 +72,7 @@ export async function printResult(result, values, print = console.log) {
|
|
|
72
72
|
options: values.baselineOptions ?? {},
|
|
73
73
|
pillar: values.sourcePillar ?? 'performance',
|
|
74
74
|
findings: result.findings,
|
|
75
|
+
skippedFiles: result.skippedFiles,
|
|
75
76
|
projectRoot: values.projectDirectory ?? process.cwd(),
|
|
76
77
|
absoluteFileOf: (finding) => path.resolve(finding.file ?? ''),
|
|
77
78
|
idRoot,
|
|
@@ -115,7 +115,20 @@ export async function checkCode(args, report = printResult, baselineFlags = {},
|
|
|
115
115
|
projectDirectory: directory,
|
|
116
116
|
sourcePillar: pillar.jsonKey,
|
|
117
117
|
};
|
|
118
|
-
const
|
|
118
|
+
const basePolicySource = sourcePolicy(values.policy, values.settings);
|
|
119
|
+
// Override globs are relative to the config file's folder, which can differ from the scan folder.
|
|
120
|
+
const withRuleOptions = (base, settings) => settings.ruleOptions
|
|
121
|
+
? {
|
|
122
|
+
...base,
|
|
123
|
+
ruleOptions: settings.ruleOptions,
|
|
124
|
+
projectDirectory: settings.filename ? path.dirname(settings.filename) : directory,
|
|
125
|
+
}
|
|
126
|
+
: base;
|
|
127
|
+
const policySource = {
|
|
128
|
+
filename: basePolicySource.filename,
|
|
129
|
+
// Watch refreshes reread the config so edited rule options apply without a restart.
|
|
130
|
+
read: () => withRuleOptions(basePolicySource.read(), values.watch ? loadSettings({ directory, explicit: values['loadwise-config'] }) : values.settings),
|
|
131
|
+
};
|
|
119
132
|
const policy = policySource.read();
|
|
120
133
|
if (withCommands.length)
|
|
121
134
|
return checkWithPillars({
|
|
@@ -204,7 +217,13 @@ async function watchSource(values, policySource) {
|
|
|
204
217
|
const { watchProject } = await import('./watch.js');
|
|
205
218
|
const logError = (error) => {
|
|
206
219
|
const message = typeof error === 'object' && error !== null && 'message' in error ? error.message : error;
|
|
207
|
-
|
|
220
|
+
// The editor must distinguish an unusable refresh from ordinary stderr coverage notes.
|
|
221
|
+
if (process.env.LOADWISE_EDITOR_WATCH_EVENTS === '1' && values.json) {
|
|
222
|
+
console.log(JSON.stringify({ watchError: terminalSafe(String(message)) }));
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
console.error(typeof message === 'string' ? terminalSafe(message) : message);
|
|
226
|
+
}
|
|
208
227
|
};
|
|
209
228
|
const watcher = watchProject(values.project ?? '.', {
|
|
210
229
|
policySource,
|
|
@@ -8,6 +8,7 @@ import { parseCommand, readJsonFile, showHelp } from './cli/cli-arguments.js';
|
|
|
8
8
|
import { printResult, scanFilter } from './cli/cli-output.js';
|
|
9
9
|
import { projectDirectory, relativeToCwd, sourcePolicy, workspaceTarget } from './cli/cli-policy.js';
|
|
10
10
|
import { checkCode } from './cli/cli-scan.js';
|
|
11
|
+
import { terminalSafe } from '../shared/system/terminal-safe.js';
|
|
11
12
|
async function checkPlan(args) {
|
|
12
13
|
const { values, positionals } = parseCommand(args, { json: { type: 'boolean' } });
|
|
13
14
|
if (values.help)
|
|
@@ -70,11 +71,15 @@ async function runPolyglot(args, pillar = 'performance') {
|
|
|
70
71
|
parseMinImpact(values['min-impact']);
|
|
71
72
|
if (!positionals.length)
|
|
72
73
|
throw new Error('Pass at least one file or directory to polyglot.');
|
|
73
|
-
const result = await (await import('./polyglot.js')).checkPolyglot(positionals, pillar);
|
|
74
74
|
const settings = loadSettings({ directory: process.cwd(), explicit: values['loadwise-config'] });
|
|
75
|
-
|
|
76
|
-
//
|
|
75
|
+
const result = await (await import('./polyglot.js')).checkPolyglot(positionals, pillar, settings.isIgnored);
|
|
76
|
+
// The renderer checks skipped-file arrays for exit status. Successful polyglot JSON retains its numeric zero.
|
|
77
77
|
const printable = result;
|
|
78
|
+
if (!values.json) {
|
|
79
|
+
for (const { file, reason } of result.skippedFiles || []) {
|
|
80
|
+
console.error(terminalSafe(`Note: ${file} was skipped (${reason}).`));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
78
83
|
const code = await printResult(printable, { ...values, ignore: [], settings, sourcePillar: pillar });
|
|
79
84
|
notifyEditor(positionals.length === 1 ? positionals[0] : process.cwd());
|
|
80
85
|
return code;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { ts } from '../engine/compiler.js';
|
|
4
4
|
import { unwrapExpression as unwrap } from '../../shared/analysis/ast-semantics.js';
|
|
5
5
|
import { enclosingRequestHandler, parameterName } from '../request/request-handlers.js';
|
|
6
|
+
import { valueSymbol } from '../request/phase5-ast.js';
|
|
6
7
|
import { hasFunctionBody } from '../analysis/function-kinds.js';
|
|
7
8
|
import { classifyExecutionContext } from '../../shared/analysis/execution-context.js';
|
|
8
9
|
const CACHE_RULE_ID = 'unbounded-module-cache';
|
|
@@ -10,15 +11,25 @@ const PAYLOAD_RULE_ID = 'whole-payload-in-memory';
|
|
|
10
11
|
const CACHE_NAME = /(?:cache|memo|lookup)s?$/i;
|
|
11
12
|
// Name parts that mark a key as coming from a request, a tenant or a user, so its space grows with
|
|
12
13
|
// traffic.
|
|
13
|
-
const REQUEST_KEY_PARTS = new Set('id ids uuid tenant user userid workspace workspaceid session email slug token req request args input params query body'.split(' '));
|
|
14
|
+
const REQUEST_KEY_PARTS = new Set('id ids uuid tenant user userid workspace workspaceid session email slug token req request args input params query body locale lang language'.split(' '));
|
|
14
15
|
const CONTEXTUAL_KEY_REASON = 'The key looks like it comes from configuration or code rather than from requests, so the key space may be small.';
|
|
15
16
|
const STARTUP_FUNCTION = /^(?:constructor|onModule[A-Za-z]+|onApplication[A-Za-z]+|register[A-Za-z]*|init[A-Za-z]*|bootstrap[A-Za-z]*|setup[A-Za-z]*)$/;
|
|
16
17
|
const LIST_CACHE_NAME = /cache|memo|history/i;
|
|
17
18
|
const WRITE_METHODS = new Set(['set', 'add', 'push']);
|
|
18
19
|
const READ_METHODS = new Set(['get', 'has']);
|
|
19
|
-
// Any use of these shows the collection is trimmed
|
|
20
|
-
|
|
21
|
-
const
|
|
20
|
+
// Any use of these shows the collection is trimmed or reset, so it may be bounded elsewhere.
|
|
21
|
+
const EVICTION_MEMBERS = new Set(['delete', 'clear', 'shift', 'pop', 'splice', 'unshift']);
|
|
22
|
+
const SIZE_MEMBERS = new Set(['size', 'length']);
|
|
23
|
+
const COMPARISON_TOKENS = new Set([
|
|
24
|
+
ts.SyntaxKind.LessThanToken,
|
|
25
|
+
ts.SyntaxKind.LessThanEqualsToken,
|
|
26
|
+
ts.SyntaxKind.GreaterThanToken,
|
|
27
|
+
ts.SyntaxKind.GreaterThanEqualsToken,
|
|
28
|
+
ts.SyntaxKind.EqualsEqualsToken,
|
|
29
|
+
ts.SyntaxKind.EqualsEqualsEqualsToken,
|
|
30
|
+
ts.SyntaxKind.ExclamationEqualsToken,
|
|
31
|
+
ts.SyntaxKind.ExclamationEqualsEqualsToken,
|
|
32
|
+
]);
|
|
22
33
|
const SCOPE_OPTOUT_ARGUMENTS = /REQUEST|TRANSIENT/;
|
|
23
34
|
const REQUEST_SCOPED_NAMES = /^(?:res|response|reply|next|h)$/;
|
|
24
35
|
const FS_MODULE = /^(?:node:)?fs(?:\/promises)?$/;
|
|
@@ -30,17 +41,34 @@ function isEmptyCollection(initializer) {
|
|
|
30
41
|
const value = unwrap(initializer);
|
|
31
42
|
if (!value)
|
|
32
43
|
return;
|
|
33
|
-
if (ts.isObjectLiteralExpression(value)
|
|
44
|
+
if (ts.isObjectLiteralExpression(value))
|
|
34
45
|
return 'object';
|
|
35
|
-
if (ts.isArrayLiteralExpression(value)
|
|
46
|
+
if (ts.isArrayLiteralExpression(value))
|
|
36
47
|
return 'array';
|
|
37
|
-
if (ts.isNewExpression(value) && ts.isIdentifier(value.expression) &&
|
|
48
|
+
if (ts.isNewExpression(value) && ts.isIdentifier(value.expression) && (value.arguments?.length ?? 0) <= 1) {
|
|
38
49
|
if (value.expression.text === 'Map')
|
|
39
50
|
return 'map';
|
|
40
51
|
if (value.expression.text === 'Set')
|
|
41
52
|
return 'set';
|
|
42
53
|
}
|
|
43
54
|
}
|
|
55
|
+
function isSizeCapCheck(access) {
|
|
56
|
+
let current = access;
|
|
57
|
+
while (current.parent &&
|
|
58
|
+
(ts.isParenthesizedExpression(current.parent) ||
|
|
59
|
+
(ts.isBinaryExpression(current.parent) && !COMPARISON_TOKENS.has(current.parent.operatorToken.kind)))) {
|
|
60
|
+
current = current.parent;
|
|
61
|
+
}
|
|
62
|
+
const parent = current.parent;
|
|
63
|
+
if (!parent)
|
|
64
|
+
return false;
|
|
65
|
+
if (ts.isBinaryExpression(parent) && COMPARISON_TOKENS.has(parent.operatorToken.kind))
|
|
66
|
+
return true;
|
|
67
|
+
if (ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken)
|
|
68
|
+
return true;
|
|
69
|
+
return ((ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) &&
|
|
70
|
+
parent.expression === current);
|
|
71
|
+
}
|
|
44
72
|
function isLiteralKey(key) {
|
|
45
73
|
const value = unwrap(key);
|
|
46
74
|
return !value || ts.isStringLiteralLike(value) || ts.isNumericLiteral(value);
|
|
@@ -58,8 +86,12 @@ function classifyUse(reference) {
|
|
|
58
86
|
const parent = reference.parent;
|
|
59
87
|
if (ts.isPropertyAccessExpression(parent) && parent.expression === reference) {
|
|
60
88
|
const member = parent.name.text;
|
|
61
|
-
if (
|
|
89
|
+
if (EVICTION_MEMBERS.has(member))
|
|
62
90
|
return { kind: 'bounded' };
|
|
91
|
+
if (member === 'length' && isAssignmentTarget(parent))
|
|
92
|
+
return { kind: 'bounded' };
|
|
93
|
+
if (SIZE_MEMBERS.has(member))
|
|
94
|
+
return { kind: isSizeCapCheck(parent) ? 'bounded' : 'read' };
|
|
63
95
|
const call = parent.parent;
|
|
64
96
|
const isCall = ts.isCallExpression(call) && call.expression === parent;
|
|
65
97
|
if (isCall && WRITE_METHODS.has(member)) {
|
|
@@ -164,8 +196,13 @@ function nameParts(text) {
|
|
|
164
196
|
.split(/[^a-z0-9]+/);
|
|
165
197
|
}
|
|
166
198
|
function derivesFromRequest(key, checker) {
|
|
199
|
+
if (ts.isCallExpression(unwrap(key) ?? key))
|
|
200
|
+
return false;
|
|
167
201
|
const declaration = ts.isIdentifier(key) ? checker.getSymbolAtLocation(key)?.valueDeclaration : undefined;
|
|
168
|
-
const
|
|
202
|
+
const declared = declaration && ts.isVariableDeclaration(declaration) ? declaration.initializer : undefined;
|
|
203
|
+
// A call may map a request value onto a small set (`normalizeLocale(locale)`), so only the key's own
|
|
204
|
+
// name counts as evidence; a firm finding needs the raw value in the key.
|
|
205
|
+
const initializer = declared && !ts.isCallExpression(unwrap(declared) ?? declared) ? declared : undefined;
|
|
169
206
|
const text = key.getText() + (initializer ? ' ' + initializer.getText() : '');
|
|
170
207
|
return nameParts(text).some((part) => REQUEST_KEY_PARTS.has(part));
|
|
171
208
|
}
|
|
@@ -259,7 +296,7 @@ function reportGrowth(context, write, label, contextual) {
|
|
|
259
296
|
: undefined;
|
|
260
297
|
context.report(write.anchor, CACHE_RULE_ID, `${label} \`${target.getText()}\` only grows: nothing in this file deletes, clears or size-checks it, so a long-lived process keeps every entry it was given until memory runs out. Bound it with an LRU or TTL (\`lru-cache\`, or evict when \`size\` passes a cap). Ignore if the key space is small and fixed.`, reason);
|
|
261
298
|
}
|
|
262
|
-
function moduleLevelCaches(sourceFile) {
|
|
299
|
+
function moduleLevelCaches(sourceFile, checker) {
|
|
263
300
|
const caches = [];
|
|
264
301
|
for (const statement of sourceFile.statements) {
|
|
265
302
|
if (!ts.isVariableStatement(statement) || isExported(statement))
|
|
@@ -272,7 +309,13 @@ function moduleLevelCaches(sourceFile) {
|
|
|
272
309
|
caches.push({
|
|
273
310
|
name: declaration.name.text,
|
|
274
311
|
shape,
|
|
275
|
-
references: identifierReferences(sourceFile, declaration.name.text, declaration.name)
|
|
312
|
+
references: identifierReferences(sourceFile, declaration.name.text, declaration.name).filter((reference) => {
|
|
313
|
+
const symbol = valueSymbol(reference, checker);
|
|
314
|
+
if (!symbol)
|
|
315
|
+
return false;
|
|
316
|
+
const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
317
|
+
return target?.valueDeclaration === declaration;
|
|
318
|
+
}),
|
|
276
319
|
});
|
|
277
320
|
}
|
|
278
321
|
}
|
|
@@ -301,7 +344,7 @@ function candidatesOf(sourceFile, checker) {
|
|
|
301
344
|
const known = cacheCandidates.get(sourceFile);
|
|
302
345
|
if (known)
|
|
303
346
|
return known;
|
|
304
|
-
const found = [...moduleLevelCaches(sourceFile), ...serviceFieldCaches(sourceFile)].flatMap((candidate) => {
|
|
347
|
+
const found = [...moduleLevelCaches(sourceFile, checker), ...serviceFieldCaches(sourceFile)].flatMap((candidate) => {
|
|
305
348
|
const growth = growingWrite(candidate.references, candidate.shape, candidate.name, checker);
|
|
306
349
|
return growth ? [{ write: growth.write, contextual: growth.contextual, shape: candidate.shape }] : [];
|
|
307
350
|
});
|
|
@@ -116,28 +116,34 @@ function compositeParts(document, schema, segments, seen) {
|
|
|
116
116
|
}
|
|
117
117
|
// Flattens an object schema to `field.path` -> { type, required, enumValues, segments }. oneOf and
|
|
118
118
|
// anyOf are not walked.
|
|
119
|
-
function flattenSchema({ document, rawSchema, segments }, fields = new Map(), prefix = '', depth = 0, seen = new Set()) {
|
|
119
|
+
function flattenSchema({ document, rawSchema, segments }, { fields = new Map(), prefix = '', depth = 0, seen = new Set(), parentReadOnly = false, } = {}) {
|
|
120
120
|
if (depth > maxSchemaDepth)
|
|
121
121
|
return fields;
|
|
122
122
|
const { schema, segments: schemaSegments } = resolveSchema(document, rawSchema, segments);
|
|
123
123
|
if (schema?.type === 'array') {
|
|
124
|
-
return flattenSchema({ document, rawSchema: schema.items, segments: [...schemaSegments, 'items'] }, fields, `${prefix}[]`, depth + 1, seen);
|
|
124
|
+
return flattenSchema({ document, rawSchema: schema.items, segments: [...schemaSegments, 'items'] }, { fields, prefix: `${prefix}[]`, depth: depth + 1, seen, parentReadOnly });
|
|
125
125
|
}
|
|
126
126
|
const visited = new Set(seen);
|
|
127
127
|
const parts = compositeParts(document, schema, schemaSegments, visited);
|
|
128
128
|
const required = new Set(parts.flatMap((part) => (Array.isArray(part.schema.required) ? part.schema.required : [])));
|
|
129
|
+
// allOf composes definitions, so any read-only member makes the property response-only whatever the order.
|
|
130
|
+
const readOnlyNames = new Set(parts.flatMap((part) => Object.entries(part.schema.properties ?? {})
|
|
131
|
+
.filter(([name, property]) => resolveSchema(document, property, [...part.segments, 'properties', name]).schema?.readOnly === true)
|
|
132
|
+
.map(([name]) => name)));
|
|
129
133
|
for (const part of parts) {
|
|
130
134
|
for (const [name, property] of Object.entries(part.schema.properties ?? {})) {
|
|
131
135
|
const propertySegments = [...part.segments, 'properties', name];
|
|
132
136
|
const resolved = resolveSchema(document, property, propertySegments);
|
|
133
137
|
const fieldPath = prefix ? `${prefix}.${name}` : name;
|
|
138
|
+
const readOnly = parentReadOnly || readOnlyNames.has(name);
|
|
134
139
|
fields.set(fieldPath, {
|
|
135
140
|
type: schemaType(document, property),
|
|
136
141
|
required: required.has(name),
|
|
142
|
+
readOnly,
|
|
137
143
|
enumValues: resolved.schema?.enum,
|
|
138
144
|
segments: propertySegments,
|
|
139
145
|
});
|
|
140
|
-
flattenSchema({ document, rawSchema: property, segments: propertySegments }, fields, fieldPath, depth + 1, visited);
|
|
146
|
+
flattenSchema({ document, rawSchema: property, segments: propertySegments }, { fields, prefix: fieldPath, depth: depth + 1, seen: visited, parentReadOnly: readOnly });
|
|
141
147
|
}
|
|
142
148
|
}
|
|
143
149
|
return fields;
|
|
@@ -291,7 +297,10 @@ function compareRequestBody({ report, label }, oldPart, newPart) {
|
|
|
291
297
|
const parentPath = fieldPath.replace(/\.?[^.]+$/, '');
|
|
292
298
|
if (!oldField && parentPath && !oldFields.has(parentPath))
|
|
293
299
|
continue;
|
|
294
|
-
|
|
300
|
+
// A descendant of an optional read-only object only inherits writability; the object itself decides whether it is sent.
|
|
301
|
+
if (oldField?.readOnly && oldFields.get(parentPath)?.readOnly)
|
|
302
|
+
continue;
|
|
303
|
+
if (newField.required && !newField.readOnly && !(oldField?.required && !oldField.readOnly)) {
|
|
295
304
|
report('api-required-input', 'new', newField.segments, `Request field "${fieldPath}" of ${label} is now required. Clients that do not send it get a 400 response.`);
|
|
296
305
|
}
|
|
297
306
|
else if (oldField && requestTypeBreaks(oldField.type, newField.type)) {
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { ts } from '../engine/compiler.js';
|
|
2
2
|
import { analyzeFragment } from './pg-fragments.js';
|
|
3
|
+
import { effectsAtOrdinaryRelease } from './pg-session-release.js';
|
|
4
|
+
import { newSessionEffects, recordSessionEffects, sessionSqlCandidate } from './pg-session-sql.js';
|
|
5
|
+
import { staticMemberName } from '../../shared/analysis/ast-semantics.js';
|
|
3
6
|
const pgPackages = ['pg', '@types/pg', 'pg-pool', '@types/pg-pool'];
|
|
4
7
|
const poolTypes = ['Pool'];
|
|
5
8
|
const queryTypes = ['Pool', 'Client', 'ClientBase', 'PoolClient'];
|
|
@@ -88,35 +91,71 @@ function queryMethod(call) {
|
|
|
88
91
|
: undefined;
|
|
89
92
|
return method?.text === 'query' && call.arguments.length ? method : undefined;
|
|
90
93
|
}
|
|
91
|
-
function
|
|
92
|
-
|
|
93
|
-
const method = queryMethod(call);
|
|
94
|
-
if (!method)
|
|
95
|
-
return;
|
|
96
|
-
// queryMethod found a name, so the callee is a property or element access.
|
|
97
|
-
if (!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access))
|
|
94
|
+
function querySql(call, receiver, context) {
|
|
95
|
+
if (!call.arguments[0])
|
|
98
96
|
return;
|
|
99
97
|
const query = textArgument(call.arguments[0]);
|
|
100
98
|
if (!query)
|
|
101
99
|
return;
|
|
102
|
-
let text;
|
|
103
100
|
if (ts.isStringLiteralLike(query))
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
101
|
+
return query.text;
|
|
102
|
+
const concatenation = ts.isBinaryExpression(query) && query.operatorToken.kind === ts.SyntaxKind.PlusToken;
|
|
103
|
+
const assembled = ts.isTemplateExpression(query) || concatenation;
|
|
104
|
+
if (!assembled && !ts.isIdentifier(query))
|
|
105
|
+
return;
|
|
106
|
+
if (assembled && !usesDriverQuery(call, receiver, queryTypes, context))
|
|
107
|
+
return;
|
|
108
|
+
if (concatenation && !(context.checker.getTypeAtLocation(query).flags & ts.TypeFlags.StringLike))
|
|
109
|
+
return;
|
|
110
|
+
const text = analyzeFragment(query, context.checker);
|
|
111
|
+
return typeof text === 'string' ? text : undefined;
|
|
112
|
+
}
|
|
113
|
+
function reportEffects(effects, node, context, source) {
|
|
114
|
+
const pool = source === 'pool';
|
|
115
|
+
if (effects.advisoryLocks.size > 0) {
|
|
116
|
+
const problem = pool
|
|
117
|
+
? 'This query can acquire a session advisory lock and return its connection to the pool.'
|
|
118
|
+
: 'This release can return the connection to the pool with a session advisory lock still held.';
|
|
119
|
+
context.report(node, 'pg-advisory-lock-session', `${problem} Keep the same checked-out client throughout the protected work and unlock on that client before release. Discard the connection if cleanup fails.`);
|
|
115
120
|
}
|
|
116
|
-
if (
|
|
117
|
-
|
|
118
|
-
|
|
121
|
+
if (effects.subscriptions.size > 0) {
|
|
122
|
+
const problem = pool
|
|
123
|
+
? 'LISTEN subscribes the connection used by this query, but pool.query() returns that connection to the pool.'
|
|
124
|
+
: 'This release can return a PostgreSQL connection that is still subscribed to notifications.';
|
|
125
|
+
context.report(node, 'pg-listen-session', `${problem} Keep one checked-out client for the listener’s lifetime and unsubscribe on that client before release. Discard the connection if cleanup fails.`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function checkSessionRelease(call, receiver, context) {
|
|
129
|
+
if (!ts.isIdentifier(receiver) || !usesDriverQuery(call, receiver, queryTypes, context))
|
|
130
|
+
return;
|
|
131
|
+
const effects = effectsAtOrdinaryRelease(call, receiver, {
|
|
132
|
+
context,
|
|
133
|
+
isCheckout: (checkout, pool) => usesDriverQuery(checkout, pool, poolTypes, context),
|
|
134
|
+
isClientQuery: (query, client) => usesDriverQuery(query, client, queryTypes, context),
|
|
135
|
+
queryText: (query) => querySql(query, receiver, context),
|
|
136
|
+
});
|
|
137
|
+
if (effects)
|
|
138
|
+
reportEffects(effects, call.expression, context, 'release');
|
|
139
|
+
}
|
|
140
|
+
function checkPgIntegrity(call, context) {
|
|
141
|
+
const access = call.expression;
|
|
142
|
+
if (!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access))
|
|
143
|
+
return;
|
|
144
|
+
if (staticMemberName(access) === 'release')
|
|
145
|
+
checkSessionRelease(call, access.expression, context);
|
|
146
|
+
const method = queryMethod(call);
|
|
147
|
+
if (!method)
|
|
148
|
+
return;
|
|
149
|
+
const text = querySql(call, access.expression, context);
|
|
150
|
+
if (text === undefined)
|
|
151
|
+
return;
|
|
152
|
+
if (transactionControl(text) && usesDriverQuery(call, access.expression, poolTypes, context)) {
|
|
119
153
|
context.report(method, 'pg-transaction-on-pool', 'Each pool.query() can run on a different connection, so BEGIN and COMMIT do not share one transaction. Use `const client = await pool.connect()`, run every statement on `client`, and call `client.release()` in finally.');
|
|
120
154
|
}
|
|
155
|
+
if (sessionSqlCandidate.test(text) && usesDriverQuery(call, access.expression, poolTypes, context)) {
|
|
156
|
+
const effects = newSessionEffects();
|
|
157
|
+
if (recordSessionEffects(text, effects))
|
|
158
|
+
reportEffects(effects, method, context, 'pool');
|
|
159
|
+
}
|
|
121
160
|
}
|
|
122
161
|
export { checkPgIntegrity, queryMethod, textArgument, usesDriverQuery, queryTypes };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { ts } from '../engine/compiler.js';
|
|
2
|
+
import { staticMemberName } from '../../shared/analysis/ast-semantics.js';
|
|
3
|
+
import { newSessionEffects, recordSessionEffects } from './pg-session-sql.js';
|
|
4
|
+
function expressionCall(statement) {
|
|
5
|
+
if (!ts.isExpressionStatement(statement))
|
|
6
|
+
return;
|
|
7
|
+
const expression = ts.skipOuterExpressions(statement.expression);
|
|
8
|
+
const call = ts.isAwaitExpression(expression) ? ts.skipOuterExpressions(expression.expression) : expression;
|
|
9
|
+
return ts.isCallExpression(call) ? call : undefined;
|
|
10
|
+
}
|
|
11
|
+
function checkoutDeclaration(declaration, probe) {
|
|
12
|
+
if (!declaration.initializer || !(declaration.parent.flags & ts.NodeFlags.Const))
|
|
13
|
+
return;
|
|
14
|
+
const acquisition = ts.skipOuterExpressions(declaration.initializer);
|
|
15
|
+
if (!ts.isAwaitExpression(acquisition))
|
|
16
|
+
return;
|
|
17
|
+
const call = ts.skipOuterExpressions(acquisition.expression);
|
|
18
|
+
if (!ts.isCallExpression(call))
|
|
19
|
+
return;
|
|
20
|
+
const access = ts.skipOuterExpressions(call.expression);
|
|
21
|
+
if ((!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access)) ||
|
|
22
|
+
staticMemberName(access) !== 'connect')
|
|
23
|
+
return;
|
|
24
|
+
if (call.arguments.length || !probe.isCheckout(call, access.expression))
|
|
25
|
+
return;
|
|
26
|
+
const statement = declaration.parent.parent;
|
|
27
|
+
if (ts.isVariableStatement(statement) && statement.declarationList.declarations.length === 1)
|
|
28
|
+
return statement;
|
|
29
|
+
}
|
|
30
|
+
function visiblePath(start, end) {
|
|
31
|
+
const block = start.parent;
|
|
32
|
+
if (!ts.isBlock(block))
|
|
33
|
+
return;
|
|
34
|
+
const statementsAfterCheckout = block.statements.slice(block.statements.indexOf(start) + 1);
|
|
35
|
+
if (end.parent === block)
|
|
36
|
+
return statementsAfterCheckout.slice(0, statementsAfterCheckout.indexOf(end));
|
|
37
|
+
const cleanup = end.parent;
|
|
38
|
+
if (!ts.isBlock(cleanup) || !ts.isTryStatement(cleanup.parent))
|
|
39
|
+
return;
|
|
40
|
+
const attempt = cleanup.parent;
|
|
41
|
+
if (attempt.parent !== block || attempt.catchClause || attempt.finallyBlock !== cleanup)
|
|
42
|
+
return;
|
|
43
|
+
const position = statementsAfterCheckout.indexOf(attempt);
|
|
44
|
+
if (position < 0)
|
|
45
|
+
return;
|
|
46
|
+
return [
|
|
47
|
+
...statementsAfterCheckout.slice(0, position),
|
|
48
|
+
...attempt.tryBlock.statements,
|
|
49
|
+
...cleanup.statements.slice(0, cleanup.statements.indexOf(end)),
|
|
50
|
+
];
|
|
51
|
+
}
|
|
52
|
+
function statementMentionsClient(statement, client, context) {
|
|
53
|
+
if (ts.isIdentifier(statement) &&
|
|
54
|
+
statement.text === client.name &&
|
|
55
|
+
context.checker.getSymbolAtLocation(statement) === client)
|
|
56
|
+
return true;
|
|
57
|
+
return ts.forEachChild(statement, (child) => statementMentionsClient(child, client, context) || undefined) === true;
|
|
58
|
+
}
|
|
59
|
+
const eventMethods = new Set(['on', 'once', 'off', 'addListener', 'removeListener']);
|
|
60
|
+
function visibleClientSql(statement, client, probe) {
|
|
61
|
+
const call = expressionCall(statement);
|
|
62
|
+
const access = call && ts.skipOuterExpressions(call.expression);
|
|
63
|
+
if (!access || (!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access)))
|
|
64
|
+
return;
|
|
65
|
+
if (probe.context.checker.getSymbolAtLocation(ts.skipOuterExpressions(access.expression)) !== client)
|
|
66
|
+
return;
|
|
67
|
+
const method = staticMemberName(access);
|
|
68
|
+
if (method && eventMethods.has(method)) {
|
|
69
|
+
return call?.arguments.some((argument) => statementMentionsClient(argument, client, probe.context))
|
|
70
|
+
? undefined
|
|
71
|
+
: '';
|
|
72
|
+
}
|
|
73
|
+
const expression = ts.isExpressionStatement(statement) && ts.skipOuterExpressions(statement.expression);
|
|
74
|
+
if (method === 'query' &&
|
|
75
|
+
expression &&
|
|
76
|
+
ts.isAwaitExpression(expression) &&
|
|
77
|
+
call &&
|
|
78
|
+
probe.isClientQuery(call, access.expression))
|
|
79
|
+
return probe.queryText(call);
|
|
80
|
+
}
|
|
81
|
+
function releaseStatement(call) {
|
|
82
|
+
if (ts.isExpressionStatement(call.parent))
|
|
83
|
+
return call.parent;
|
|
84
|
+
if (ts.isAwaitExpression(call.parent) && ts.isExpressionStatement(call.parent.parent))
|
|
85
|
+
return call.parent.parent;
|
|
86
|
+
}
|
|
87
|
+
// Follow only straight-line operations and an explicit finally block on one local checkout.
|
|
88
|
+
// Unknown control flow or a reference that could hand off the client ends the proof.
|
|
89
|
+
export function effectsAtOrdinaryRelease(call, receiver, probe) {
|
|
90
|
+
const destroy = call.arguments[0];
|
|
91
|
+
if (destroy && ts.skipOuterExpressions(destroy).kind !== ts.SyntaxKind.FalseKeyword)
|
|
92
|
+
return;
|
|
93
|
+
const client = probe.context.checker.getSymbolAtLocation(receiver);
|
|
94
|
+
const declaration = client?.valueDeclaration;
|
|
95
|
+
const end = releaseStatement(call);
|
|
96
|
+
if (!client || !declaration || !ts.isVariableDeclaration(declaration) || !end)
|
|
97
|
+
return;
|
|
98
|
+
const start = checkoutDeclaration(declaration, probe);
|
|
99
|
+
const statements = start && visiblePath(start, end);
|
|
100
|
+
if (!start || !statements)
|
|
101
|
+
return;
|
|
102
|
+
if (ts.isBlock(start.parent) &&
|
|
103
|
+
start.parent.statements.some((statement) => statement.end <= start.getStart() && statementMentionsClient(statement, client, probe.context)))
|
|
104
|
+
return;
|
|
105
|
+
const effects = newSessionEffects();
|
|
106
|
+
for (const statement of statements) {
|
|
107
|
+
if (!statementMentionsClient(statement, client, probe.context))
|
|
108
|
+
continue;
|
|
109
|
+
const sql = visibleClientSql(statement, client, probe);
|
|
110
|
+
if (sql === undefined || !recordSessionEffects(sql, effects))
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
return effects;
|
|
114
|
+
}
|