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.
- package/PERFORMANCE.md +31 -6
- package/README.md +580 -1024
- package/bin/loadwise.js +4 -0
- package/lib/accessibility/frontend-detect.js +2 -1
- package/lib/accessibility/rule-ids.js +12 -9
- package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
- package/lib/editor/actions.js +117 -0
- package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
- package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
- package/lib/editor/diagnostics.js +365 -0
- package/lib/editor/dismissals.js +111 -0
- package/lib/editor/editor-document.js +99 -0
- package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
- package/lib/editor/fix-edits.js +200 -0
- package/lib/editor/language-server.js +437 -0
- package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
- package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
- package/lib/editor/perf-watch.js +78 -0
- package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
- package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
- package/lib/editor/scan-session.js +334 -0
- package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
- package/lib/editor/server-commands.js +232 -0
- package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
- package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
- package/lib/editor/types/dismissal.js +1 -0
- package/lib/editor/types/fix-example.js +1 -0
- package/lib/editor/types/source-document.js +1 -0
- package/lib/editor/workspace-files.js +78 -0
- package/lib/editor/workspace-paths.js +22 -0
- package/lib/maintainability/analyze-source.js +2 -0
- package/lib/maintainability/apply-fix.js +1 -1
- package/lib/maintainability/cli.js +1 -1
- package/lib/maintainability/examples.js +58 -41
- package/lib/maintainability/rule-ids.js +29 -14
- package/lib/maintainability/scan-changed.js +3 -0
- package/lib/maintainability/scan.js +13 -9
- package/lib/maintainability/tsconfig-strict.js +69 -0
- package/lib/maintainability/type-safety-hygiene.js +204 -0
- package/lib/performance/analyze.js +2 -0
- package/lib/performance/cli-arguments.js +0 -2
- package/lib/performance/cli-policy.js +17 -9
- package/lib/performance/cli-scan.js +10 -8
- package/lib/performance/cli.js +4 -23
- package/lib/performance/editor-signal.js +1 -1
- package/lib/performance/finding-text.js +3 -3
- package/lib/performance/fix-cli.js +1 -1
- package/lib/performance/frontend-perf.js +7 -0
- package/lib/performance/frontend-render-perf.js +200 -0
- package/lib/performance/llm-max-tokens.js +56 -0
- package/lib/performance/native.js +46 -26
- package/lib/performance/polyglot.js +22 -1
- package/lib/performance/pooling.js +38 -23
- package/lib/performance/projects.js +42 -21
- package/lib/performance/rule-ids.js +236 -222
- package/lib/performance/site-fixes/database.js +3 -1
- package/lib/performance/site-fixes/integrity.js +15 -1
- package/lib/performance/source-inputs.js +18 -6
- package/lib/performance/unscanned-javascript.js +66 -19
- package/lib/reliability/analyze.js +12 -0
- package/lib/reliability/child-process.js +106 -0
- package/lib/reliability/error-values.js +177 -0
- package/lib/reliability/pool-timeout.js +79 -0
- package/lib/reliability/react-bugs.js +602 -0
- package/lib/reliability/resource-leaks.js +3 -6
- package/lib/reliability/rule-ids.js +169 -127
- package/lib/reliability/switch-exhaustive.js +284 -0
- package/lib/reliability/uncaught-exception.js +223 -0
- package/lib/security/auth-crypto/rule-ids.js +3 -2
- package/lib/security/cli.js +6 -5
- package/lib/security/deps/rule-ids.js +1 -0
- package/lib/security/examples/auth-crypto.cjs +5 -4
- package/lib/security/examples/deps.cjs +1 -0
- package/lib/security/examples/exposure.cjs +55 -42
- package/lib/security/examples/files.cjs +1 -0
- package/lib/security/examples/injection.cjs +1 -0
- package/lib/security/examples/moved.cjs +5 -4
- package/lib/security/examples/request-forgery.cjs +1 -0
- package/lib/security/exposure/client-env.js +113 -0
- package/lib/security/exposure/frontend-security.js +12 -10
- package/lib/security/exposure/index.js +14 -3
- package/lib/security/exposure/jsx-url.js +267 -0
- package/lib/security/exposure/next-image-config.js +34 -0
- package/lib/security/exposure/package-manifest.js +45 -0
- package/lib/security/exposure/react-version.js +45 -0
- package/lib/security/exposure/rule-ids.js +16 -12
- package/lib/security/files/index.js +1 -1
- package/lib/security/files/rule-ids.js +1 -0
- package/lib/security/injection/code.js +24 -10
- package/lib/security/injection/command.js +81 -28
- package/lib/security/injection/nosql.js +109 -22
- package/lib/security/injection/redos.js +152 -308
- package/lib/security/injection/regex-pattern.js +290 -0
- package/lib/security/injection/regex.js +30 -11
- package/lib/security/injection/rule-ids.js +2 -1
- package/lib/security/injection/shared.js +19 -1
- package/lib/security/injection/sql.js +83 -2
- package/lib/security/request-forgery/rule-ids.js +1 -0
- package/lib/security/rule-descriptions.js +36 -32
- package/lib/security/rule-ids.js +74 -67
- package/lib/security/taint/filename-guard.js +3 -1
- package/lib/security/taint/guards.js +84 -10
- package/lib/security/taint/index.js +124 -13
- package/lib/security/taint/propagate.js +10 -7
- package/lib/security/taint/sanitizers.js +7 -3
- package/lib/security/taint/sources.js +6 -3
- package/lib/security/taint/summaries.js +13 -1
- package/lib/security/taint/url-parts.js +14 -5
- package/lib/shared/agent-session.js +2 -2
- package/lib/shared/check.js +9 -6
- package/lib/shared/explain.js +5 -5
- package/lib/shared/fix-convergence.js +1 -1
- package/lib/shared/formats/finding-location.js +6 -2
- package/lib/shared/formats/sarif.js +3 -3
- package/lib/shared/heap-limit.js +6 -0
- package/lib/shared/pillars.js +7 -7
- package/lib/shared/rule-docs.js +12 -0
- package/lib/shared/scan-cache.js +0 -1
- package/lib/shared/workspaces.js +31 -9
- package/package.json +25 -17
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/schema/loadwise.config.schema.json +44 -0
- package/editor/README.md +0 -47
- package/examples/redis-keys.otlp.json +0 -22
- package/lib/maintainability/notify-editor.js +0 -1
- package/lib/performance/editor-report.js +0 -191
- package/lib/performance/editor-setup.js +0 -189
- package/lib/performance/editor-watch-supervisor.js +0 -104
- package/lib/performance/editor-watch.js +0 -193
- package/lib/performance/notify-editor.js +0 -1
- package/lib/performance/recursive-watch.js +0 -181
- /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// A `switch` over a union of string or number literals, or over an enum, that names only some members and has no
|
|
2
|
+
// `default`. The rule fires only where the gap shows: the function falls off its end after returning a value in other
|
|
3
|
+
// branches, or a variable declared without a value is read after the switch. Elsewhere a missing case may be meant.
|
|
4
|
+
import { ts } from '../performance/compiler.js';
|
|
5
|
+
import { walkNodes } from './walk.js';
|
|
6
|
+
import { isIgnoredSource } from './source-helpers.js';
|
|
7
|
+
const minimumLiteralMembers = 2;
|
|
8
|
+
const emptinessFlags = ts.TypeFlags.Undefined | ts.TypeFlags.Null;
|
|
9
|
+
const literalFlags = ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral;
|
|
10
|
+
const emptyValueFlags = ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never;
|
|
11
|
+
function literalMember(type) {
|
|
12
|
+
if (!(type.flags & literalFlags) || (typeof type.value !== 'string' && typeof type.value !== 'number'))
|
|
13
|
+
return;
|
|
14
|
+
return { key: `${typeof type.value}:${type.value}`, label: JSON.stringify(type.value) };
|
|
15
|
+
}
|
|
16
|
+
// The members of the switched value, or undefined when the type is not a plain union of string or number literals
|
|
17
|
+
// (so booleans, bigints and mixed object unions are left alone).
|
|
18
|
+
function literalMembers(type) {
|
|
19
|
+
if (!type.isUnion() || !type.types)
|
|
20
|
+
return;
|
|
21
|
+
const members = [];
|
|
22
|
+
for (const member of type.types) {
|
|
23
|
+
if (member.flags & emptinessFlags)
|
|
24
|
+
continue;
|
|
25
|
+
const literal = literalMember(member);
|
|
26
|
+
if (!literal)
|
|
27
|
+
return;
|
|
28
|
+
members.push(literal);
|
|
29
|
+
}
|
|
30
|
+
return members.length >= minimumLiteralMembers ? members : undefined;
|
|
31
|
+
}
|
|
32
|
+
function coveredKeys(statement, checker) {
|
|
33
|
+
const covered = new Set();
|
|
34
|
+
for (const clause of statement.caseBlock.clauses) {
|
|
35
|
+
if (!ts.isCaseClause(clause))
|
|
36
|
+
return;
|
|
37
|
+
const caseType = checker.getTypeAtLocation(clause.expression);
|
|
38
|
+
// `case null` and `case undefined` name no string or number member, so they cover none of them.
|
|
39
|
+
if (caseType.flags & emptinessFlags)
|
|
40
|
+
continue;
|
|
41
|
+
const literal = literalMember(caseType);
|
|
42
|
+
// A case that is not a literal (a variable, a call) could cover anything.
|
|
43
|
+
if (!literal)
|
|
44
|
+
return;
|
|
45
|
+
covered.add(literal.key);
|
|
46
|
+
}
|
|
47
|
+
return covered;
|
|
48
|
+
}
|
|
49
|
+
function statementsOf(clauses) {
|
|
50
|
+
return clauses.flatMap((clause) => [...clause.statements]);
|
|
51
|
+
}
|
|
52
|
+
// A returned value that is itself void, undefined or never (a call to a `Promise<void>` helper or one that always throws)
|
|
53
|
+
// makes the fall-off harmless. `null` is a real value, so falling off the end instead of returning it is a gap.
|
|
54
|
+
function returnsValueWithin(root, checker) {
|
|
55
|
+
let found = false;
|
|
56
|
+
const visit = (node) => {
|
|
57
|
+
if (found || ts.isFunctionLike(node) || ts.isClassLike(node))
|
|
58
|
+
return;
|
|
59
|
+
if (ts.isReturnStatement(node) && node.expression)
|
|
60
|
+
found = !isEmptyValue(node.expression, checker);
|
|
61
|
+
else
|
|
62
|
+
ts.forEachChild(node, visit);
|
|
63
|
+
};
|
|
64
|
+
ts.forEachChild(root, visit);
|
|
65
|
+
return found;
|
|
66
|
+
}
|
|
67
|
+
const undefinedAdmittingFlags = ts.TypeFlags.Undefined | ts.TypeFlags.Unknown;
|
|
68
|
+
function unionAdmitsUndefined(type) {
|
|
69
|
+
return type.isUnion() && (type.types ?? []).some((member) => (member.flags & ts.TypeFlags.Undefined) !== 0);
|
|
70
|
+
}
|
|
71
|
+
// Only an async function unwraps a returned promise; a plain function hands the promise itself to its caller.
|
|
72
|
+
function isInsideAsyncFunction(node) {
|
|
73
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
74
|
+
if (ts.isFunctionLike(current)) {
|
|
75
|
+
return (ts.canHaveModifiers(current) &&
|
|
76
|
+
!!ts.getModifiers(current)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
function isEmptyValue(expression, checker) {
|
|
82
|
+
const type = checker.getTypeAtLocation(expression);
|
|
83
|
+
const awaited = isInsideAsyncFunction(expression) ? (checker.getAwaitedType(type) ?? type) : type;
|
|
84
|
+
return (awaited.flags & emptyValueFlags) !== 0;
|
|
85
|
+
}
|
|
86
|
+
function enclosingFunctionBody(node) {
|
|
87
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
88
|
+
if (ts.isFunctionLike(current))
|
|
89
|
+
return 'body' in current && current.body && ts.isBlock(current.body) ? current.body : undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// A `finally` block that always returns or throws replaces whatever the try and catch blocks did.
|
|
93
|
+
function finallyAlwaysExits(statement) {
|
|
94
|
+
return (statement.finallyBlock?.statements ?? []).some((inner) => ts.isReturnStatement(inner) || ts.isThrowStatement(inner));
|
|
95
|
+
}
|
|
96
|
+
// Whether nothing runs after the statement before the function ends: it closes its block, or the branch or try block
|
|
97
|
+
// that does.
|
|
98
|
+
function endsFunctionBody(statement, body) {
|
|
99
|
+
let current = statement;
|
|
100
|
+
while (current !== body) {
|
|
101
|
+
const parent = current.parent;
|
|
102
|
+
if (ts.isBlock(parent) && parent.statements.at(-1) !== current)
|
|
103
|
+
return false;
|
|
104
|
+
if (ts.isTryStatement(parent) && (parent.finallyBlock === current || finallyAlwaysExits(parent)))
|
|
105
|
+
return false;
|
|
106
|
+
const passesThrough = ts.isBlock(parent) || ts.isIfStatement(parent) || ts.isTryStatement(parent) || ts.isCatchClause(parent);
|
|
107
|
+
if (!passesThrough)
|
|
108
|
+
return false;
|
|
109
|
+
current = parent;
|
|
110
|
+
}
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
// The switch can be the last thing the function runs, so a value that matches no case leaves the function without a
|
|
114
|
+
// return value.
|
|
115
|
+
function fallsOffFunctionEnd(statement, checker) {
|
|
116
|
+
const body = enclosingFunctionBody(statement);
|
|
117
|
+
return body !== undefined && endsFunctionBody(statement, body) && returnsValueWithin(statement, checker);
|
|
118
|
+
}
|
|
119
|
+
function isPlainAssignment(node) {
|
|
120
|
+
return ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken;
|
|
121
|
+
}
|
|
122
|
+
// The variable declarations an assignment target writes, including those inside destructuring patterns.
|
|
123
|
+
function assignedDeclarations(target, checker) {
|
|
124
|
+
if (ts.isIdentifier(target)) {
|
|
125
|
+
const declaration = checker.getSymbolAtLocation(target)?.valueDeclaration;
|
|
126
|
+
return declaration ? [declaration] : [];
|
|
127
|
+
}
|
|
128
|
+
if (ts.isShorthandPropertyAssignment(target)) {
|
|
129
|
+
const declaration = checker.getShorthandAssignmentValueSymbol(target)?.valueDeclaration;
|
|
130
|
+
return declaration ? [declaration] : [];
|
|
131
|
+
}
|
|
132
|
+
if (ts.isPropertyAssignment(target))
|
|
133
|
+
return assignedDeclarations(target.initializer, checker);
|
|
134
|
+
if (ts.isSpreadAssignment(target) || ts.isSpreadElement(target))
|
|
135
|
+
return assignedDeclarations(target.expression, checker);
|
|
136
|
+
if (isPlainAssignment(target))
|
|
137
|
+
return assignedDeclarations(target.left, checker);
|
|
138
|
+
if (ts.isObjectLiteralExpression(target))
|
|
139
|
+
return target.properties.flatMap((property) => assignedDeclarations(property, checker));
|
|
140
|
+
if (ts.isArrayLiteralExpression(target))
|
|
141
|
+
return target.elements.flatMap((element) => assignedDeclarations(element, checker));
|
|
142
|
+
return [];
|
|
143
|
+
}
|
|
144
|
+
function isWithin(node, container) {
|
|
145
|
+
return node.pos >= container.pos && node.end <= container.end;
|
|
146
|
+
}
|
|
147
|
+
function assignedWithin(statement, checker) {
|
|
148
|
+
const declarations = new Set();
|
|
149
|
+
walkNodes(statement.caseBlock, (node) => {
|
|
150
|
+
if (!isPlainAssignment(node))
|
|
151
|
+
return;
|
|
152
|
+
for (const declaration of assignedDeclarations(node.left, checker))
|
|
153
|
+
declarations.add(declaration);
|
|
154
|
+
});
|
|
155
|
+
return declarations;
|
|
156
|
+
}
|
|
157
|
+
const conditionalFlowKinds = new Set([
|
|
158
|
+
ts.SyntaxKind.IfStatement,
|
|
159
|
+
ts.SyntaxKind.ConditionalExpression,
|
|
160
|
+
ts.SyntaxKind.ForStatement,
|
|
161
|
+
ts.SyntaxKind.ForInStatement,
|
|
162
|
+
ts.SyntaxKind.ForOfStatement,
|
|
163
|
+
ts.SyntaxKind.WhileStatement,
|
|
164
|
+
ts.SyntaxKind.DoStatement,
|
|
165
|
+
ts.SyntaxKind.CaseClause,
|
|
166
|
+
ts.SyntaxKind.DefaultClause,
|
|
167
|
+
ts.SyntaxKind.TryStatement,
|
|
168
|
+
ts.SyntaxKind.CatchClause,
|
|
169
|
+
]);
|
|
170
|
+
const shortCircuitOperators = new Set([
|
|
171
|
+
ts.SyntaxKind.AmpersandAmpersandToken,
|
|
172
|
+
ts.SyntaxKind.BarBarToken,
|
|
173
|
+
ts.SyntaxKind.QuestionQuestionToken,
|
|
174
|
+
]);
|
|
175
|
+
// The condition of an `if` or a ternary is evaluated on every path; only its branches are conditional.
|
|
176
|
+
function isConditionOf(statement, child) {
|
|
177
|
+
if (ts.isIfStatement(statement))
|
|
178
|
+
return statement.expression === child;
|
|
179
|
+
return ts.isConditionalExpression(statement) && statement.condition === child;
|
|
180
|
+
}
|
|
181
|
+
// Whether the node runs on every path through the function body: not behind a branch, a loop, a short-circuit or a nested
|
|
182
|
+
// function that may never be called.
|
|
183
|
+
function runsUnconditionally(node, body) {
|
|
184
|
+
for (let current = node; current !== body; current = current.parent) {
|
|
185
|
+
const parent = current.parent;
|
|
186
|
+
if (ts.isFunctionLike(parent) || ts.isClassLike(parent))
|
|
187
|
+
return false;
|
|
188
|
+
if (conditionalFlowKinds.has(parent.kind) && !isConditionOf(parent, current))
|
|
189
|
+
return false;
|
|
190
|
+
if (ts.isBinaryExpression(parent) &&
|
|
191
|
+
parent.right === current &&
|
|
192
|
+
shortCircuitOperators.has(parent.operatorToken.kind))
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
function isAssignmentTarget(identifier) {
|
|
198
|
+
const parent = identifier.parent;
|
|
199
|
+
return isPlainAssignment(parent) && parent.left === identifier;
|
|
200
|
+
}
|
|
201
|
+
// The declaration a read of the identifier resolves to. A declaration's own name is not a read, and a shorthand
|
|
202
|
+
// `{ value }` reads the variable `value` unless it sits in a destructuring target such as `({ value } = box)`.
|
|
203
|
+
function readDeclaration(identifier, checker) {
|
|
204
|
+
const parent = identifier.parent;
|
|
205
|
+
if (ts.isVariableDeclaration(parent) && parent.name === identifier)
|
|
206
|
+
return;
|
|
207
|
+
if (ts.isShorthandPropertyAssignment(parent) && parent.name === identifier) {
|
|
208
|
+
const isDestructuringTarget = ts.findAncestor(parent, (ancestor) => isPlainAssignment(ancestor) && isWithin(parent, ancestor.left));
|
|
209
|
+
return isDestructuringTarget ? undefined : checker.getShorthandAssignmentValueSymbol(parent)?.valueDeclaration;
|
|
210
|
+
}
|
|
211
|
+
return checker.getSymbolAtLocation(identifier)?.valueDeclaration;
|
|
212
|
+
}
|
|
213
|
+
// Whether the declaration has no value of its own, no assignment outside the switch can supply one, and the code after
|
|
214
|
+
// the switch reads it.
|
|
215
|
+
function leavesUnsetValueRead(declaration, statement, body, checker) {
|
|
216
|
+
if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name) || declaration.initializer) {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
if (!isWithin(declaration, body))
|
|
220
|
+
return false;
|
|
221
|
+
// A type that admits undefined says the code already handles the unset case.
|
|
222
|
+
const declaredType = checker.getTypeAtLocation(declaration.name);
|
|
223
|
+
if ((declaredType.flags & undefinedAdmittingFlags) !== 0 || unionAdmitsUndefined(declaredType))
|
|
224
|
+
return false;
|
|
225
|
+
let assignedElsewhere = false;
|
|
226
|
+
let readAfter = false;
|
|
227
|
+
walkNodes(body, (node) => {
|
|
228
|
+
if (isPlainAssignment(node) && !isWithin(node, statement.caseBlock) && runsUnconditionally(node, body)) {
|
|
229
|
+
assignedElsewhere = assignedElsewhere || assignedDeclarations(node.left, checker).includes(declaration);
|
|
230
|
+
}
|
|
231
|
+
if (!ts.isIdentifier(node) || node.getStart() < statement.end || isAssignmentTarget(node))
|
|
232
|
+
return;
|
|
233
|
+
// `typeof value` in a type position names the variable without reading it.
|
|
234
|
+
if (ts.findAncestor(node, ts.isTypeQueryNode))
|
|
235
|
+
return;
|
|
236
|
+
readAfter = readAfter || (readDeclaration(node, checker) === declaration && runsUnconditionally(node, body));
|
|
237
|
+
});
|
|
238
|
+
return readAfter && !assignedElsewhere;
|
|
239
|
+
}
|
|
240
|
+
function leavesVariableUnset(statement, checker) {
|
|
241
|
+
const body = enclosingFunctionBody(statement);
|
|
242
|
+
if (!body)
|
|
243
|
+
return false;
|
|
244
|
+
for (const declaration of assignedWithin(statement, checker)) {
|
|
245
|
+
if (leavesUnsetValueRead(declaration, statement, body, checker))
|
|
246
|
+
return true;
|
|
247
|
+
}
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
function checkSwitch(statement, sourceFile, file, checker) {
|
|
251
|
+
if (statement.caseBlock.clauses.some(ts.isDefaultClause))
|
|
252
|
+
return;
|
|
253
|
+
const members = literalMembers(checker.getTypeAtLocation(statement.expression));
|
|
254
|
+
const covered = members && coveredKeys(statement, checker);
|
|
255
|
+
if (!members || !covered || statementsOf(statement.caseBlock.clauses).length === 0)
|
|
256
|
+
return;
|
|
257
|
+
const missing = members.filter((member) => !covered.has(member.key));
|
|
258
|
+
if (missing.length === 0)
|
|
259
|
+
return;
|
|
260
|
+
if (!fallsOffFunctionEnd(statement, checker) && !leavesVariableUnset(statement, checker))
|
|
261
|
+
return;
|
|
262
|
+
const position = sourceFile.getLineAndCharacterOfPosition(statement.getStart(sourceFile));
|
|
263
|
+
return {
|
|
264
|
+
file,
|
|
265
|
+
line: position.line + 1,
|
|
266
|
+
column: position.character + 1,
|
|
267
|
+
ruleId: 'switch-not-exhaustive',
|
|
268
|
+
message: `This switch has no case for ${missing.map((member) => member.label).join(', ')} and no default, so that value leaves the result undefined. Add the missing cases, or a default that throws.`,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function checkSwitchExhaustive(sourceFile, file, checker) {
|
|
272
|
+
if (!sourceFile.text.includes('switch') || isIgnoredSource(sourceFile, file))
|
|
273
|
+
return [];
|
|
274
|
+
const findings = [];
|
|
275
|
+
walkNodes(sourceFile, (node) => {
|
|
276
|
+
if (!ts.isSwitchStatement(node))
|
|
277
|
+
return;
|
|
278
|
+
const finding = checkSwitch(node, sourceFile, file, checker);
|
|
279
|
+
if (finding)
|
|
280
|
+
findings.push(finding);
|
|
281
|
+
});
|
|
282
|
+
return findings;
|
|
283
|
+
}
|
|
284
|
+
export { checkSwitchExhaustive };
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// `process.on('uncaughtException', handler)` where the handler only logs. Node keeps running after such a handler, but
|
|
2
|
+
// the process is in an unknown state (half-written data, leaked handles), so the handler has to end the process.
|
|
3
|
+
import { ts } from '../performance/compiler.js';
|
|
4
|
+
import { walkNodes } from './walk.js';
|
|
5
|
+
import { isIgnoredSource } from './source-helpers.js';
|
|
6
|
+
const listenerMethods = new Set(['on', 'once', 'addListener', 'prependListener', 'prependOnceListener']);
|
|
7
|
+
const processModuleNames = new Set(['process', 'node:process']);
|
|
8
|
+
// Calls that end the process or start its shutdown, however the project names them.
|
|
9
|
+
const shutdownCallName = /exit|shutdown|terminate|abort|kill|crash|die|stop|close|destroy/i;
|
|
10
|
+
const promiseReactionName = /^(?:then|catch|finally)$/;
|
|
11
|
+
// Callbacks handed to these run after the surrounding try block has finished, so an enclosing catch cannot see them.
|
|
12
|
+
const deferredCallName = /^(?:setTimeout|setInterval|setImmediate|nextTick|queueMicrotask|then|catch|finally|on|once)$/;
|
|
13
|
+
function isProcessModuleImport(declaration) {
|
|
14
|
+
const importDeclaration = ts.findAncestor(declaration, ts.isImportDeclaration);
|
|
15
|
+
return (importDeclaration !== undefined &&
|
|
16
|
+
ts.isStringLiteralLike(importDeclaration.moduleSpecifier) &&
|
|
17
|
+
processModuleNames.has(importDeclaration.moduleSpecifier.text));
|
|
18
|
+
}
|
|
19
|
+
// The Node `process`: the global from the Node typings, or an import of `node:process`. A local variable of that name
|
|
20
|
+
// is some other object.
|
|
21
|
+
function isNodeProcess(identifier, checker) {
|
|
22
|
+
const declarations = checker.getSymbolAtLocation(identifier)?.declarations ?? [];
|
|
23
|
+
return declarations.every((declaration) => declaration.getSourceFile().isDeclarationFile || isProcessModuleImport(declaration));
|
|
24
|
+
}
|
|
25
|
+
function isProcessListenerCall(call, checker) {
|
|
26
|
+
const callee = ts.skipOuterExpressions(call.expression);
|
|
27
|
+
if (!ts.isPropertyAccessExpression(callee) || !listenerMethods.has(callee.name.text))
|
|
28
|
+
return false;
|
|
29
|
+
const receiver = ts.skipOuterExpressions(callee.expression);
|
|
30
|
+
const [event] = call.arguments;
|
|
31
|
+
return (ts.isIdentifier(receiver) &&
|
|
32
|
+
receiver.text === 'process' &&
|
|
33
|
+
isNodeProcess(receiver, checker) &&
|
|
34
|
+
event !== undefined &&
|
|
35
|
+
ts.isStringLiteralLike(event) &&
|
|
36
|
+
event.text === 'uncaughtException');
|
|
37
|
+
}
|
|
38
|
+
function isProcessReference(node, checker) {
|
|
39
|
+
const expression = ts.skipOuterExpressions(node);
|
|
40
|
+
return ts.isIdentifier(expression) && expression.text === 'process' && isNodeProcess(expression, checker);
|
|
41
|
+
}
|
|
42
|
+
function isExitCodeAssignment(node, checker) {
|
|
43
|
+
if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
|
|
44
|
+
return false;
|
|
45
|
+
return (ts.isPropertyAccessExpression(node.left) &&
|
|
46
|
+
node.left.name.text === 'exitCode' &&
|
|
47
|
+
isProcessReference(node.left.expression, checker));
|
|
48
|
+
}
|
|
49
|
+
// Assigning `undefined` or `null` clears the exit status instead of setting one.
|
|
50
|
+
function clearsExitCode(assignment) {
|
|
51
|
+
const value = ts.skipOuterExpressions(assignment.right);
|
|
52
|
+
return value.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(value) && value.text === 'undefined');
|
|
53
|
+
}
|
|
54
|
+
function calleeName(call) {
|
|
55
|
+
const callee = ts.skipOuterExpressions(call.expression);
|
|
56
|
+
if (ts.isIdentifier(callee))
|
|
57
|
+
return callee.text;
|
|
58
|
+
return ts.isPropertyAccessExpression(callee) ? callee.name.text : undefined;
|
|
59
|
+
}
|
|
60
|
+
// A function written inside the handler runs only when called or handed to a call (a scheduled shutdown such as
|
|
61
|
+
// `setTimeout(() => process.exit(1))`); one that is merely declared or stored does not end the process.
|
|
62
|
+
function isDormantFunction(node) {
|
|
63
|
+
if (!ts.isFunctionLike(node))
|
|
64
|
+
return false;
|
|
65
|
+
let parent = node.parent;
|
|
66
|
+
// `(() => { ... })()` wraps the function in parentheses before the call.
|
|
67
|
+
while (ts.isParenthesizedExpression(parent))
|
|
68
|
+
parent = parent.parent;
|
|
69
|
+
return !ts.isCallExpression(parent) && !ts.isNewExpression(parent);
|
|
70
|
+
}
|
|
71
|
+
// Only the callback positions of a deferring call; later arguments such as `setTimeout(callback, delay, data)` are data.
|
|
72
|
+
function callbackArguments(call, name) {
|
|
73
|
+
if (name === 'then')
|
|
74
|
+
return call.arguments.slice(0, 2);
|
|
75
|
+
if (name === 'on' || name === 'once')
|
|
76
|
+
return call.arguments.slice(1, 2);
|
|
77
|
+
return call.arguments.slice(0, 1);
|
|
78
|
+
}
|
|
79
|
+
function isDeferredCallback(node) {
|
|
80
|
+
return (ts.isFunctionLike(node) && ts.isCallExpression(node.parent) && deferredCallName.test(calleeName(node.parent) ?? ''));
|
|
81
|
+
}
|
|
82
|
+
// Callbacks of `then`, `catch` and `finally` run as promise reactions, so a throw in one rejects the derived promise.
|
|
83
|
+
function isPromiseReaction(node) {
|
|
84
|
+
return (ts.isFunctionLike(node) &&
|
|
85
|
+
ts.isCallExpression(node.parent) &&
|
|
86
|
+
promiseReactionName.test(calleeName(node.parent) ?? ''));
|
|
87
|
+
}
|
|
88
|
+
// A Promise executor's throw becomes a rejection instead of leaving the handler.
|
|
89
|
+
function isPromiseExecutor(node) {
|
|
90
|
+
return (ts.isFunctionLike(node) &&
|
|
91
|
+
ts.isNewExpression(node.parent) &&
|
|
92
|
+
ts.isIdentifier(node.parent.expression) &&
|
|
93
|
+
node.parent.expression.text === 'Promise');
|
|
94
|
+
}
|
|
95
|
+
// A `return` in a finally block cancels a throw from the try or catch block.
|
|
96
|
+
function finallyReturns(statement) {
|
|
97
|
+
return (statement.finallyBlock?.statements ?? []).some((inner) => ts.isReturnStatement(inner));
|
|
98
|
+
}
|
|
99
|
+
// A `let` or `var` may have been reassigned, so its initializer is not trustworthy.
|
|
100
|
+
function isMutableVariable(declaration) {
|
|
101
|
+
return (declaration !== undefined &&
|
|
102
|
+
ts.isVariableDeclaration(declaration) &&
|
|
103
|
+
!(ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const));
|
|
104
|
+
}
|
|
105
|
+
// An async function turns a throw into a rejected promise instead of letting it escape.
|
|
106
|
+
function isAsyncFunction(node) {
|
|
107
|
+
return (ts.canHaveModifiers(node) &&
|
|
108
|
+
(ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword));
|
|
109
|
+
}
|
|
110
|
+
function functionOf(declaration) {
|
|
111
|
+
if (!declaration || declaration.getSourceFile().isDeclarationFile)
|
|
112
|
+
return;
|
|
113
|
+
if (ts.isFunctionDeclaration(declaration) || ts.isMethodDeclaration(declaration))
|
|
114
|
+
return declaration;
|
|
115
|
+
const initializer = ts.isVariableDeclaration(declaration) || ts.isPropertyAssignment(declaration) ? declaration.initializer : undefined;
|
|
116
|
+
return initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))
|
|
117
|
+
? initializer
|
|
118
|
+
: undefined;
|
|
119
|
+
}
|
|
120
|
+
// The function a call invokes when it is written inside the handler, so a helper that rethrows is read at its call site.
|
|
121
|
+
function localFunction(expression, handler, checker) {
|
|
122
|
+
const callee = ts.skipOuterExpressions(expression);
|
|
123
|
+
if (!ts.isIdentifier(callee))
|
|
124
|
+
return;
|
|
125
|
+
const declaration = checker.getSymbolAtLocation(callee)?.valueDeclaration;
|
|
126
|
+
if (isMutableVariable(declaration))
|
|
127
|
+
return;
|
|
128
|
+
const target = functionOf(declaration);
|
|
129
|
+
return target && target.pos >= handler.pos && target.end <= handler.end ? target : undefined;
|
|
130
|
+
}
|
|
131
|
+
// A throw counts only when it leaves the handler, so one inside a `try` that has a `catch`, whose `finally` returns, or
|
|
132
|
+
// inside a promise callback is not evidence. The last write to `process.exitCode` decides whether an exit status stays.
|
|
133
|
+
function endsOrRethrows(handler, checker) {
|
|
134
|
+
let ends = false;
|
|
135
|
+
let exitCodeRetained = false;
|
|
136
|
+
const visitedHelpers = new Set();
|
|
137
|
+
const visitChildren = (node, swallowed) => {
|
|
138
|
+
ts.forEachChild(node, (child) => visit(child, isPromiseExecutor(child) ||
|
|
139
|
+
isPromiseReaction(child) ||
|
|
140
|
+
isAsyncFunction(child) ||
|
|
141
|
+
(swallowed && !isDeferredCallback(child))));
|
|
142
|
+
};
|
|
143
|
+
const visitHelper = (helper, swallowed) => {
|
|
144
|
+
if (visitedHelpers.has(helper))
|
|
145
|
+
return;
|
|
146
|
+
visitedHelpers.add(helper);
|
|
147
|
+
visitChildren(helper, swallowed || isAsyncFunction(helper));
|
|
148
|
+
};
|
|
149
|
+
const visitCalledHelpers = (call, swallowed) => {
|
|
150
|
+
const name = calleeName(call) ?? '';
|
|
151
|
+
const callee = localFunction(call.expression, handler, checker);
|
|
152
|
+
if (callee)
|
|
153
|
+
visitHelper(callee, swallowed);
|
|
154
|
+
if (!deferredCallName.test(name))
|
|
155
|
+
return;
|
|
156
|
+
// A named function handed to a scheduler runs later, like an inline callback.
|
|
157
|
+
for (const argument of callbackArguments(call, name)) {
|
|
158
|
+
const scheduled = localFunction(argument, handler, checker);
|
|
159
|
+
if (scheduled)
|
|
160
|
+
visitHelper(scheduled, promiseReactionName.test(name));
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const visit = (node, swallowed) => {
|
|
164
|
+
if (ends || isDormantFunction(node))
|
|
165
|
+
return;
|
|
166
|
+
if (ts.isThrowStatement(node) && !swallowed)
|
|
167
|
+
ends = true;
|
|
168
|
+
else if (isExitCodeAssignment(node, checker))
|
|
169
|
+
exitCodeRetained = !clearsExitCode(node);
|
|
170
|
+
else if (ts.isCallExpression(node) && shutdownCallName.test(calleeName(node) ?? ''))
|
|
171
|
+
ends = true;
|
|
172
|
+
else if (ts.isTryStatement(node)) {
|
|
173
|
+
const cancelsThrow = finallyReturns(node);
|
|
174
|
+
visit(node.tryBlock, swallowed || cancelsThrow || node.catchClause !== undefined);
|
|
175
|
+
if (node.catchClause)
|
|
176
|
+
visit(node.catchClause, swallowed || cancelsThrow);
|
|
177
|
+
if (node.finallyBlock)
|
|
178
|
+
visit(node.finallyBlock, swallowed);
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
if (ts.isCallExpression(node))
|
|
182
|
+
visitCalledHelpers(node, swallowed);
|
|
183
|
+
visitChildren(node, swallowed);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
visitChildren(handler, isAsyncFunction(handler));
|
|
187
|
+
return ends || exitCodeRetained;
|
|
188
|
+
}
|
|
189
|
+
// The handler's code when it is written in place or is a function, method or property of this file; undefined when it
|
|
190
|
+
// comes from elsewhere and cannot be read.
|
|
191
|
+
function handlerBody(handler, checker) {
|
|
192
|
+
const expression = ts.skipOuterExpressions(handler);
|
|
193
|
+
if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))
|
|
194
|
+
return expression;
|
|
195
|
+
if (!ts.isIdentifier(expression) && !ts.isPropertyAccessExpression(expression))
|
|
196
|
+
return;
|
|
197
|
+
const declaration = checker.getSymbolAtLocation(expression)?.valueDeclaration;
|
|
198
|
+
if (isMutableVariable(declaration))
|
|
199
|
+
return;
|
|
200
|
+
return functionOf(declaration);
|
|
201
|
+
}
|
|
202
|
+
function checkUncaughtException(sourceFile, file, checker) {
|
|
203
|
+
if (!sourceFile.text.includes('uncaughtException') || isIgnoredSource(sourceFile, file))
|
|
204
|
+
return [];
|
|
205
|
+
const findings = [];
|
|
206
|
+
walkNodes(sourceFile, (node) => {
|
|
207
|
+
if (!ts.isCallExpression(node) || !isProcessListenerCall(node, checker))
|
|
208
|
+
return;
|
|
209
|
+
const body = node.arguments[1] && handlerBody(node.arguments[1], checker);
|
|
210
|
+
if (!body || endsOrRethrows(body, checker))
|
|
211
|
+
return;
|
|
212
|
+
const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
213
|
+
findings.push({
|
|
214
|
+
file,
|
|
215
|
+
line: position.line + 1,
|
|
216
|
+
column: position.character + 1,
|
|
217
|
+
ruleId: 'uncaught-exception-continues',
|
|
218
|
+
message: 'This uncaughtException handler never exits or rethrows, so the process keeps running in an unknown state. Log the error, then shut down and exit with a non-zero code.',
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
return findings;
|
|
222
|
+
}
|
|
223
|
+
export { checkUncaughtException };
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Rule id -> { needs }: the weakest recognition the rule accepts ('syntax', 'import' or 'types';
|
|
2
2
|
// see bindings.cjs).
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
export default {
|
|
5
|
+
'auth-route-without-rate-limit': { needs: 'syntax' },
|
|
4
6
|
'bcrypt-low-cost': { needs: 'import' },
|
|
5
7
|
'hardcoded-secret': { needs: 'syntax' },
|
|
6
8
|
'insecure-cipher': { needs: 'import' },
|
|
@@ -9,9 +11,8 @@ export default {
|
|
|
9
11
|
'jwt-none-algorithm': { needs: 'syntax' },
|
|
10
12
|
'jwt-sign-without-expiry': { needs: 'import' },
|
|
11
13
|
'jwt-verify-without-algorithms': { needs: 'import' },
|
|
14
|
+
'plaintext-password-storage': { needs: 'syntax' },
|
|
12
15
|
'secret-compared-non-constant-time': { needs: 'import' },
|
|
13
16
|
'tls-verification-disabled': { needs: 'syntax' },
|
|
14
17
|
'weak-password-hash': { needs: 'import' },
|
|
15
|
-
'plaintext-password-storage': { needs: 'syntax' },
|
|
16
|
-
'auth-route-without-rate-limit': { needs: 'syntax' },
|
|
17
18
|
};
|
package/lib/security/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ import { exitCodeWithSkips } from '../performance/scan-outcome.js';
|
|
|
12
12
|
import { knownRules } from '../performance/rule-ids.js';
|
|
13
13
|
import { collectProjectChangedLines, fileKey } from '../performance/changed-lines.js';
|
|
14
14
|
import { sourcePolicy, workspaceTarget, projectDirectory, scanFilter, relativeToCwd } from '../performance/cli.js';
|
|
15
|
-
import { coveringConfig, projectConfig,
|
|
15
|
+
import { coveringConfig, projectConfig, configlessSources, isProjectDirectory } from '../shared/workspaces.js';
|
|
16
16
|
import { enableCompileCache } from 'node:module';
|
|
17
17
|
import { noteOffline, main as mainCli } from './deps/cli.js';
|
|
18
18
|
import { scanDependencies } from './deps/scan.js';
|
|
@@ -130,7 +130,7 @@ function scanFiles(values, positionals, workspace, isChangedFile) {
|
|
|
130
130
|
return { scannedFiles: 0, findings: [] };
|
|
131
131
|
const project = path.resolve(values.project ?? '.');
|
|
132
132
|
const root = fs.statSync(project).isDirectory() ? project : path.dirname(project);
|
|
133
|
-
const roots = workspace && values.workspace.length ? workspace.
|
|
133
|
+
const roots = workspace && values.workspace.length ? workspace.packages.map(({ directory }) => path.resolve(directory)) : [root];
|
|
134
134
|
const isIgnored = values.settings?.isIgnored;
|
|
135
135
|
return scanProjectFiles(roots, isChangedFile, isIgnored && ((file) => isIgnored(process.cwd(), file)));
|
|
136
136
|
}
|
|
@@ -152,12 +152,13 @@ async function scanProjectSources(values, positionals, scope) {
|
|
|
152
152
|
const directory = filesOnly ? input : (workspace?.directory ?? projectDirectory(values.project, positionals));
|
|
153
153
|
values.settings = loadSettings({ directory, explicit: values['loadwise-config'] });
|
|
154
154
|
enableCompileCache?.();
|
|
155
|
-
const inferredFiles = filesOnly ?
|
|
155
|
+
const inferredFiles = filesOnly ? configlessSources(input) : undefined;
|
|
156
156
|
const result = filesOnly && !inferredFiles
|
|
157
157
|
? { scannedFiles: 0, findings: [] }
|
|
158
158
|
: await analyzeWithEngine({
|
|
159
|
-
project: workspace?.configs ?? values.project,
|
|
160
|
-
files:
|
|
159
|
+
project: inferredFiles ? [] : (workspace?.configs ?? values.project),
|
|
160
|
+
files: positionals,
|
|
161
|
+
standaloneFiles: inferredFiles ?? workspace?.standaloneFiles,
|
|
161
162
|
policy: sourcePolicy(values.policy, values.settings).read(),
|
|
162
163
|
onlyFiles: scanFilter(values.settings, scope),
|
|
163
164
|
analyzers: [analyzer],
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Rule id -> { needs }: the weakest recognition the rule accepts ('syntax', 'import' or 'types';
|
|
2
2
|
// see bindings.cjs). This rule reads the lockfile, not source, and is reported by `loadwise sec
|
|
3
3
|
// deps`, so no source recognition applies.
|
|
4
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
4
5
|
export default {
|
|
5
6
|
'dependency-known-vulnerability': { needs: 'syntax' },
|
|
6
7
|
};
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
const examples = {
|
|
5
|
+
'auth-route-without-rate-limit': [
|
|
6
|
+
"app.post('/login', rateLimit({ windowMs: 60_000, max: 5 }), loginHandler);",
|
|
7
|
+
'Limit attempts per IP and per account; a gateway or proxy limit also counts.',
|
|
8
|
+
],
|
|
4
9
|
'bcrypt-low-cost': [
|
|
5
10
|
'const hash = await bcrypt.hash(password, 12);',
|
|
6
11
|
'Use a cost of 10 or higher; 12 is a common choice. Measure the hashing time on your hardware and raise the cost while a login stays fast enough.',
|
|
@@ -49,9 +54,5 @@ const examples = {
|
|
|
49
54
|
'const passwordHash = await bcrypt.hash(password, 12);\nconst matches = await bcrypt.compare(attempt, passwordHash);',
|
|
50
55
|
'Hash passwords with bcrypt, argon2 or crypto.scrypt. Existing hashes need a migration: re-hash each password at its next successful login.',
|
|
51
56
|
],
|
|
52
|
-
'auth-route-without-rate-limit': [
|
|
53
|
-
"app.post('/login', rateLimit({ windowMs: 60_000, max: 5 }), loginHandler);",
|
|
54
|
-
'Limit attempts per IP and per account; a gateway or proxy limit also counts.',
|
|
55
|
-
],
|
|
56
57
|
};
|
|
57
58
|
exports.default = examples;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
3
4
|
const examples = {
|
|
4
5
|
'dependency-known-vulnerability': [
|
|
5
6
|
'// Direct dependency: npm install lodash@4.17.21\n// Transitive: add "overrides": { "lodash": "4.17.21" } to package.json',
|