circle-ir 4.21.0 → 4.22.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 (58) hide show
  1. package/dist/analysis/config-loader.d.ts.map +1 -1
  2. package/dist/analysis/config-loader.js +6 -0
  3. package/dist/analysis/config-loader.js.map +1 -1
  4. package/dist/analysis/findings.d.ts.map +1 -1
  5. package/dist/analysis/findings.js +14 -6
  6. package/dist/analysis/findings.js.map +1 -1
  7. package/dist/analysis/passes/_js-crypto-binding.d.ts +53 -0
  8. package/dist/analysis/passes/_js-crypto-binding.d.ts.map +1 -0
  9. package/dist/analysis/passes/_js-crypto-binding.js +123 -0
  10. package/dist/analysis/passes/_js-crypto-binding.js.map +1 -0
  11. package/dist/analysis/passes/hardcoded-secret-argument-pass.d.ts +85 -0
  12. package/dist/analysis/passes/hardcoded-secret-argument-pass.d.ts.map +1 -0
  13. package/dist/analysis/passes/hardcoded-secret-argument-pass.js +351 -0
  14. package/dist/analysis/passes/hardcoded-secret-argument-pass.js.map +1 -0
  15. package/dist/analysis/passes/language-sources-pass.d.ts +21 -1
  16. package/dist/analysis/passes/language-sources-pass.d.ts.map +1 -1
  17. package/dist/analysis/passes/language-sources-pass.js +264 -9
  18. package/dist/analysis/passes/language-sources-pass.js.map +1 -1
  19. package/dist/analysis/passes/missing-auth-middleware-pass.d.ts +56 -0
  20. package/dist/analysis/passes/missing-auth-middleware-pass.d.ts.map +1 -0
  21. package/dist/analysis/passes/missing-auth-middleware-pass.js +255 -0
  22. package/dist/analysis/passes/missing-auth-middleware-pass.js.map +1 -0
  23. package/dist/analysis/passes/prototype-pollution-pass.d.ts +78 -0
  24. package/dist/analysis/passes/prototype-pollution-pass.d.ts.map +1 -0
  25. package/dist/analysis/passes/prototype-pollution-pass.js +736 -0
  26. package/dist/analysis/passes/prototype-pollution-pass.js.map +1 -0
  27. package/dist/analysis/passes/redos-regex-literal-pass.d.ts +106 -0
  28. package/dist/analysis/passes/redos-regex-literal-pass.d.ts.map +1 -0
  29. package/dist/analysis/passes/redos-regex-literal-pass.js +637 -0
  30. package/dist/analysis/passes/redos-regex-literal-pass.js.map +1 -0
  31. package/dist/analysis/passes/scan-secrets-pass.d.ts +3 -0
  32. package/dist/analysis/passes/scan-secrets-pass.d.ts.map +1 -1
  33. package/dist/analysis/passes/scan-secrets-pass.js +3 -3
  34. package/dist/analysis/passes/scan-secrets-pass.js.map +1 -1
  35. package/dist/analysis/passes/taint-propagation-pass.js +24 -0
  36. package/dist/analysis/passes/taint-propagation-pass.js.map +1 -1
  37. package/dist/analysis/passes/weak-crypto-pass.d.ts.map +1 -1
  38. package/dist/analysis/passes/weak-crypto-pass.js +7 -1
  39. package/dist/analysis/passes/weak-crypto-pass.js.map +1 -1
  40. package/dist/analysis/passes/weak-hash-pass.d.ts.map +1 -1
  41. package/dist/analysis/passes/weak-hash-pass.js +7 -1
  42. package/dist/analysis/passes/weak-hash-pass.js.map +1 -1
  43. package/dist/analysis/passes/weak-password-hash-pass.d.ts.map +1 -1
  44. package/dist/analysis/passes/weak-password-hash-pass.js +7 -1
  45. package/dist/analysis/passes/weak-password-hash-pass.js.map +1 -1
  46. package/dist/analyzer.d.ts.map +1 -1
  47. package/dist/analyzer.js +12 -0
  48. package/dist/analyzer.js.map +1 -1
  49. package/dist/browser/circle-ir.js +1905 -152
  50. package/dist/core/circle-ir-core.cjs +70 -79
  51. package/dist/core/circle-ir-core.js +70 -79
  52. package/dist/core/extractors/imports.js +18 -1
  53. package/dist/core/extractors/imports.js.map +1 -1
  54. package/dist/types/index.d.ts +5 -0
  55. package/dist/types/index.d.ts.map +1 -1
  56. package/dist/wasm/web-tree-sitter.wasm +0 -0
  57. package/docs/SPEC.md +1 -0
  58. package/package.json +2 -2
