loadwise 0.5.0 → 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 (132) hide show
  1. package/README.md +543 -628
  2. package/bin/loadwise.js +5 -1
  3. package/lib/accessibility/frontend-detect.js +2 -1
  4. package/lib/accessibility/rule-ids.js +12 -9
  5. package/lib/accessibility/template-attributes.js +4 -2
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +16 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +20 -3
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +12 -19
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -4,6 +4,7 @@
4
4
  // modifiers) is skipped rather than guessed.
5
5
  import { ts } from '../../performance/compiler.js';
6
6
  import { reportTraced, isGlobalName, methodName, initializerOf } from './shared.js';
7
+ import { createParser, normalize, overlaps, maxCodePoint, Unsupported } from './regex-pattern.js';
7
8
  const ruleId = 'regex-catastrophic-backtracking';
8
9
  const regexConstructors = new Set(['RegExp']);
9
10
  // Methods called on the regex with the subject as the first argument, and string methods taking the
@@ -15,292 +16,6 @@ const stringMethods = new Set(['match', 'matchAll', 'replace', 'replaceAll', 'sp
15
16
  const truncatingMethods = new Set(['slice', 'substring', 'substr']);
16
17
  // Bounds the `const` alias chain followed to find a regex.
17
18
  const maxAliasDepth = 4;
18
- const maxCodePoint = 0x10ffff;
19
- const everyCharacter = [[0, maxCodePoint]];
20
- const digitRanges = [[0x30, 0x39]];
21
- const wordRanges = [
22
- [0x30, 0x39],
23
- [0x41, 0x5a],
24
- [0x5f, 0x5f],
25
- [0x61, 0x7a],
26
- ];
27
- const spaceRanges = [
28
- [0x09, 0x0d],
29
- [0x20, 0x20],
30
- [0xa0, 0xa0],
31
- [0x1680, 0x1680],
32
- [0x2000, 0x200a],
33
- [0x2028, 0x2029],
34
- [0x202f, 0x202f],
35
- [0x205f, 0x205f],
36
- [0x3000, 0x3000],
37
- [0xfeff, 0xfeff],
38
- ];
39
- const controlEscapes = { n: 0x0a, r: 0x0d, t: 0x09, v: 0x0b, f: 0x0c, 0: 0x00 };
40
- const classEscapes = { d: digitRanges, w: wordRanges, s: spaceRanges };
41
- const upperToLowerOffset = 0x20;
42
- // Thrown when the parser meets syntax it does not model; the pattern is then treated as safe.
43
- class Unsupported extends Error {
44
- }
45
- // ---- Character sets: sorted, merged [low, high] code point ranges. ----
46
- function normalize(ranges) {
47
- const sorted = [...ranges].sort((left, right) => left[0] - right[0]);
48
- const merged = [];
49
- for (const [low, high] of sorted) {
50
- const last = merged.at(-1);
51
- if (last && low <= last[1] + 1)
52
- last[1] = Math.max(last[1], high);
53
- else
54
- merged.push([low, high]);
55
- }
56
- return merged;
57
- }
58
- function complement(ranges) {
59
- const result = [];
60
- let next = 0;
61
- for (const [low, high] of normalize(ranges)) {
62
- if (low > next)
63
- result.push([next, low - 1]);
64
- next = high + 1;
65
- }
66
- if (next <= maxCodePoint)
67
- result.push([next, maxCodePoint]);
68
- return result;
69
- }
70
- function overlaps(left, right) {
71
- return left.some(([low, high]) => right.some(([otherLow, otherHigh]) => low <= otherHigh && otherLow <= high));
72
- }
73
- // Adds the other case of every ASCII letter in the set, for the `i` flag.
74
- function foldCase(ranges) {
75
- const folded = [...ranges];
76
- for (const [low, high] of ranges) {
77
- for (const [letterLow, letterHigh, offset] of [
78
- [0x41, 0x5a, upperToLowerOffset],
79
- [0x61, 0x7a, -upperToLowerOffset],
80
- ]) {
81
- const from = Math.max(low, letterLow);
82
- const to = Math.min(high, letterHigh);
83
- if (from <= to)
84
- folded.push([from + offset, to + offset]);
85
- }
86
- }
87
- return normalize(folded);
88
- }
89
- // ---- Parser: pattern text -> { kind: 'char' | 'assert' | 'group' | 'alt' | 'seq' | 'quant' |
90
- // 'lookaround' } ----
91
- function createParser(source, flags) {
92
- let position = 0;
93
- const ignoreCase = flags.includes('i');
94
- const peek = (offset = 0) => source[position + offset];
95
- const atEnd = () => position >= source.length;
96
- function charNode(ranges) {
97
- return { kind: 'char', ranges: ignoreCase ? foldCase(ranges) : normalize(ranges) };
98
- }
99
- function codePointAt() {
100
- const codePoint = source.codePointAt(position);
101
- if (codePoint === undefined)
102
- throw new Unsupported();
103
- position += codePoint > 0xffff ? 2 : 1;
104
- return codePoint;
105
- }
106
- function readHex(length) {
107
- const digits = source.slice(position, position + length);
108
- if (digits.length !== length || !/^[0-9a-fA-F]+$/.test(digits))
109
- throw new Unsupported();
110
- position += length;
111
- return parseInt(digits, 16);
112
- }
113
- // A single code point escape (`\n`, `\x41`, `A`, `\u{41}`, `\.`), or a class escape's ranges.
114
- function readEscape(inClass) {
115
- position++;
116
- const letter = peek();
117
- if (letter === undefined)
118
- throw new Unsupported();
119
- position++;
120
- if (classEscapes[letter])
121
- return { ranges: classEscapes[letter] };
122
- if (classEscapes[letter.toLowerCase()])
123
- return { ranges: complement(classEscapes[letter.toLowerCase()]) };
124
- if (letter in controlEscapes && !(letter === '0' && /\d/.test(peek() ?? '')))
125
- return { code: controlEscapes[letter] };
126
- if (letter === 'x')
127
- return { code: readHex(2) };
128
- if (letter === 'u' && peek() === '{') {
129
- const close = source.indexOf('}', position);
130
- if (close < 0)
131
- throw new Unsupported();
132
- const digits = source.slice(position + 1, close);
133
- if (!/^[0-9a-fA-F]{1,6}$/.test(digits))
134
- throw new Unsupported();
135
- position = close + 1;
136
- return { code: parseInt(digits, 16) };
137
- }
138
- if (letter === 'u')
139
- return { code: readHex(4) };
140
- if (inClass && letter === 'b')
141
- return { code: 0x08 };
142
- // Backreferences, `\k<name>`, `\p{...}`, `\c` and octal escapes change matching in ways not
143
- // modelled here.
144
- if (/[0-9kpPc]/.test(letter))
145
- throw new Unsupported();
146
- return { code: letter.codePointAt(0) };
147
- }
148
- function readClassAtom() {
149
- if (peek() === '\\')
150
- return readEscape(true);
151
- return { code: codePointAt() };
152
- }
153
- function parseClass() {
154
- position++;
155
- const negated = peek() === '^';
156
- if (negated)
157
- position++;
158
- const ranges = [];
159
- while (peek() !== ']') {
160
- if (atEnd())
161
- throw new Unsupported();
162
- const start = readClassAtom();
163
- if (peek() === '-' && peek(1) !== ']' && peek(1) !== undefined && start.code !== undefined) {
164
- position++;
165
- const end = readClassAtom();
166
- if (end.code === undefined || end.code < start.code)
167
- throw new Unsupported();
168
- ranges.push([start.code, end.code]);
169
- continue;
170
- }
171
- if (start.ranges)
172
- ranges.push(...start.ranges);
173
- else if (start.code !== undefined)
174
- ranges.push([start.code, start.code]);
175
- }
176
- position++;
177
- const members = ignoreCase ? foldCase(ranges) : ranges;
178
- return { kind: 'char', ranges: negated ? complement(members) : normalize(members) };
179
- }
180
- // The group kind for the text after `(`, consuming its `?:`, `?=`, `?<!` or `?<name>` prefix.
181
- function readGroupKind() {
182
- if (peek() !== '?')
183
- return 'group';
184
- const opener = source.slice(position, position + 3);
185
- if (['?=', '?!'].includes(opener.slice(0, 2)) || ['?<=', '?<!'].includes(opener)) {
186
- position += opener.startsWith('?<') ? 3 : 2;
187
- return 'lookaround';
188
- }
189
- const nameEnd = source.indexOf('>', position);
190
- if (opener.startsWith('?:'))
191
- position += 2;
192
- else if (opener.startsWith('?<') && nameEnd > 0)
193
- position = nameEnd + 1;
194
- else
195
- throw new Unsupported();
196
- return 'group';
197
- }
198
- let groupDepth = 0;
199
- function parseGroup() {
200
- if (++groupDepth > 64)
201
- throw new Unsupported();
202
- try {
203
- position++;
204
- const kind = readGroupKind();
205
- const body = parseAlternation();
206
- if (peek() !== ')')
207
- throw new Unsupported();
208
- position++;
209
- return { kind, body };
210
- }
211
- finally {
212
- groupDepth--;
213
- }
214
- }
215
- // Consumes `length` characters and returns `node`.
216
- function consume(length, node) {
217
- position += length;
218
- return node;
219
- }
220
- function parseAtom() {
221
- const character = peek();
222
- if (character === '^' || character === '$')
223
- return consume(1, { kind: 'assert', anchor: character });
224
- if (character === '(')
225
- return parseGroup();
226
- if (character === '[')
227
- return parseClass();
228
- if (character === '.')
229
- return consume(1, charNode(everyCharacter));
230
- if (character === '\\' && (peek(1) === 'b' || peek(1) === 'B'))
231
- return consume(2, { kind: 'assert' });
232
- if (character === '\\') {
233
- const escape = readEscape(false);
234
- if (escape.ranges)
235
- return charNode(escape.ranges);
236
- if (escape.code === undefined)
237
- throw new Unsupported();
238
- return charNode([[escape.code, escape.code]]);
239
- }
240
- if (character === '*' ||
241
- character === '+' ||
242
- character === '?' ||
243
- character === ')' ||
244
- (character === '{' && /^\{\d+(,\d*)?\}/.test(source.slice(position))))
245
- throw new Unsupported();
246
- const code = codePointAt();
247
- return charNode([[code, code]]);
248
- }
249
- // `{n}`, `{n,}`, `{n,m}`, `*`, `+`, `?` (lazy or not), or undefined.
250
- function readQuantifier() {
251
- const character = peek();
252
- let bounds;
253
- if (character === '*')
254
- bounds = { min: 0, max: Infinity, length: 1 };
255
- else if (character === '+')
256
- bounds = { min: 1, max: Infinity, length: 1 };
257
- else if (character === '?')
258
- bounds = { min: 0, max: 1, length: 1 };
259
- else if (character === '{') {
260
- const braces = /^\{(\d+)(,(\d*))?\}/.exec(source.slice(position));
261
- if (!braces)
262
- return;
263
- const min = Number(braces[1]);
264
- const max = braces[2] === undefined ? min : braces[3] === '' ? Infinity : Number(braces[3]);
265
- bounds = { min, max, length: braces[0].length };
266
- }
267
- else
268
- return;
269
- position += bounds.length;
270
- if (peek() === '?')
271
- position++;
272
- return bounds;
273
- }
274
- function parseSequence() {
275
- const items = [];
276
- while (!atEnd() && peek() !== '|' && peek() !== ')') {
277
- const atom = parseAtom();
278
- const bounds = readQuantifier();
279
- if (!bounds) {
280
- items.push(atom);
281
- continue;
282
- }
283
- if (atom.kind === 'assert' || atom.kind === 'lookaround')
284
- throw new Unsupported();
285
- items.push({ kind: 'quant', body: atom, min: bounds.min, max: bounds.max });
286
- }
287
- return { kind: 'seq', items };
288
- }
289
- function parseAlternation() {
290
- const alternatives = [parseSequence()];
291
- while (peek() === '|') {
292
- position++;
293
- alternatives.push(parseSequence());
294
- }
295
- return alternatives.length === 1 ? alternatives[0] : { kind: 'alt', alternatives };
296
- }
297
- return function parse() {
298
- const tree = parseAlternation();
299
- if (!atEnd())
300
- throw new Unsupported();
301
- return tree;
302
- };
303
- }
304
19
  // ---- Analysis ----
305
20
  function nullable(node) {
306
21
  switch (node.kind) {
@@ -381,12 +96,38 @@ function unwrapGroups(node) {
381
96
  current = current.kind === 'group' ? current.body : current.items[0];
382
97
  return current;
383
98
  }
99
+ // The character set at each position of an alternative made only of single characters, or
100
+ // undefined when its length can vary.
101
+ function fixedPositions(node) {
102
+ const unwrapped = unwrapGroups(node);
103
+ if (unwrapped.kind === 'char')
104
+ return [unwrapped.ranges];
105
+ if (unwrapped.kind !== 'seq')
106
+ return;
107
+ const positions = [];
108
+ for (const item of unwrapped.items) {
109
+ const itemPositions = fixedPositions(item);
110
+ if (!itemPositions)
111
+ return;
112
+ positions.push(...itemPositions);
113
+ }
114
+ return positions;
115
+ }
116
+ // Same-length fixed alternatives such as `ab|ac` match the same text only when every position
117
+ // overlaps; sharing a first character alone leaves each iteration one way to match.
118
+ function alternativesCanMatchSameText(left, right) {
119
+ const leftPositions = fixedPositions(left);
120
+ const rightPositions = fixedPositions(right);
121
+ if (leftPositions && rightPositions && leftPositions.length === rightPositions.length) {
122
+ return leftPositions.every((positionRanges, index) => overlaps(positionRanges, rightPositions[index]));
123
+ }
124
+ return overlaps(firstSet(left), firstSet(right));
125
+ }
384
126
  function hasOverlappingAlternatives(node) {
385
127
  const body = unwrapGroups(node);
386
128
  if (body.kind !== 'alt')
387
129
  return false;
388
- const starts = body.alternatives.map(firstSet);
389
- return starts.some((start, index) => starts.slice(index + 1).some((other) => overlaps(start, other)));
130
+ return body.alternatives.some((alternative, index) => body.alternatives.slice(index + 1).some((other) => alternativesCanMatchSameText(alternative, other)));
390
131
  }
391
132
  // An unbounded loop whose iterations can split the same text in more than one way.
392
133
  function isAmbiguousLoop(node) {
@@ -428,39 +169,126 @@ function repeatedCharacters(node) {
428
169
  function canFail(node) {
429
170
  return !nullable(node) || node.kind === 'assert' || node.kind === 'lookaround';
430
171
  }
172
+ function isEveryCharacter(ranges) {
173
+ return ranges.length === 1 && ranges[0][0] === 0 && ranges[0][1] === maxCodePoint;
174
+ }
175
+ // The first atom of `node`, looking into groups and sequences, so `(^[\t ]*)` starts with `^`.
176
+ function leadingAtom(node) {
177
+ let current = node;
178
+ while (current.kind === 'group' || (current.kind === 'seq' && current.items.length > 0))
179
+ current = current.kind === 'group' ? current.body : current.items[0];
180
+ return current;
181
+ }
182
+ // `.*` alone, or a group that is `.*` after optional single characters only (`(\/?.*)`).
183
+ function isDotRunEnding(node) {
184
+ const body = unwrapGroups(node);
185
+ const items = body.kind === 'seq' ? body.items : [body];
186
+ const last = items.at(-1);
187
+ const characters = last && repeatedCharacters(last);
188
+ return (Boolean(characters && isEveryCharacter(characters)) &&
189
+ items.slice(0, -1).every((item) => !canFail(item) && edgeRunCharacters(item, false).length === 0));
190
+ }
431
191
  function isTrailingDotEndAnchor(items, index, followed) {
432
192
  if (followed || index === 0)
433
193
  return false;
434
- const first = items[0];
194
+ const first = leadingAtom(items[0]);
435
195
  if (first.kind !== 'assert' || first.anchor !== '^')
436
196
  return false;
437
197
  const tail = items.slice(index + 1);
438
198
  if (tail.length !== 1 || tail[0].kind !== 'assert' || tail[0].anchor !== '$')
439
199
  return false;
440
- const chars = repeatedCharacters(items[index]);
441
- return Boolean(chars && chars.length === 1 && chars[0][0] === 0 && chars[0][1] === maxCodePoint);
200
+ return isDotRunEnding(items[index]);
201
+ }
202
+ // The characters of the unbounded character repeats inside `node` that one end of its match can
203
+ // begin with, because everything between that end and the repeat can match empty: `\s*` in
204
+ // `(?:\(?\w*\)?\s*=>)?` from the start, or in `(?:x\s*)+` from the end. Assertions and required
205
+ // characters stop the walk.
206
+ function edgeRunCharacters(node, fromEnd) {
207
+ const characters = repeatedCharacters(node);
208
+ if (characters)
209
+ return characters;
210
+ switch (node.kind) {
211
+ case 'group':
212
+ return edgeRunCharacters(node.body, fromEnd);
213
+ case 'quant':
214
+ // A `{0}` body never runs. An unbounded loop whose body can match a single character
215
+ // (`(?:a\s*)+`) is itself a run over those characters.
216
+ if (node.max === 0)
217
+ return [];
218
+ if (node.max !== Infinity)
219
+ return edgeRunCharacters(node.body, fromEnd);
220
+ return normalize([...singleCharacters(node.body), ...edgeRunCharacters(node.body, fromEnd)]);
221
+ case 'alt':
222
+ return normalize(node.alternatives.flatMap((alternative) => edgeRunCharacters(alternative, fromEnd)));
223
+ case 'seq': {
224
+ const ranges = [];
225
+ const items = fromEnd ? [...node.items].reverse() : node.items;
226
+ for (const item of items) {
227
+ ranges.push(...edgeRunCharacters(item, fromEnd));
228
+ if (canFail(item))
229
+ break;
230
+ }
231
+ return normalize(ranges);
232
+ }
233
+ default:
234
+ return [];
235
+ }
236
+ }
237
+ // The characters `node` can match as a whole one-character match: `a` for `a\s*`.
238
+ function singleCharacters(node) {
239
+ switch (node.kind) {
240
+ case 'char':
241
+ return node.ranges;
242
+ case 'group':
243
+ return singleCharacters(node.body);
244
+ case 'alt':
245
+ return normalize(node.alternatives.flatMap(singleCharacters));
246
+ case 'quant':
247
+ return node.max === 0 || node.min > 1 ? [] : singleCharacters(node.body);
248
+ case 'seq': {
249
+ // An assertion limits where each turn can start, so turns cannot each take one character of a run.
250
+ if (node.items.some((item) => item.kind === 'assert' || item.kind === 'lookaround'))
251
+ return [];
252
+ const required = node.items.filter((item) => !nullable(item));
253
+ if (required.length > 1)
254
+ return [];
255
+ if (required.length === 1)
256
+ return singleCharacters(required[0]);
257
+ return normalize(node.items.flatMap(singleCharacters));
258
+ }
259
+ default:
260
+ return [];
261
+ }
262
+ }
263
+ // The items of a sequence with plain (unquantified, single-branch) groups spliced in, so
264
+ // `^a*(?:a+$)` is checked like `^a*a+$`.
265
+ function flattenGroups(items) {
266
+ return items.flatMap((item) => {
267
+ if (item.kind !== 'group' || item.body.kind === 'alt')
268
+ return [item];
269
+ return flattenGroups(item.body.kind === 'seq' ? item.body.items : [item.body]);
270
+ });
442
271
  }
443
272
  // Two unbounded repeats over overlapping characters with nothing required between them
444
273
  // (`\s+.*\s+$`,
445
274
  // `\w+\s*\w+$`) can split one run of n characters in n ways. The split is only retried when
446
275
  // something after them can fail, so `/\d+\w*/` alone is quiet. Repeats of longer bodies
447
276
  // (`(ab)+(ac)+`) are left alone: their first characters can overlap without any text matching both.
448
- function hasAmbiguousRun(items, followed) {
277
+ // A repeat at the edge of a group or loop counts too: the trailing `\s*` of `(?:\w+\(\)\s*)+` and
278
+ // a later `\s*` split the same run, as do `^\s*` and the `\s*` inside an optional `(?:\w*\s*=>)?`.
279
+ function hasAmbiguousRun(sequence, followed) {
280
+ const items = flattenGroups(sequence);
449
281
  // Characters of the repeats that the next item can take over because everything since them can
450
282
  // match empty.
451
283
  let reachable = [];
452
284
  for (const [index, item] of items.entries()) {
453
285
  const characters = repeatedCharacters(item);
454
- if (!characters) {
455
- if (canFail(item))
456
- reachable = [];
457
- continue;
458
- }
459
- if (overlaps(reachable, characters) &&
286
+ if (overlaps(reachable, characters ?? edgeRunCharacters(item, false)) &&
460
287
  (followed || items.slice(index + 1).some(canFail)) &&
461
288
  !isTrailingDotEndAnchor(items, index, followed))
462
289
  return true;
463
- reachable = nullable(item) ? normalize([...reachable, ...characters]) : characters;
290
+ const trailing = characters ?? edgeRunCharacters(item, true);
291
+ reachable = canFail(item) ? trailing : normalize([...reachable, ...trailing]);
464
292
  }
465
293
  return false;
466
294
  }
@@ -543,15 +371,24 @@ function fixedRegex(expression, checker, depth = 0) {
543
371
  return;
544
372
  return { source, flags };
545
373
  }
546
- // `text.slice(0, 200)`: a fixed-length cut keeps the input short enough.
374
+ // A cut at a huge literal such as `1e9` does not shorten the input in practice. A negative end
375
+ // is a prefix expression, not a numeric literal, so it never counts as a cap.
376
+ const maxTruncationLength = 10_000;
377
+ function isShortLimit(limit) {
378
+ return ts.isNumericLiteral(limit) && Number(limit.text) <= maxTruncationLength;
379
+ }
380
+ // `text.slice(0, 200)`: a fixed-length cut keeps the input short enough for polynomial patterns.
381
+ // `substring` swaps its arguments when the start is larger, so `substring(start, 200)` returns
382
+ // everything from 200 to `start`; it needs a literal start too.
547
383
  function isTruncated(subject) {
548
384
  const node = ts.skipOuterExpressions(subject);
549
385
  const method = ts.isCallExpression(node) ? methodName(node) : undefined;
550
- return (ts.isCallExpression(node) &&
551
- method !== undefined &&
552
- truncatingMethods.has(method) &&
553
- node.arguments.length === 2 &&
554
- ts.isNumericLiteral(ts.skipOuterExpressions(node.arguments[1])));
386
+ if (!ts.isCallExpression(node) || method === undefined || !truncatingMethods.has(method))
387
+ return false;
388
+ const [start, end] = node.arguments;
389
+ if (node.arguments.length !== 2 || !isShortLimit(ts.skipOuterExpressions(end)))
390
+ return false;
391
+ return method !== 'substring' || ts.isNumericLiteral(ts.skipOuterExpressions(start));
555
392
  }
556
393
  const parameterReason = 'Contextual: the text is a function parameter, so the finding applies only if callers pass untrusted or very long input.';
557
394
  // The parameter a subject is built from (`input`, `String(input)`, `input.trim()`), or undefined
@@ -587,16 +424,23 @@ const growthWording = {
587
424
  exponential: 'exponentially',
588
425
  polynomial: 'in polynomial time',
589
426
  };
427
+ // A length cap silences only polynomial findings, so exponential ones are told to rewrite.
428
+ const remedyWording = {
429
+ exponential: 'Rewrite the pattern to remove the nested or overlapping repetition so no part can match the same text in two ways; a length cap does not make it safe.',
430
+ polynomial: 'Rewrite the pattern so no part can match the same text in two ways, or cap the input length first.',
431
+ };
590
432
  function message(label, kind) {
591
- return `This regular expression can backtrack ${growthWording[kind]} on \`${label}\` (ReDoS), blocking the event loop. Rewrite the pattern so no part can match the same text in two ways, or cap the input length first.`;
433
+ return `This regular expression can backtrack ${growthWording[kind]} on \`${label}\` (ReDoS), blocking the event loop. ${remedyWording[kind]}`;
592
434
  }
593
435
  function checkCall(node, context) {
594
436
  const parts = regexAndSubject(node);
595
- if (!parts?.regex || !parts.subject || ts.isSpreadElement(parts.subject) || isTruncated(parts.subject))
437
+ if (!parts?.regex || !parts.subject || ts.isSpreadElement(parts.subject))
596
438
  return;
597
439
  const regex = fixedRegex(parts.regex, context.checker);
598
440
  const kind = regex && backtrackingKind(regex.source, regex.flags);
599
- if (!kind)
441
+ // A cap keeps polynomial work small, but exponential backtracking is already catastrophic at a
442
+ // few dozen characters, so a cut such as `slice(0, 254)` does not make it safe.
443
+ if (!kind || (kind === 'polynomial' && isTruncated(parts.subject)))
600
444
  return;
601
445
  const trace = context.taint.trace(parts.subject, 'regex');
602
446
  if (trace)