loadwise 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +542 -627
  2. package/bin/loadwise.js +4 -0
  3. package/lib/accessibility/frontend-detect.js +2 -1
  4. package/lib/accessibility/rule-ids.js +12 -9
  5. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  6. package/lib/editor/actions.js +117 -0
  7. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  8. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  9. package/lib/editor/diagnostics.js +365 -0
  10. package/lib/editor/dismissals.js +111 -0
  11. package/lib/editor/editor-document.js +99 -0
  12. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  13. package/lib/editor/fix-edits.js +200 -0
  14. package/lib/editor/language-server.js +437 -0
  15. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  16. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  17. package/lib/editor/perf-watch.js +78 -0
  18. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  19. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  20. package/lib/editor/scan-session.js +334 -0
  21. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  22. package/lib/editor/server-commands.js +232 -0
  23. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  24. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  25. package/lib/editor/types/dismissal.js +1 -0
  26. package/lib/editor/types/fix-example.js +1 -0
  27. package/lib/editor/types/source-document.js +1 -0
  28. package/lib/editor/workspace-files.js +78 -0
  29. package/lib/editor/workspace-paths.js +22 -0
  30. package/lib/maintainability/analyze-source.js +2 -0
  31. package/lib/maintainability/apply-fix.js +1 -1
  32. package/lib/maintainability/cli.js +1 -1
  33. package/lib/maintainability/examples.js +58 -41
  34. package/lib/maintainability/rule-ids.js +29 -14
  35. package/lib/maintainability/scan-changed.js +3 -0
  36. package/lib/maintainability/scan.js +13 -9
  37. package/lib/maintainability/tsconfig-strict.js +69 -0
  38. package/lib/maintainability/type-safety-hygiene.js +204 -0
  39. package/lib/performance/analyze.js +2 -0
  40. package/lib/performance/cli-arguments.js +0 -2
  41. package/lib/performance/cli-policy.js +17 -9
  42. package/lib/performance/cli-scan.js +10 -8
  43. package/lib/performance/cli.js +4 -23
  44. package/lib/performance/editor-signal.js +1 -1
  45. package/lib/performance/finding-text.js +3 -3
  46. package/lib/performance/fix-cli.js +1 -1
  47. package/lib/performance/frontend-perf.js +7 -0
  48. package/lib/performance/frontend-render-perf.js +200 -0
  49. package/lib/performance/llm-max-tokens.js +56 -0
  50. package/lib/performance/native.js +46 -26
  51. package/lib/performance/polyglot.js +22 -1
  52. package/lib/performance/pooling.js +38 -23
  53. package/lib/performance/projects.js +42 -21
  54. package/lib/performance/rule-ids.js +236 -222
  55. package/lib/performance/site-fixes/database.js +3 -1
  56. package/lib/performance/site-fixes/integrity.js +15 -1
  57. package/lib/performance/source-inputs.js +18 -6
  58. package/lib/performance/unscanned-javascript.js +66 -19
  59. package/lib/reliability/analyze.js +12 -0
  60. package/lib/reliability/child-process.js +106 -0
  61. package/lib/reliability/error-values.js +177 -0
  62. package/lib/reliability/pool-timeout.js +79 -0
  63. package/lib/reliability/react-bugs.js +602 -0
  64. package/lib/reliability/resource-leaks.js +3 -6
  65. package/lib/reliability/rule-ids.js +169 -127
  66. package/lib/reliability/switch-exhaustive.js +284 -0
  67. package/lib/reliability/uncaught-exception.js +223 -0
  68. package/lib/security/auth-crypto/rule-ids.js +3 -2
  69. package/lib/security/cli.js +6 -5
  70. package/lib/security/deps/rule-ids.js +1 -0
  71. package/lib/security/examples/auth-crypto.cjs +5 -4
  72. package/lib/security/examples/deps.cjs +1 -0
  73. package/lib/security/examples/exposure.cjs +55 -42
  74. package/lib/security/examples/files.cjs +1 -0
  75. package/lib/security/examples/injection.cjs +1 -0
  76. package/lib/security/examples/moved.cjs +5 -4
  77. package/lib/security/examples/request-forgery.cjs +1 -0
  78. package/lib/security/exposure/client-env.js +113 -0
  79. package/lib/security/exposure/frontend-security.js +12 -10
  80. package/lib/security/exposure/index.js +14 -3
  81. package/lib/security/exposure/jsx-url.js +267 -0
  82. package/lib/security/exposure/next-image-config.js +34 -0
  83. package/lib/security/exposure/package-manifest.js +45 -0
  84. package/lib/security/exposure/react-version.js +45 -0
  85. package/lib/security/exposure/rule-ids.js +16 -12
  86. package/lib/security/files/index.js +1 -1
  87. package/lib/security/files/rule-ids.js +1 -0
  88. package/lib/security/injection/code.js +24 -10
  89. package/lib/security/injection/command.js +81 -28
  90. package/lib/security/injection/nosql.js +109 -22
  91. package/lib/security/injection/redos.js +152 -308
  92. package/lib/security/injection/regex-pattern.js +290 -0
  93. package/lib/security/injection/regex.js +30 -11
  94. package/lib/security/injection/rule-ids.js +2 -1
  95. package/lib/security/injection/shared.js +19 -1
  96. package/lib/security/injection/sql.js +83 -2
  97. package/lib/security/request-forgery/rule-ids.js +1 -0
  98. package/lib/security/rule-descriptions.js +36 -32
  99. package/lib/security/rule-ids.js +74 -67
  100. package/lib/security/taint/filename-guard.js +3 -1
  101. package/lib/security/taint/guards.js +84 -10
  102. package/lib/security/taint/index.js +124 -13
  103. package/lib/security/taint/propagate.js +10 -7
  104. package/lib/security/taint/sanitizers.js +7 -3
  105. package/lib/security/taint/sources.js +6 -3
  106. package/lib/security/taint/summaries.js +13 -1
  107. package/lib/security/taint/url-parts.js +14 -5
  108. package/lib/shared/agent-session.js +2 -2
  109. package/lib/shared/check.js +9 -6
  110. package/lib/shared/explain.js +5 -5
  111. package/lib/shared/fix-convergence.js +1 -1
  112. package/lib/shared/formats/finding-location.js +6 -2
  113. package/lib/shared/formats/sarif.js +3 -3
  114. package/lib/shared/heap-limit.js +6 -0
  115. package/lib/shared/pillars.js +7 -7
  116. package/lib/shared/rule-docs.js +12 -0
  117. package/lib/shared/scan-cache.js +0 -1
  118. package/lib/shared/workspaces.js +31 -9
  119. package/package.json +9 -16
  120. package/plugin/.claude-plugin/plugin.json +1 -1
  121. package/schema/loadwise.config.schema.json +44 -0
  122. package/editor/README.md +0 -47
  123. package/examples/redis-keys.otlp.json +0 -22
  124. package/lib/maintainability/notify-editor.js +0 -1
  125. package/lib/performance/editor-report.js +0 -191
  126. package/lib/performance/editor-setup.js +0 -189
  127. package/lib/performance/editor-watch-supervisor.js +0 -104
  128. package/lib/performance/editor-watch.js +0 -193
  129. package/lib/performance/notify-editor.js +0 -1
  130. package/lib/performance/recursive-watch.js +0 -181
  131. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -0,0 +1,290 @@