@@ -0,0 +1,736 @@
1
+ /**
2
+ * Pass: prototype-pollution (CWE-1321, category: security)
3
+ *
4
+ * Pattern pass for JavaScript / TypeScript. Three shapes write an
5
+ * attacker-chosen key into an object at depth, so a `__proto__` (or
6
+ * `constructor` then `prototype`) key reaches `Object.prototype`:
7
+ *
8
+ * 1. recursive merge — a function iterates the keys of one object
9
+ * (`for (k in src)`, `for (k of Object.keys(src))`, `Object.entries`,
10
+ * `Object.keys(src).forEach(k => …)`), writes `target[k] = …`, and
11
+ * calls itself with `target[k]` among the arguments (a deep clone that
12
+ * recurses only on `src[k]` writes into fresh objects and is not one);
13
+ * 2. set by path — a function walks an object along a key path
14
+ * (`cur = cur[k]`, or `cur[k] = cur[k] || {}`) inside a loop and
15
+ * writes `cur[…] = …`, where the keys come from `path.split('.')` (any
16
+ * non-empty separator) or from a collection named like a key path
17
+ * (`path`, `keys`, `segments`, `parts`, `props`);
18
+ * 3. request keys — `obj[a][b] = …` where both `a` and `b` come from the
19
+ * HTTP request (`const { a, b } = req.body`, `const a = req.query.x`,
20
+ * or `req.body.x` written in the brackets).
21
+ *
22
+ * Precision (abstain rather than guess):
23
+ * - The function (shapes 1 and 2) or handler (shape 3) mentions
24
+ * `__proto__`, `constructor` or `prototype` in a string literal or as
25
+ * a name, or passes the key to a function whose name says it checks
26
+ * the key (`isSafeKey(k)`, `isPrototypeKey(k)`, `assertAllowed(k)`):
27
+ * that is the guard.
28
+ * - The written object was made with `Object.create(null)`.
29
+ * - A shallow copy (no recursion, no path walk) is not reported: writing
30
+ * `__proto__` one level deep changes only that object's own prototype.
31
+ * - Character iteration (`word.split('')`, `for (const ch of word)`) is not
32
+ * a key path: one character cannot spell `__proto__`.
33
+ * - Library calls (`_.merge`, `$.extend`, `Object.assign`) are left to the
34
+ * taint sinks that already model them.
35
+ *
36
+ * Detection runs on the source text with strings and comments masked, so
37
+ * braces or keywords inside literals never count.
38
+ */
39
+ const KEYWORDS = new Set([
40
+ 'if', 'for', 'while', 'switch', 'catch', 'with', 'return', 'typeof', 'function', 'new', 'await',
41
+ 'yield', 'delete', 'void', 'in', 'of', 'do', 'else', 'try', 'finally', 'throw', 'case', 'super',
42
+ ]);
43
+ const PATH_NAME_WORDS = ['path', 'keys', 'segments', 'segs', 'parts', 'props', 'keypath', 'fields'];
44
+ const GUARD_NAME_WORDS = [
45
+ 'safe', 'proto', 'pollut', 'forbid', 'unsafe', 'danger', 'block', 'allow', 'reserved', 'valid', 'deny', 'illegal',
46
+ ];
47
+ const REQUEST_ROOTS = new Set(['req', 'request']);
48
+ const REQUEST_BAGS = new Set(['body', 'query', 'params']);
49
+ const MAX_CODE_LENGTH = 1_000_000;
50
+ function isIdentStart(ch) {
51
+ return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$';
52
+ }
53
+ function isIdentChar(ch) {
54
+ return isIdentStart(ch) || (ch >= '0' && ch <= '9');
55
+ }
56
+ function isIdent(t) {
57
+ return !!t && isIdentStart(t[0]) && !KEYWORDS.has(t);
58
+ }
59
+ /**
60
+ * Blank the content of comments and string / template literals (quotes kept,
61
+ * newlines kept, so offsets and line numbers are unchanged). Regex literals
62
+ * are not recognised; a stray quote inside one only blanks to the line end.
63
+ */
64
+ export function maskLiterals(code) {
65
+ const out = code.split('');
66
+ let i = 0;
67
+ const n = code.length;
68
+ while (i < n) {
69
+ const ch = code[i];
70
+ if (ch === '/' && code[i + 1] === '/') {
71
+ while (i < n && code[i] !== '\n')
72
+ out[i++] = ' ';
73
+ continue;
74
+ }
75
+ if (ch === '/' && code[i + 1] === '*') {
76
+ out[i] = ' ';
77
+ out[i + 1] = ' ';
78
+ i += 2;
79
+ while (i < n && !(code[i] === '*' && code[i + 1] === '/')) {
80
+ if (code[i] !== '\n')
81
+ out[i] = ' ';
82
+ i++;
83
+ }
84
+ if (i < n) {
85
+ out[i] = ' ';
86
+ out[i + 1] = ' ';
87
+ i += 2;
88
+ }
89
+ continue;
90
+ }
91
+ if (ch === '"' || ch === "'" || ch === '`') {
92
+ i++;
93
+ while (i < n && code[i] !== ch) {
94
+ if (code[i] === '\n' && ch !== '`')
95
+ break;
96
+ if (code[i] === '\\') {
97
+ out[i] = ' ';
98
+ i++;
99
+ if (i < n && code[i] !== '\n')
100
+ out[i] = ' ';
101
+ i++;
102
+ continue;
103
+ }
104
+ if (code[i] !== '\n')
105
+ out[i] = ' ';
106
+ i++;
107
+ }
108
+ i++;
109
+ continue;
110
+ }
111
+ i++;
112
+ }
113
+ return out.join('');
114
+ }
115
+ const PUNCT3 = ['===', '!==', '??=', '||=', '&&=', '...'];
116
+ const PUNCT2 = ['==', '!=', '=>', '||', '&&', '??', '<=', '>=', '+=', '-=', '?.', '++', '--'];
117
+ export function tokenize(masked) {
118
+ const toks = [];
119
+ let i = 0;
120
+ const n = masked.length;
121
+ while (i < n) {
122
+ const ch = masked[i];
123
+ if (ch === ' ' || ch === '\n' || ch === '\t' || ch === '\r') {
124
+ i++;
125
+ continue;
126
+ }
127
+ if (isIdentStart(ch)) {
128
+ const s = i;
129
+ while (i < n && isIdentChar(masked[i]))
130
+ i++;
131
+ toks.push({ t: masked.slice(s, i), pos: s, m: -1 });
132
+ continue;
133
+ }
134
+ if (ch >= '0' && ch <= '9') {
135
+ const s = i;
136
+ while (i < n && (isIdentChar(masked[i]) || masked[i] === '.'))
137
+ i++;
138
+ toks.push({ t: masked.slice(s, i), pos: s, m: -1 });
139
+ continue;
140
+ }
141
+ if (ch === '"' || ch === "'" || ch === '`') {
142
+ const s = i;
143
+ i++;
144
+ while (i < n && masked[i] !== ch && masked[i] !== '\n')
145
+ i++;
146
+ i++;
147
+ toks.push({ t: '"', pos: s, m: -1 });
148
+ continue;
149
+ }
150
+ const three = masked.slice(i, i + 3);
151
+ if (PUNCT3.includes(three)) {
152
+ toks.push({ t: three, pos: i, m: -1 });
153
+ i += 3;
154
+ continue;
155
+ }
156
+ const two = masked.slice(i, i + 2);
157
+ if (PUNCT2.includes(two)) {
158
+ toks.push({ t: two, pos: i, m: -1 });
159
+ i += 2;
160
+ continue;
161
+ }
162
+ toks.push({ t: ch, pos: i, m: -1 });
163
+ i++;
164
+ }
165
+ // Pair brackets in one pass so every lookup below is O(1).
166
+ const stack = [];
167
+ for (let j = 0; j < toks.length; j++) {
168
+ const t = toks[j].t;
169
+ if (t === '(' || t === '[' || t === '{')
170
+ stack.push(j);
171
+ else if (t === ')' || t === ']' || t === '}') {
172
+ const want = t === ')' ? '(' : t === ']' ? '[' : '{';
173
+ // Drop unmatched openers of another kind (a regex literal's bracket, say).
174
+ while (stack.length > 0 && toks[stack[stack.length - 1]].t !== want)
175
+ stack.pop();
176
+ const o = stack.pop();
177
+ if (o !== undefined) {
178
+ toks[o].m = j;
179
+ toks[j].m = o;
180
+ }
181
+ }
182
+ }
183
+ return toks;
184
+ }
185
+ /** Index of the token closing the bracket opened at `i`, or -1. */
186
+ function matchClose(toks, i) {
187
+ return toks[i]?.m ?? -1;
188
+ }
189
+ /** Index of the token opening the bracket closed at `i`, or -1. */
190
+ function matchOpen(toks, i) {
191
+ return toks[i]?.m ?? -1;
192
+ }
193
+ function paramNames(toks, open, close) {
194
+ const out = [];
195
+ let depth = 0;
196
+ let expectName = true;
197
+ for (let j = open + 1; j < close; j++) {
198
+ const t = toks[j].t;
199
+ if (t === '(' || t === '[' || t === '{')
200
+ depth++;
201
+ else if (t === ')' || t === ']' || t === '}')
202
+ depth--;
203
+ else if (depth === 0 && t === ',') {
204
+ expectName = true;
205
+ continue;
206
+ }
207
+ if (depth === 0 && expectName && isIdent(t) && t !== 'this') {
208
+ out.push(t);
209
+ expectName = false;
210
+ }
211
+ else if (depth === 0 && t !== '...')
212
+ expectName = false;
213
+ }
214
+ return out;
215
+ }
216
+ /** The name a function expression or arrow is bound to (`const f = …`, `f: …`), or null. */
217
+ function boundName(toks, start) {
218
+ let k = start - 1;
219
+ if (toks[k]?.t === 'async')
220
+ k--;
221
+ if (toks[k]?.t === '=' || toks[k]?.t === ':')
222
+ return isIdent(toks[k - 1]?.t) ? toks[k - 1].t : null;
223
+ return null;
224
+ }
225
+ export function findFunctions(toks) {
226
+ const fns = [];
227
+ for (let i = 0; i < toks.length; i++) {
228
+ if (toks[i].t !== '{')
229
+ continue;
230
+ const prev = toks[i - 1]?.t;
231
+ let fn = null;
232
+ if (prev === '=>') {
233
+ const close = matchClose(toks, i);
234
+ if (close < 0)
235
+ continue;
236
+ let start = i - 2;
237
+ let params = [];
238
+ if (toks[start]?.t === ')') {
239
+ const po = matchOpen(toks, start);
240
+ if (po < 0)
241
+ continue;
242
+ params = paramNames(toks, po, start);
243
+ start = po;
244
+ }
245
+ else if (isIdent(toks[start]?.t)) {
246
+ params = [toks[start].t];
247
+ }
248
+ fn = { name: boundName(toks, start), open: i, close, params };
249
+ }
250
+ else if (prev === ')') {
251
+ const pc = i - 1;
252
+ const po = matchOpen(toks, pc);
253
+ if (po < 1)
254
+ continue;
255
+ const before = toks[po - 1].t;
256
+ const close = matchClose(toks, i);
257
+ if (close < 0)
258
+ continue;
259
+ const params = paramNames(toks, po, pc);
260
+ if (before === 'function') {
261
+ fn = { name: boundName(toks, po - 1), open: i, close, params };
262
+ }
263
+ else if (isIdent(before)) {
264
+ const kw = toks[po - 2]?.t;
265
+ if (kw === 'function')
266
+ fn = { name: before, open: i, close, params };
267
+ else if (kw !== '.' && kw !== 'new')
268
+ fn = { name: before, open: i, close, params }; // method shorthand
269
+ }
270
+ }
271
+ if (!fn && prev !== undefined && prev !== '=>' && prev !== ')') {
272
+ // TypeScript return type: `function f(a: T): R {` / `m(a): Promise<R> {` / `): void {`.
273
+ for (let j = i - 1; j > Math.max(0, i - 16); j--) {
274
+ if (toks[j].t === ':' && toks[j - 1]?.t === ')') {
275
+ const pc = j - 1;
276
+ const po = matchOpen(toks, pc);
277
+ if (po < 1)
278
+ break;
279
+ const before = toks[po - 1].t;
280
+ const close = matchClose(toks, i);
281
+ if (close < 0)
282
+ break;
283
+ const params = paramNames(toks, po, pc);
284
+ if (before === 'function')
285
+ fn = { name: boundName(toks, po - 1), open: i, close, params };
286
+ else if (isIdent(before) && toks[po - 2]?.t !== '.')
287
+ fn = { name: before, open: i, close, params };
288
+ break;
289
+ }
290
+ if (toks[j].t === '{' || toks[j].t === '}' || toks[j].t === ';')
291
+ break;
292
+ }
293
+ }
294
+ if (fn)
295
+ fns.push(fn);
296
+ }
297
+ return fns;
298
+ }
299
+ /** End index (exclusive) of a member chain `a.b.c` starting at `i`; returns the chain text too. */
300
+ function chainAt(toks, i) {
301
+ if (!isIdent(toks[i]?.t) && toks[i]?.t !== 'this')
302
+ return null;
303
+ let text = toks[i].t;
304
+ let j = i + 1;
305
+ while ((toks[j]?.t === '.' || toks[j]?.t === '?.') && isIdent(toks[j + 1]?.t)) {
306
+ text += '.' + toks[j + 1].t;
307
+ j += 2;
308
+ }
309
+ return { text, end: j };
310
+ }
311
+ /** Is `toks[j]` the plain assignment operator (not `==`, `===`, `=>`)? */
312
+ function isAssign(t) {
313
+ return t === '=' || t === '||=' || t === '??=' || t === '&&=';
314
+ }
315
+ function lineOf(code, pos) {
316
+ let line = 1;
317
+ for (let i = code.lastIndexOf('\n', pos - 1); i >= 0; i = code.lastIndexOf('\n', i - 1))
318
+ line++;
319
+ return line;
320
+ }
321
+ /** True when the raw text of a range names a prototype key, or the key goes through a checking function. */
322
+ function hasGuard(raw, toks, from, to, keys) {
323
+ if (raw.includes('__proto__') || raw.includes('constructor') || raw.includes('prototype'))
324
+ return true;
325
+ for (let j = from; j < to; j++) {
326
+ const t = toks[j].t;
327
+ if (!isIdent(t) || toks[j + 1]?.t !== '(')
328
+ continue;
329
+ const lower = t.toLowerCase();
330
+ // A set / list membership test on the key (`BLOCKED.has(k)`, `ALLOWED.includes(k)`) is a key check.
331
+ const membership = toks[j - 1]?.t === '.' && (t === 'has' || t === 'includes' || t === 'indexOf');
332
+ if (!membership && !GUARD_NAME_WORDS.some((w) => lower.includes(w)))
333
+ continue;
334
+ const close = matchClose(toks, j + 1);
335
+ for (let k = j + 2; k < close; k++)
336
+ if (keys.has(toks[k].t))
337
+ return true;
338
+ }
339
+ return false;
340
+ }
341
+ /** Names written as `X = Object.create(null)` in a range. */
342
+ function nullProtoNames(toks, from, to) {
343
+ const out = new Set();
344
+ for (let j = from; j + 6 < to; j++) {
345
+ if (toks[j + 1].t === '=' && isIdent(toks[j].t) && toks[j + 2].t === 'Object' && toks[j + 3].t === '.' &&
346
+ toks[j + 4].t === 'create' && toks[j + 5].t === '(' && toks[j + 6].t === 'null')
347
+ out.add(toks[j].t);
348
+ }
349
+ return out;
350
+ }
351
+ /** Loop variables bound to the keys of an object inside `[from, to)`. */
352
+ function keyLoops(toks, from, to) {
353
+ const out = [];
354
+ for (let j = from; j < to; j++) {
355
+ const t = toks[j].t;
356
+ if (t === 'for' && toks[j + 1]?.t === '(') {
357
+ let k = j + 2;
358
+ if (toks[k]?.t === 'const' || toks[k]?.t === 'let' || toks[k]?.t === 'var')
359
+ k++;
360
+ let key = null;
361
+ if (isIdent(toks[k]?.t)) {
362
+ key = toks[k].t;
363
+ k++;
364
+ }
365
+ else if (toks[k]?.t === '[' && isIdent(toks[k + 1]?.t)) {
366
+ key = toks[k + 1].t;
367
+ const c = matchClose(toks, k);
368
+ if (c < 0)
369
+ continue;
370
+ k = c + 1;
371
+ }
372
+ if (!key)
373
+ continue;
374
+ if (toks[k]?.t === 'in') {
375
+ const c = chainAt(toks, k + 1);
376
+ if (c && toks[c.end]?.t === ')')
377
+ out.push({ key, source: c.text });
378
+ }
379
+ else if (toks[k]?.t === 'of' && toks[k + 1]?.t === 'Object' && toks[k + 2]?.t === '.' &&
380
+ ['keys', 'entries', 'getOwnPropertyNames'].includes(toks[k + 3]?.t ?? '') && toks[k + 4]?.t === '(') {
381
+ const c = chainAt(toks, k + 5);
382
+ if (c && toks[c.end]?.t === ')')
383
+ out.push({ key, source: c.text });
384
+ }
385
+ }
386
+ else if (t === 'Object' && toks[j + 1]?.t === '.' && (toks[j + 2]?.t === 'keys' || toks[j + 2]?.t === 'entries') &&
387
+ toks[j + 3]?.t === '(') {
388
+ const c = chainAt(toks, j + 4);
389
+ if (!c || toks[c.end]?.t !== ')')
390
+ continue;
391
+ let k = c.end + 1;
392
+ if (toks[k]?.t !== '.' || toks[k + 1]?.t !== 'forEach' || toks[k + 2]?.t !== '(')
393
+ continue;
394
+ k += 3;
395
+ if (toks[k]?.t === 'function')
396
+ k++;
397
+ if (toks[k]?.t === '(')
398
+ k++;
399
+ if (toks[k]?.t === '[')
400
+ k++;
401
+ if (isIdent(toks[k]?.t))
402
+ out.push({ key: toks[k].t, source: c.text });
403
+ }
404
+ }
405
+ return out;
406
+ }
407
+ /** Text of the member chain that ends just before token `k` (`a.b` for `a.b[k]`), or null. */
408
+ function chainBefore(toks, k) {
409
+ let j = k - 1;
410
+ if (!isIdent(toks[j]?.t) && toks[j]?.t !== 'this')
411
+ return null;
412
+ const parts = [toks[j].t];
413
+ while ((toks[j - 1]?.t === '.' || toks[j - 1]?.t === '?.') && (isIdent(toks[j - 2]?.t) || toks[j - 2]?.t === 'this')) {
414
+ parts.unshift(toks[j - 2].t);
415
+ j -= 2;
416
+ }
417
+ return parts.join('.');
418
+ }
419
+ /**
420
+ * Shape 1: recursive merge. The function writes `target[key] = …` and recurses with
421
+ * `target[key]` as an argument: with `key === '__proto__'` that argument is
422
+ * `Object.prototype`, and the recursive call writes into it. A deep clone that
423
+ * recurses only on the source (`clone(src[key])`) writes into fresh objects and is
424
+ * not reported.
425
+ */
426
+ function recursiveMerge(toks, fn) {
427
+ if (!fn.name)
428
+ return [];
429
+ const out = [];
430
+ for (const loop of keyLoops(toks, fn.open, fn.close)) {
431
+ // Targets the function recurses into: `fn(…, target[key], …)`.
432
+ const recursedTargets = new Set();
433
+ for (let j = fn.open + 1; j < fn.close; j++) {
434
+ if (toks[j].t !== fn.name || toks[j + 1]?.t !== '(')
435
+ continue;
436
+ const prev = toks[j - 1]?.t;
437
+ if (prev === 'function' || (prev === '.' && toks[j - 2]?.t !== 'this'))
438
+ continue;
439
+ const close = matchClose(toks, j + 1);
440
+ for (let k = j + 2; k + 2 < close; k++) {
441
+ if (toks[k].t === '[' && toks[k + 1].t === loop.key && toks[k + 2].t === ']') {
442
+ const t = chainBefore(toks, k);
443
+ if (t && t !== loop.source)
444
+ recursedTargets.add(t);
445
+ }
446
+ }
447
+ }
448
+ if (recursedTargets.size === 0)
449
+ continue;
450
+ for (let j = fn.open + 1; j < fn.close; j++) {
451
+ if (toks[j - 1]?.t === '.')
452
+ continue;
453
+ const c = chainAt(toks, j);
454
+ if (!c)
455
+ continue;
456
+ const k = c.end;
457
+ if (recursedTargets.has(c.text) && toks[k]?.t === '[' && toks[k + 1]?.t === loop.key && toks[k + 2]?.t === ']' &&
458
+ isAssign(toks[k + 3]?.t)) {
459
+ out.push({ pos: toks[j].pos, target: c.text, key: loop.key });
460
+ break;
461
+ }
462
+ }
463
+ }
464
+ return out;
465
+ }
466
+ function isPathName(name) {
467
+ const lower = name.toLowerCase();
468
+ return PATH_NAME_WORDS.some((w) => lower === w || lower.endsWith(w));
469
+ }
470
+ /**
471
+ * Shape 2: set by path. The function holds a key path (`parts = path.split('.')`,
472
+ * or a loop over a collection named like one), walks a cursor along it inside a
473
+ * loop (`cur = cur[k]`, `cur = cur[k] || (cur[k] = {})`, or a `reduce((o, k) => …)`
474
+ * callback writing `o[k] = o[k] || {}`), and writes `cur[k] = …` with a key taken
475
+ * from the path. A cache or map filled with `m[k] = m[k] || {}` and never walked is
476
+ * not a path walk; a write whose key does not come from the path is not reported.
477
+ */
478
+ function setByPath(toks, raw, base, fn) {
479
+ let hasLoop = false;
480
+ let pathEvidence = false;
481
+ /** Names that hold the path or one of its keys. */
482
+ const pathNames = new Set();
483
+ for (let j = fn.open + 1; j < fn.close; j++) {
484
+ const t = toks[j].t;
485
+ if (t === 'for' || t === 'while' || t === 'forEach' || t === 'reduce')
486
+ hasLoop = true;
487
+ if (t === 'split' && toks[j - 1]?.t === '.' && toks[j + 1]?.t === '(') {
488
+ const arg = toks[j + 2];
489
+ let real = false;
490
+ if (arg && arg.t === '"') {
491
+ const q = raw[arg.pos - base];
492
+ real = raw[arg.pos - base + 1] !== q; // not `split('')`
493
+ }
494
+ else if (arg && arg.t === '/') {
495
+ real = true;
496
+ }
497
+ if (real) {
498
+ pathEvidence = true;
499
+ // `const parts = path.split('.')` — find the name the split is bound to.
500
+ let k = j - 2;
501
+ while (k > fn.open && (isIdent(toks[k]?.t) || toks[k]?.t === '.' || toks[k]?.t === ')' || toks[k]?.t === '(')) {
502
+ if (toks[k].t === ')') {
503
+ const o = matchOpen(toks, k);
504
+ if (o < 0)
505
+ break;
506
+ k = o - 1;
507
+ continue;
508
+ }
509
+ k--;
510
+ }
511
+ if (toks[k]?.t === '=' && isIdent(toks[k - 1]?.t))
512
+ pathNames.add(toks[k - 1].t);
513
+ }
514
+ }
515
+ if (t === 'for' && toks[j + 1]?.t === '(') {
516
+ const close = matchClose(toks, j + 1);
517
+ for (let k = j + 2; k < close; k++) {
518
+ if (toks[k].t === 'of' || toks[k].t === 'in') {
519
+ const c = chainAt(toks, k + 1);
520
+ const last = c ? c.text.split('.').pop() ?? '' : '';
521
+ if (c && (isPathName(last) || pathNames.has(last))) {
522
+ pathEvidence = true;
523
+ if (isIdent(toks[k - 1]?.t))
524
+ pathNames.add(toks[k - 1].t);
525
+ }
526
+ }
527
+ }
528
+ }
529
+ if ((t === 'forEach' || t === 'reduce') && toks[j - 1]?.t === '.') {
530
+ const coll = toks[j - 2]?.t;
531
+ const isSplit = toks[j - 2]?.t === ')' && toks[matchOpen(toks, j - 2) - 1]?.t === 'split';
532
+ if ((isIdent(coll) && (isPathName(coll) || pathNames.has(coll))) || isSplit) {
533
+ pathEvidence = true;
534
+ // Callback parameters: `forEach((k) =>`, `reduce((o, k) =>`.
535
+ let k = j + 2;
536
+ if (toks[k]?.t === 'function')
537
+ k++;
538
+ if (toks[k]?.t === '(') {
539
+ const c = matchClose(toks, k);
540
+ for (const n of paramNames(toks, k, c))
541
+ pathNames.add(n);
542
+ }
543
+ else if (isIdent(toks[k]?.t)) {
544
+ pathNames.add(toks[k].t);
545
+ }
546
+ }
547
+ }
548
+ }
549
+ if (!hasLoop || !pathEvidence)
550
+ return [];
551
+ // Names derived from a path name: `const p = parts[i]`, `const last = parts.pop()`.
552
+ for (let j = fn.open + 1; j < fn.close; j++) {
553
+ if ((toks[j].t === 'const' || toks[j].t === 'let' || toks[j].t === 'var') && isIdent(toks[j + 1]?.t) && toks[j + 2]?.t === '=' &&
554
+ pathNames.has(toks[j + 3]?.t ?? '') && (toks[j + 4]?.t === '[' || toks[j + 4]?.t === '.')) {
555
+ pathNames.add(toks[j + 1].t);
556
+ }
557
+ }
558
+ // Cursors: reassigned along the path (`x = x[k]`, `x = x[k] || …`), or the
559
+ // accumulator of a `reduce((x, k) => …)` callback.
560
+ const cursors = new Set();
561
+ for (let j = fn.open + 1; j < fn.close; j++) {
562
+ const x = toks[j].t;
563
+ if (x === 'reduce' && toks[j - 1]?.t === '.' && toks[j + 1]?.t === '(' && toks[j + 2]?.t === '(' && isIdent(toks[j + 3]?.t)) {
564
+ cursors.add(toks[j + 3].t);
565
+ }
566
+ if (!isIdent(x) || toks[j - 1]?.t === '.')
567
+ continue;
568
+ if (toks[j + 1]?.t === '=' && toks[j + 2]?.t === x && toks[j + 3]?.t === '[')
569
+ cursors.add(x);
570
+ }
571
+ const out = [];
572
+ for (const x of cursors) {
573
+ // A computed write through the cursor whose key comes from the path: `x[k] = …`.
574
+ for (let j = fn.open + 1; j < fn.close; j++) {
575
+ if (toks[j].t !== x || toks[j - 1]?.t === '.' || toks[j + 1]?.t !== '[')
576
+ continue;
577
+ const c = matchClose(toks, j + 1);
578
+ if (c < 0 || !isAssign(toks[c + 1]?.t))
579
+ continue;
580
+ let key = null;
581
+ for (let k = j + 2; k < c; k++)
582
+ if (pathNames.has(toks[k].t)) {
583
+ key = toks[k].t;
584
+ break;
585
+ }
586
+ if (!key)
587
+ continue;
588
+ out.push({ pos: toks[j].pos, target: x, key });
589
+ break;
590
+ }
591
+ }
592
+ return out;
593
+ }
594
+ /** Names bound from the HTTP request inside `[from, to)`: `const { a } = req.body`, `const a = req.query.x`. */
595
+ function requestNames(toks, from, to) {
596
+ const out = new Set();
597
+ const isBag = (k) => REQUEST_ROOTS.has(toks[k]?.t ?? '') && toks[k + 1]?.t === '.' && REQUEST_BAGS.has(toks[k + 2]?.t ?? '');
598
+ for (let j = from; j < to; j++) {
599
+ const t = toks[j].t;
600
+ if (t !== 'const' && t !== 'let' && t !== 'var')
601
+ continue;
602
+ if (toks[j + 1]?.t === '{') {
603
+ const close = matchClose(toks, j + 1);
604
+ if (close < 0 || toks[close + 1]?.t !== '=' || !isBag(close + 2))
605
+ continue;
606
+ let depth = 0;
607
+ for (let k = j + 2; k < close; k++) {
608
+ const s = toks[k].t;
609
+ if (s === '{' || s === '[')
610
+ depth++;
611
+ else if (s === '}' || s === ']')
612
+ depth--;
613
+ else if (depth === 0 && isIdent(s) && toks[k + 1]?.t !== ':')
614
+ out.add(s);
615
+ }
616
+ }
617
+ else if (isIdent(toks[j + 1]?.t) && toks[j + 2]?.t === '=' && isBag(j + 3)) {
618
+ out.add(toks[j + 1].t);
619
+ }
620
+ }
621
+ return out;
622
+ }
623
+ /** Is the bracket content `[k]` request-controlled? */
624
+ function requestKey(toks, open, close, names) {
625
+ if (close === open + 2 && names.has(toks[open + 1].t))
626
+ return toks[open + 1].t;
627
+ const k = open + 1;
628
+ if (REQUEST_ROOTS.has(toks[k]?.t ?? '') && toks[k + 1]?.t === '.' && REQUEST_BAGS.has(toks[k + 2]?.t ?? '') &&
629
+ toks[k + 3]?.t === '.' && isIdent(toks[k + 4]?.t) && close === k + 5) {
630
+ return `${toks[k].t}.${toks[k + 2].t}.${toks[k + 4].t}`;
631
+ }
632
+ return null;
633
+ }
634
+ /** Shape 3: `obj[a][b] = …` with both keys from the request. */
635
+ function requestKeys(toks, fn) {
636
+ const names = requestNames(toks, fn.open, fn.close);
637
+ const out = [];
638
+ for (let j = fn.open + 1; j < fn.close; j++) {
639
+ if (toks[j - 1]?.t === '.')
640
+ continue;
641
+ const c = chainAt(toks, j);
642
+ if (!c || toks[c.end]?.t !== '[')
643
+ continue;
644
+ const c1 = matchClose(toks, c.end);
645
+ if (c1 < 0 || toks[c1 + 1]?.t !== '[')
646
+ continue;
647
+ const c2 = matchClose(toks, c1 + 1);
648
+ if (c2 < 0 || !isAssign(toks[c2 + 1]?.t))
649
+ continue;
650
+ const k1 = requestKey(toks, c.end, c1, names);
651
+ const k2 = requestKey(toks, c1 + 1, c2, names);
652
+ if (k1 && k2)
653
+ out.push({ pos: toks[j].pos, target: c.text, key: `${k1}, ${k2}` });
654
+ }
655
+ return out;
656
+ }
657
+ export function detectPrototypePollution(code) {
658
+ if (code.length > MAX_CODE_LENGTH)
659
+ return [];
660
+ const masked = maskLiterals(code);
661
+ const toks = tokenize(masked);
662
+ const fns = findFunctions(toks);
663
+ const fileNullProto = nullProtoNames(toks, 0, toks.length);
664
+ const hits = [];
665
+ const seen = new Set();
666
+ for (const fn of fns) {
667
+ const base = toks[fn.open].pos;
668
+ const raw = code.slice(base, toks[fn.close].pos + 1);
669
+ const found = [];
670
+ for (const h of recursiveMerge(toks, fn))
671
+ found.push({ ...h, shape: 'recursive-merge' });
672
+ for (const h of setByPath(toks, raw, base, fn))
673
+ found.push({ ...h, shape: 'set-by-path' });
674
+ for (const h of requestKeys(toks, fn))
675
+ found.push({ ...h, shape: 'request-keys' });
676
+ if (found.length === 0)
677
+ continue;
678
+ const keys = new Set();
679
+ for (const h of found)
680
+ for (const k of h.key.split(', '))
681
+ keys.add(k);
682
+ if (hasGuard(raw, toks, fn.open, fn.close, keys))
683
+ continue;
684
+ const nullProto = nullProtoNames(toks, fn.open, fn.close);
685
+ for (const h of found) {
686
+ const root = h.target.split('.')[0];
687
+ if (nullProto.has(root) || fileNullProto.has(root))
688
+ continue;
689
+ const line = lineOf(code, h.pos);
690
+ if (seen.has(line))
691
+ continue;
692
+ seen.add(line);
693
+ hits.push({ line, shape: h.shape, target: h.target, key: h.key, fn: fn.name });
694
+ }
695
+ }
696
+ return hits.sort((a, b) => a.line - b.line);
697
+ }
698
+ const MESSAGES = {
699
+ 'recursive-merge': (h) => `Recursive merge${h.fn ? ` \`${h.fn}\`` : ''} copies every key into \`${h.target}\` without rejecting ` +
700
+ '`__proto__`, `constructor` or `prototype`: a source object with a `__proto__` key (for example from ' +
701
+ '`JSON.parse`) writes into `Object.prototype`.',
702
+ 'set-by-path': (h) => `Set-by-path${h.fn ? ` \`${h.fn}\`` : ''} walks \`${h.target}\` along a key path without rejecting ` +
703
+ '`__proto__`, `constructor` or `prototype`: a path such as `__proto__.isAdmin` writes into `Object.prototype`.',
704
+ 'request-keys': (h) => `\`${h.target}[…][…]\` is written with keys from the request (${h.key}): \`__proto__\` as the first key ` +
705
+ 'writes the second key into `Object.prototype`.',
706
+ };
707
+ export class PrototypePollutionPass {
708
+ name = 'prototype-pollution';
709
+ category = 'security';
710
+ run(ctx) {
711
+ const { language } = ctx;
712
+ if (language !== 'javascript' && language !== 'typescript')
713
+ return { findings: [] };
714
+ const file = ctx.graph.ir.meta.file;
715
+ const findings = detectPrototypePollution(ctx.code);
716
+ for (const h of findings) {
717
+ ctx.addFinding({
718
+ id: `${this.name}-${file}-${h.line}`,
719
+ pass: this.name,
720
+ category: this.category,
721
+ rule_id: this.name,
722
+ cwe: 'CWE-1321',
723
+ severity: h.shape === 'request-keys' ? 'high' : 'medium',
724
+ level: h.shape === 'request-keys' ? 'error' : 'warning',
725
+ message: MESSAGES[h.shape](h),
726
+ file,
727
+ line: h.line,
728
+ fix: 'Skip the keys `__proto__`, `constructor` and `prototype` before writing, or write into an object made ' +
729
+ 'with `Object.create(null)` or a `Map`.',
730
+ evidence: { shape: h.shape, target: h.target, key: h.key, ...(h.fn ? { function: h.fn } : {}) },
731
+ });
732
+ }
733
+ return { findings };
734
+ }
735
+ }
736
+ //# sourceMappingURL=prototype-pollution-pass.js.map