1
+ // The small, conservative regex parser behind `regex-catastrophic-backtracking`, plus the code point
2
+ // range helpers it builds on. Anything it does not fully understand (backreferences, Unicode
3
+ // property escapes, inline modifiers) throws `Unsupported`, and the caller treats the pattern as safe.
4
+ const maxCodePoint = 0x10ffff;
5
+ const everyCharacter = [[0, maxCodePoint]];
6
+ const digitRanges = [[0x30, 0x39]];
7
+ const wordRanges = [
8
+ [0x30, 0x39],
9
+ [0x41, 0x5a],
10
+ [0x5f, 0x5f],
11
+ [0x61, 0x7a],
12
+ ];
13
+ const spaceRanges = [
14
+ [0x09, 0x0d],
15
+ [0x20, 0x20],
16
+ [0xa0, 0xa0],
17
+ [0x1680, 0x1680],
18
+ [0x2000, 0x200a],
19
+ [0x2028, 0x2029],
20
+ [0x202f, 0x202f],
21
+ [0x205f, 0x205f],
22
+ [0x3000, 0x3000],
23
+ [0xfeff, 0xfeff],
24
+ ];
25
+ const controlEscapes = { n: 0x0a, r: 0x0d, t: 0x09, v: 0x0b, f: 0x0c, 0: 0x00 };
26
+ const classEscapes = { d: digitRanges, w: wordRanges, s: spaceRanges };
27
+ const upperToLowerOffset = 0x20;
28
+ // Thrown when the parser meets syntax it does not model; the pattern is then treated as safe.
29
+ class Unsupported extends Error {
30
+ }
31
+ // ---- Character sets: sorted, merged [low, high] code point ranges. ----
32
+ function normalize(ranges) {
33
+ const sorted = [...ranges].sort((left, right) => left[0] - right[0]);
34
+ const merged = [];
35
+ for (const [low, high] of sorted) {
36
+ const last = merged.at(-1);
37
+ if (last && low <= last[1] + 1)
38
+ last[1] = Math.max(last[1], high);
39
+ else
40
+ merged.push([low, high]);
41
+ }
42
+ return merged;
43
+ }
44
+ function complement(ranges) {
45
+ const result = [];
46
+ let next = 0;
47
+ for (const [low, high] of normalize(ranges)) {
48
+ if (low > next)
49
+ result.push([next, low - 1]);
50
+ next = high + 1;
51
+ }
52
+ if (next <= maxCodePoint)
53
+ result.push([next, maxCodePoint]);
54
+ return result;
55
+ }
56
+ function overlaps(left, right) {
57
+ return left.some(([low, high]) => right.some(([otherLow, otherHigh]) => low <= otherHigh && otherLow <= high));
58
+ }
59
+ // Adds the other case of every ASCII letter in the set, for the `i` flag.
60
+ function foldCase(ranges) {
61
+ const folded = [...ranges];
62
+ for (const [low, high] of ranges) {
63
+ for (const [letterLow, letterHigh, offset] of [
64
+ [0x41, 0x5a, upperToLowerOffset],
65
+ [0x61, 0x7a, -upperToLowerOffset],
66
+ ]) {
67
+ const from = Math.max(low, letterLow);
68
+ const to = Math.min(high, letterHigh);
69
+ if (from <= to)
70
+ folded.push([from + offset, to + offset]);
71
+ }
72
+ }
73
+ return normalize(folded);
74
+ }
75
+ // ---- Parser: pattern text -> { kind: 'char' | 'assert' | 'group' | 'alt' | 'seq' | 'quant' |
76
+ // 'lookaround' } ----
77
+ function createParser(source, flags) {
78
+ let position = 0;
79
+ const ignoreCase = flags.includes('i');
80
+ const peek = (offset = 0) => source[position + offset];
81
+ const atEnd = () => position >= source.length;
82
+ function charNode(ranges) {
83
+ return { kind: 'char', ranges: ignoreCase ? foldCase(ranges) : normalize(ranges) };
84
+ }
85
+ function codePointAt() {
86
+ const codePoint = source.codePointAt(position);
87
+ if (codePoint === undefined)
88
+ throw new Unsupported();
89
+ position += codePoint > 0xffff ? 2 : 1;
90
+ return codePoint;
91
+ }
92
+ function readHex(length) {
93
+ const digits = source.slice(position, position + length);
94
+ if (digits.length !== length || !/^[0-9a-fA-F]+$/.test(digits))
95
+ throw new Unsupported();
96
+ position += length;
97
+ return parseInt(digits, 16);
98
+ }
99
+ // A single code point escape (`\n`, `\x41`, `A`, `\u{41}`, `\.`), or a class escape's ranges.
100
+ function readEscape(inClass) {
101
+ position++;
102
+ const letter = peek();
103
+ if (letter === undefined)
104
+ throw new Unsupported();
105
+ position++;
106
+ if (classEscapes[letter])
107
+ return { ranges: classEscapes[letter] };
108
+ if (classEscapes[letter.toLowerCase()])
109
+ return { ranges: complement(classEscapes[letter.toLowerCase()]) };
110
+ if (letter in controlEscapes && !(letter === '0' && /\d/.test(peek() ?? '')))
111
+ return { code: controlEscapes[letter] };
112
+ if (letter === 'x')
113
+ return { code: readHex(2) };
114
+ if (letter === 'u' && peek() === '{') {
115
+ const close = source.indexOf('}', position);
116
+ if (close < 0)
117
+ throw new Unsupported();
118
+ const digits = source.slice(position + 1, close);
119
+ if (!/^[0-9a-fA-F]{1,6}$/.test(digits))
120
+ throw new Unsupported();
121
+ position = close + 1;
122
+ return { code: parseInt(digits, 16) };
123
+ }
124
+ if (letter === 'u')
125
+ return { code: readHex(4) };
126
+ if (inClass && letter === 'b')
127
+ return { code: 0x08 };
128
+ // Backreferences, `\k<name>`, `\p{...}`, `\c` and octal escapes change matching in ways not
129
+ // modelled here.
130
+ if (/[0-9kpPc]/.test(letter))
131
+ throw new Unsupported();
132
+ return { code: letter.codePointAt(0) };
133
+ }
134
+ function readClassAtom() {
135
+ if (peek() === '\\')
136
+ return readEscape(true);
137
+ return { code: codePointAt() };
138
+ }
139
+ function parseClass() {
140
+ position++;
141
+ const negated = peek() === '^';
142
+ if (negated)
143
+ position++;
144
+ const ranges = [];
145
+ while (peek() !== ']') {
146
+ if (atEnd())
147
+ throw new Unsupported();
148
+ const start = readClassAtom();
149
+ if (peek() === '-' && peek(1) !== ']' && peek(1) !== undefined && start.code !== undefined) {
150
+ position++;
151
+ const end = readClassAtom();
152
+ if (end.code === undefined || end.code < start.code)
153
+ throw new Unsupported();
154
+ ranges.push([start.code, end.code]);
155
+ continue;
156
+ }
157
+ if (start.ranges)
158
+ ranges.push(...start.ranges);
159
+ else if (start.code !== undefined)
160
+ ranges.push([start.code, start.code]);
161
+ }
162
+ position++;
163
+ const members = ignoreCase ? foldCase(ranges) : ranges;
164
+ return { kind: 'char', ranges: negated ? complement(members) : normalize(members) };
165
+ }
166
+ // The group kind for the text after `(`, consuming its `?:`, `?=`, `?<!` or `?<name>` prefix.
167
+ function readGroupKind() {
168
+ if (peek() !== '?')
169
+ return 'group';
170
+ const opener = source.slice(position, position + 3);
171
+ if (['?=', '?!'].includes(opener.slice(0, 2)) || ['?<=', '?<!'].includes(opener)) {
172
+ position += opener.startsWith('?<') ? 3 : 2;
173
+ return 'lookaround';
174
+ }
175
+ const nameEnd = source.indexOf('>', position);
176
+ if (opener.startsWith('?:'))
177
+ position += 2;
178
+ else if (opener.startsWith('?<') && nameEnd > 0)
179
+ position = nameEnd + 1;
180
+ else
181
+ throw new Unsupported();
182
+ return 'group';
183
+ }
184
+ let groupDepth = 0;
185
+ function parseGroup() {
186
+ if (++groupDepth > 64)
187
+ throw new Unsupported();
188
+ try {
189
+ position++;
190
+ const kind = readGroupKind();
191
+ const body = parseAlternation();
192
+ if (peek() !== ')')
193
+ throw new Unsupported();
194
+ position++;
195
+ return { kind, body };
196
+ }
197
+ finally {
198
+ groupDepth--;
199
+ }
200
+ }
201
+ // Consumes `length` characters and returns `node`.
202
+ function consume(length, node) {
203
+ position += length;
204
+ return node;
205
+ }
206
+ function parseAtom() {
207
+ const character = peek();
208
+ if (character === '^' || character === '$')
209
+ return consume(1, { kind: 'assert', anchor: character });
210
+ if (character === '(')
211
+ return parseGroup();
212
+ if (character === '[')
213
+ return parseClass();
214
+ if (character === '.')
215
+ return consume(1, charNode(everyCharacter));
216
+ if (character === '\\' && (peek(1) === 'b' || peek(1) === 'B'))
217
+ return consume(2, { kind: 'assert' });
218
+ if (character === '\\') {
219
+ const escape = readEscape(false);
220
+ if (escape.ranges)
221
+ return charNode(escape.ranges);
222
+ if (escape.code === undefined)
223
+ throw new Unsupported();
224
+ return charNode([[escape.code, escape.code]]);
225
+ }
226
+ if (character === '*' ||
227
+ character === '+' ||
228
+ character === '?' ||
229
+ character === ')' ||
230
+ (character === '{' && /^\{\d+(,\d*)?\}/.test(source.slice(position))))
231
+ throw new Unsupported();
232
+ const code = codePointAt();
233
+ return charNode([[code, code]]);
234
+ }
235
+ // `{n}`, `{n,}`, `{n,m}`, `*`, `+`, `?` (lazy or not), or undefined.
236
+ function readQuantifier() {
237
+ const character = peek();
238
+ let bounds;
239
+ if (character === '*')
240
+ bounds = { min: 0, max: Infinity, length: 1 };
241
+ else if (character === '+')
242
+ bounds = { min: 1, max: Infinity, length: 1 };
243
+ else if (character === '?')
244
+ bounds = { min: 0, max: 1, length: 1 };
245
+ else if (character === '{') {
246
+ const braces = /^\{(\d+)(,(\d*))?\}/.exec(source.slice(position));
247
+ if (!braces)
248
+ return;
249
+ const min = Number(braces[1]);
250
+ const max = braces[2] === undefined ? min : braces[3] === '' ? Infinity : Number(braces[3]);
251
+ bounds = { min, max, length: braces[0].length };
252
+ }
253
+ else
254
+ return;
255
+ position += bounds.length;
256
+ if (peek() === '?')
257
+ position++;
258
+ return bounds;
259
+ }
260
+ function parseSequence() {
261
+ const items = [];
262
+ while (!atEnd() && peek() !== '|' && peek() !== ')') {
263
+ const atom = parseAtom();
264
+ const bounds = readQuantifier();
265
+ if (!bounds) {
266
+ items.push(atom);
267
+ continue;
268
+ }
269
+ if (atom.kind === 'assert' || atom.kind === 'lookaround')
270
+ throw new Unsupported();
271
+ items.push({ kind: 'quant', body: atom, min: bounds.min, max: bounds.max });
272
+ }
273
+ return { kind: 'seq', items };
274
+ }
275
+ function parseAlternation() {
276
+ const alternatives = [parseSequence()];
277
+ while (peek() === '|') {
278
+ position++;
279
+ alternatives.push(parseSequence());
280
+ }
281
+ return alternatives.length === 1 ? alternatives[0] : { kind: 'alt', alternatives };
282
+ }
283
+ return function parse() {
284
+ const tree = parseAlternation();
285
+ if (!atEnd())
286
+ throw new Unsupported();
287
+ return tree;
288
+ };
289
+ }
290
+ export { createParser, normalize, overlaps, maxCodePoint, Unsupported };
@@ -1,7 +1,7 @@
1
1
  // `regex-from-input`: request text compiled as a regular expression, by `RegExp`, by a string
2
2
  // method that converts its argument to a pattern, or as a MongoDB `$regex` operand.
3
3
  import { ts } from '../../performance/compiler.js';
4
- import { reportTraced, isGlobalName, methodName } from './shared.js';
4
+ import { reportTraced, isGlobalName } from './shared.js';
5
5
  const ruleId = 'regex-from-input';
6
6
  const regexConstructors = new Set(['RegExp']);
7
7
  const patternMethods = new Set(['match', 'matchAll', 'search']);
@@ -16,11 +16,21 @@ function reportPattern(pattern, context) {
16
16
  return;
17
17
  reportTraced(context, pattern, ruleId, message(trace.label), trace);
18
18
  }
19
- function isStringReceiver(call, checker) {
19
+ // `text.search(...)` and `text['search'](...)` call the same method.
20
+ function stringMethodCall(call) {
20
21
  const callee = ts.skipOuterExpressions(call.expression);
21
- if (!ts.isPropertyAccessExpression(callee))
22
- return false;
23
- return Boolean(checker.getTypeAtLocation(callee.expression).flags & ts.TypeFlags.StringLike);
22
+ if (ts.isPropertyAccessExpression(callee))
23
+ return { receiver: callee.expression, method: callee.name.text };
24
+ if (!ts.isElementAccessExpression(callee))
25
+ return;
26
+ const key = ts.skipOuterExpressions(callee.argumentExpression);
27
+ return ts.isStringLiteralLike(key) ? { receiver: callee.expression, method: key.text } : undefined;
28
+ }
29
+ // A union such as `string | RegExp` can still be compiled as a pattern when it holds a string.
30
+ function canBeString(type) {
31
+ if (type.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown))
32
+ return true;
33
+ return type.isUnion() && (type.types?.some(canBeString) ?? false);
24
34
  }
25
35
  function checkCall(node, context) {
26
36
  const callee = ts.skipOuterExpressions(node.expression);
@@ -28,20 +38,29 @@ function checkCall(node, context) {
28
38
  return reportPattern(node.arguments?.[0], context);
29
39
  if (!ts.isCallExpression(node))
30
40
  return;
31
- const method = methodName(node);
32
- if (method === undefined || !patternMethods.has(method))
41
+ const stringCall = stringMethodCall(node);
42
+ if (stringCall === undefined || !patternMethods.has(stringCall.method))
33
43
  return;
34
44
  const [pattern] = node.arguments;
35
- if (!pattern || !isStringReceiver(node, context.checker))
45
+ if (!pattern)
46
+ return;
47
+ if (!(context.checker.getTypeAtLocation(stringCall.receiver).flags & ts.TypeFlags.StringLike))
36
48
  return;
37
49
  // A RegExp object built elsewhere is reported where it is built.
38
- if (!(context.checker.getTypeAtLocation(pattern).flags &
39
- (ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown)))
50
+ if (!canBeString(context.checker.getTypeAtLocation(pattern)))
40
51
  return;
41
52
  reportPattern(pattern, context);
42
53
  }
54
+ // The decoded name of a static property key: `$regex`, `'$regex'` and `['$regex']`.
55
+ function staticKeyName(name) {
56
+ if (ts.isComputedPropertyName(name)) {
57
+ const key = ts.skipOuterExpressions(name.expression);
58
+ return ts.isStringLiteralLike(key) ? key.text : undefined;
59
+ }
60
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? name.text : undefined;
61
+ }
43
62
  function checkRegexOperator(property, context) {
44
- if (property.name.getText().replaceAll(/['"]/g, '') !== '$regex')
63
+ if (staticKeyName(property.name) !== '$regex')
45
64
  return;
46
65
  reportPattern(property.initializer, context);
47
66
  }
@@ -1,5 +1,6 @@
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 {
4
5
  'code-injection': { needs: 'syntax' },
5
6
  'command-injection': { needs: 'import' },
@@ -8,8 +9,8 @@ export default {
8
9
  'mysql-dynamic-query-text': { needs: 'import' },
9
10
  'nosql-operator-injection': { needs: 'import' },
10
11
  'prisma-raw-unsafe-dynamic': { needs: 'syntax' },
11
- 'regex-from-input': { needs: 'syntax' },
12
12
  'regex-catastrophic-backtracking': { needs: 'syntax' },
13
+ 'regex-from-input': { needs: 'syntax' },
13
14
  'sequelize-dynamic-query-text': { needs: 'import' },
14
15
  'template-injection': { needs: 'import' },
15
16
  'typeorm-dynamic-query-text': { needs: 'import' },
@@ -1,6 +1,7 @@
1
1
  // Helpers shared by the injection rules: trace wording and tiering, global and locally created
2
2
  // values.
3
3
  import { ts } from '../../performance/compiler.js';
4
+ import { fieldWritesTo } from '../taint/guards.js';
4
5
  const secondHopReason = 'Reached through two calls; confirm the intermediate functions do not validate the value.';
5
6
  // Bounds the alias chains followed when a value is created by a library call in another statement.
6
7
  const maxAliasDepth = 4;
@@ -61,6 +62,23 @@ function initializerOf(identifier, checker) {
61
62
  if (ts.isBinaryExpression(declaration))
62
63
  return ts.skipOuterExpressions(declaration.right);
63
64
  }
65
+ // The field writes (`options.shell = true`) to the local object `identifier` names, which change
66
+ // what its literal initializer says.
67
+ function fieldWritesOf(identifier, checker) {
68
+ const declaration = valueDeclaration(identifier, checker);
69
+ if (!declaration || !ts.isVariableDeclaration(declaration))
70
+ return [];
71
+ const scope = ts.findAncestor(declaration, (node) => ts.isFunctionLike(node) || ts.isSourceFile(node));
72
+ return scope ? fieldWritesTo(declaration, scope, checker) : [];
73
+ }
74
+ // The arguments in the positions the callee receives them: `f(...['a', b])` passes `'a'`, then `b`.
75
+ // A spread of anything else stays a spread, since the positions it fills are unknown.
76
+ function positionalArguments(args) {
77
+ return args.flatMap((argument) => {
78
+ const spread = ts.isSpreadElement(argument) ? ts.skipOuterExpressions(argument.expression) : undefined;
79
+ return spread && ts.isArrayLiteralExpression(spread) ? positionalArguments(spread.elements) : [argument];
80
+ });
81
+ }
64
82
  // The value of `module.exports = value` or `export = value` in a project source file.
65
83
  function moduleExportValue(sourceFile, checker) {
66
84
  if (sourceFile.isDeclarationFile)
@@ -116,4 +134,4 @@ function createdBy(expression, isFactory, checker, depth = 0) {
116
134
  return (createdBy(value.left, isFactory, checker, depth + 1) || createdBy(value.right, isFactory, checker, depth + 1));
117
135
  return false;
118
136
  }
119
- export { sourceSuffix, hopReason, reportTraced, methodName, isGlobalName, calledExport, initializerOf, createdBy };
137
+ export { sourceSuffix, reportTraced, methodName, isGlobalName, calledExport, initializerOf, fieldWritesOf, positionalArguments, createdBy, };
@@ -116,6 +116,8 @@ function isPlaceholderList(node, call, context) {
116
116
  if (!ts.isCallExpression(list))
117
117
  return false;
118
118
  const method = methodName(list);
119
+ if ((method === 'fill' || method === 'map') && !isBuiltInArrayReceiver(list, context))
120
+ return false;
119
121
  if (method === 'fill' && list.arguments.length >= 1) {
120
122
  return isFixedPart(list.arguments[0], call, context);
121
123
  }
@@ -130,6 +132,15 @@ function isPlaceholderList(node, call, context) {
130
132
  return false;
131
133
  return isFixedPlaceholderCallback(list.arguments[0], call, context);
132
134
  }
135
+ // A custom `map` or `fill` can return runtime text without calling its callback, so a method the
136
+ // project declares itself loses the placeholder-list exemption; the library's array methods and an
137
+ // unresolved call (plain JavaScript, loose request types) keep it.
138
+ function isBuiltInArrayReceiver(list, context) {
139
+ if (!ts.isPropertyAccessExpression(list.expression))
140
+ return false;
141
+ const method = context.checker.getSymbolAtLocation(list.expression.name);
142
+ return !method?.declarations?.some((declaration) => !declaration.getSourceFile().isDeclarationFile);
143
+ }
133
144
  // Any identifier with the same text counts as a use, shadowed or not, so the answer errs towards
134
145
  // "used".
135
146
  function isNameUsedIn(name, body) {
@@ -166,12 +177,73 @@ function iteratedArray(expression, checker) {
166
177
  const declaration = checker.getSymbolAtLocation(isField ? iterated.name : iterated)?.valueDeclaration;
167
178
  if (!declaration)
168
179
  return;
180
+ const symbol = checker.getSymbolAtLocation(isField ? iterated.name : iterated);
169
181
  if (ts.isVariableDeclaration(declaration) && declaration.parent.flags & ts.NodeFlags.Const)
170
- return declaration.initializer;
182
+ return symbol && hasElementWrites(declaration, symbol, checker) ? undefined : declaration.initializer;
171
183
  if (!ts.isPropertyDeclaration(declaration))
172
184
  return;
173
185
  const readonly = declaration.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword);
174
- return readonly ? declaration.initializer : undefined;
186
+ if (!readonly || (symbol && hasElementWrites(declaration, symbol, checker)))
187
+ return;
188
+ return declaration.initializer;
189
+ }
190
+ // The methods that can put a new value into the array; `pop`, `sort` and the like only remove or
191
+ // reorder its literal elements.
192
+ const arrayMutatingMethods = new Set(['push', 'unshift', 'splice', 'fill']);
193
+ function mutatingMethodName(access) {
194
+ if (ts.isPropertyAccessExpression(access))
195
+ return access.name.text;
196
+ if (!ts.isElementAccessExpression(access))
197
+ return;
198
+ const key = ts.skipOuterExpressions(access.argumentExpression);
199
+ return ts.isStringLiteralLike(key) ? key.text : undefined;
200
+ }
201
+ // `const` and `readonly` only pin the binding: `TABLES[0] = x`, `TABLES.push(x)` or
202
+ // `TABLES['push'](x)` still changes the elements, as does a write through `const alias = TABLES`, so
203
+ // an alias counts as a write. Passing the array to another function is not tracked.
204
+ function hasElementWrites(declaration, symbol, checker) {
205
+ const refersToSymbol = (node) => {
206
+ const target = ts.skipOuterExpressions(node);
207
+ const named = ts.isPropertyAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword
208
+ ? target.name
209
+ : target;
210
+ return checker.getSymbolAtLocation(named) === symbol;
211
+ };
212
+ return Boolean((function visit(node) {
213
+ if (ts.isElementAccessExpression(node) && ts.isAssignmentTarget(node) && refersToSymbol(node.expression))
214
+ return true;
215
+ const method = mutatingMethodName(node);
216
+ if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) &&
217
+ method !== undefined &&
218
+ arrayMutatingMethods.has(method) &&
219
+ refersToSymbol(node.expression))
220
+ return true;
221
+ if (isAliasing(node) && refersToSymbol(node))
222
+ return true;
223
+ return ts.forEachChild(node, visit);
224
+ })(declaration.getSourceFile()));
225
+ }
226
+ // `const alias = value` or `alias = value`: the value gets a second name that can be mutated.
227
+ function isAliasing(node) {
228
+ if (!(ts.isIdentifier(node) || ts.isPropertyAccessExpression(node)))
229
+ return false;
230
+ // `const alias = (TABLES)` and `TABLES as string[]` still alias the array.
231
+ let aliased = node;
232
+ while (aliased.parent && isTransparentWrapper(aliased.parent))
233
+ aliased = aliased.parent;
234
+ const parent = aliased.parent;
235
+ if (!parent)
236
+ return false;
237
+ if (ts.isVariableDeclaration(parent))
238
+ return parent.initializer === aliased;
239
+ return (ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && parent.right === aliased);
240
+ }
241
+ function isTransparentWrapper(node) {
242
+ return (ts.isParenthesizedExpression(node) ||
243
+ ts.isAsExpression(node) ||
244
+ ts.isSatisfiesExpression(node) ||
245
+ ts.isNonNullExpression(node) ||
246
+ ts.isTypeAssertionExpression(node));
175
247
  }
176
248
  // `for (const table of ['a', 'b'])` and `for (const [table, policy] of POLICIES)`: each value is a
177
249
  // literal.
@@ -221,6 +293,15 @@ function fieldValuesAreFixed(declaration, symbol, call, context) {
221
293
  otherWrite = true;
222
294
  }
223
295
  }
296
+ // `this['table'] = x` writes the field without a property access; a computed key may name any field.
297
+ if (ts.isElementAccessExpression(child) && child.expression.kind === ts.SyntaxKind.ThisKeyword) {
298
+ const key = child.argumentExpression;
299
+ const namesOtherField = ts.isStringLiteralLike(key) && key.text !== symbol.name;
300
+ // A computed key cannot name an ECMAScript `#private` field.
301
+ const canWriteField = !ts.isPrivateIdentifier(declaration.name) && !namesOtherField;
302
+ if (ts.isAssignmentTarget(child) && canWriteField)
303
+ otherWrite = true;
304
+ }
224
305
  ts.forEachChild(child, visit);
225
306
  })(declaration.parent);
226
307
  return !otherWrite && values.length > 0 && values.every((value) => isFixedText(value, call, context, 0));
@@ -1,5 +1,6 @@
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 {
4
5
  'open-redirect': { needs: 'import' },
5
6
  'path-traversal': { needs: 'import' },