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
@@ -93,17 +93,17 @@ function unmarshalNode(tree, address = TRANSFER_BUFFER) {
93
93
  });
94
94
  return result;
95
95
  }
96
- function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
97
- C.setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32");
98
- C.setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32");
99
- C.setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
100
- C.setValue(address + 3 * SIZE_OF_INT, cursor[3], "i32");
101
- }
102
- function unmarshalTreeCursor(cursor) {
103
- cursor[0] = C.getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
104
- cursor[1] = C.getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
105
- cursor[2] = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
106
- cursor[3] = C.getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
96
+ function marshalTreeCursor({ handles }, address = TRANSFER_BUFFER) {
97
+ C.setValue(address + 0 * SIZE_OF_INT, handles[0], "i32");
98
+ C.setValue(address + 1 * SIZE_OF_INT, handles[1], "i32");
99
+ C.setValue(address + 2 * SIZE_OF_INT, handles[2], "i32");
100
+ C.setValue(address + 3 * SIZE_OF_INT, handles[3], "i32");
101
+ }
102
+ function unmarshalTreeCursor({ handles }) {
103
+ handles[0] = C.getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
104
+ handles[1] = C.getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
105
+ handles[2] = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
106
+ handles[3] = C.getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
107
107
  }
108
108
  function marshalPoint(address, point) {
109
109
  C.setValue(address, point.row, "i32");
@@ -1509,7 +1509,7 @@ async function Module2(moduleArg = {}) {
1509
1509
  Module["loadWebAssemblyModule"] = loadWebAssemblyModule;
1510
1510
  Module["LE_HEAP_STORE_I64"] = LE_HEAP_STORE_I64;
1511
1511
  var ASM_CONSTS = {};
1512
- var _malloc, _calloc, _realloc, _free, _ts_range_edit, _memcmp, _ts_language_symbol_count, _ts_language_state_count, _ts_language_abi_version, _ts_language_name, _ts_language_field_count, _ts_language_next_state, _ts_language_symbol_name, _ts_language_symbol_for_name, _strncmp, _ts_language_symbol_type, _ts_language_field_name_for_id, _ts_lookahead_iterator_new, _ts_lookahead_iterator_delete, _ts_lookahead_iterator_reset_state, _ts_lookahead_iterator_reset, _ts_lookahead_iterator_next, _ts_lookahead_iterator_current_symbol, _ts_point_edit, _ts_parser_delete, _ts_parser_reset, _ts_parser_set_language, _ts_parser_set_included_ranges, _ts_query_new, _ts_query_delete, _iswspace, _iswalnum, _ts_query_copy, _ts_query_pattern_count, _ts_query_capture_count, _ts_query_string_count, _ts_query_capture_name_for_id, _ts_query_capture_quantifier_for_id, _ts_query_string_value_for_id, _ts_query_predicates_for_pattern, _ts_query_start_byte_for_pattern, _ts_query_end_byte_for_pattern, _ts_query_is_pattern_rooted, _ts_query_is_pattern_non_local, _ts_query_is_pattern_guaranteed_at_step, _ts_query_disable_capture, _ts_query_disable_pattern, _ts_tree_copy, _ts_tree_delete, _ts_init, _ts_parser_new_wasm, _ts_parser_enable_logger_wasm, _ts_parser_parse_wasm, _ts_parser_included_ranges_wasm, _ts_language_type_is_named_wasm, _ts_language_type_is_visible_wasm, _ts_language_metadata_wasm, _ts_language_supertypes_wasm, _ts_language_subtypes_wasm, _ts_tree_root_node_wasm, _ts_tree_root_node_with_offset_wasm, _ts_tree_edit_wasm, _ts_tree_included_ranges_wasm, _ts_tree_get_changed_ranges_wasm, _ts_tree_cursor_new_wasm, _ts_tree_cursor_copy_wasm, _ts_tree_cursor_delete_wasm, _ts_tree_cursor_reset_wasm, _ts_tree_cursor_reset_to_wasm, _ts_tree_cursor_goto_first_child_wasm, _ts_tree_cursor_goto_last_child_wasm, _ts_tree_cursor_goto_first_child_for_index_wasm, _ts_tree_cursor_goto_first_child_for_position_wasm, _ts_tree_cursor_goto_next_sibling_wasm, _ts_tree_cursor_goto_previous_sibling_wasm, _ts_tree_cursor_goto_descendant_wasm, _ts_tree_cursor_goto_parent_wasm, _ts_tree_cursor_current_node_type_id_wasm, _ts_tree_cursor_current_node_state_id_wasm, _ts_tree_cursor_current_node_is_named_wasm, _ts_tree_cursor_current_node_is_missing_wasm, _ts_tree_cursor_current_node_id_wasm, _ts_tree_cursor_start_position_wasm, _ts_tree_cursor_end_position_wasm, _ts_tree_cursor_start_index_wasm, _ts_tree_cursor_end_index_wasm, _ts_tree_cursor_current_field_id_wasm, _ts_tree_cursor_current_depth_wasm, _ts_tree_cursor_current_descendant_index_wasm, _ts_tree_cursor_current_node_wasm, _ts_node_symbol_wasm, _ts_node_field_name_for_child_wasm, _ts_node_field_name_for_named_child_wasm, _ts_node_children_by_field_id_wasm, _ts_node_first_child_for_byte_wasm, _ts_node_first_named_child_for_byte_wasm, _ts_node_grammar_symbol_wasm, _ts_node_child_count_wasm, _ts_node_named_child_count_wasm, _ts_node_child_wasm, _ts_node_named_child_wasm, _ts_node_child_by_field_id_wasm, _ts_node_next_sibling_wasm, _ts_node_prev_sibling_wasm, _ts_node_next_named_sibling_wasm, _ts_node_prev_named_sibling_wasm, _ts_node_descendant_count_wasm, _ts_node_parent_wasm, _ts_node_child_with_descendant_wasm, _ts_node_descendant_for_index_wasm, _ts_node_named_descendant_for_index_wasm, _ts_node_descendant_for_position_wasm, _ts_node_named_descendant_for_position_wasm, _ts_node_start_point_wasm, _ts_node_end_point_wasm, _ts_node_start_index_wasm, _ts_node_end_index_wasm, _ts_node_to_string_wasm, _ts_node_children_wasm, _ts_node_named_children_wasm, _ts_node_descendants_of_type_wasm, _ts_node_is_named_wasm, _ts_node_has_changes_wasm, _ts_node_has_error_wasm, _ts_node_is_error_wasm, _ts_node_is_missing_wasm, _ts_node_is_extra_wasm, _ts_node_parse_state_wasm, _ts_node_next_parse_state_wasm, _ts_query_matches_wasm, _ts_query_captures_wasm, _memset, _memcpy, _memmove, _iswalpha, _iswblank, _iswdigit, _iswlower, _iswpunct, _iswupper, _iswxdigit, _memchr, _strlen, _strcmp, _strncat, _strncpy, _towlower, _towupper, _setThrew, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, ___wasm_apply_data_relocs;
1512
+ var _malloc, _calloc, _realloc, _free, _ts_range_edit, _memcmp, _ts_language_symbol_count, _ts_language_state_count, _ts_language_abi_version, _ts_language_name, _ts_language_field_count, _ts_language_next_state, _ts_language_symbol_name, _ts_language_symbol_for_name, _strncmp, _strlen, _ts_language_symbol_type, _ts_language_field_name_for_id, _ts_lookahead_iterator_new, _ts_lookahead_iterator_delete, _ts_lookahead_iterator_reset_state, _ts_lookahead_iterator_reset, _ts_lookahead_iterator_next, _ts_lookahead_iterator_current_symbol, _ts_point_edit, _ts_parser_delete, _ts_parser_reset, _ts_parser_set_language, _ts_parser_set_included_ranges, _ts_query_new, _ts_query_delete, _iswspace, _iswalnum, _ts_query_copy, _ts_query_pattern_count, _ts_query_capture_count, _ts_query_string_count, _ts_query_capture_name_for_id, _ts_query_capture_quantifier_for_id, _ts_query_string_value_for_id, _ts_query_predicates_for_pattern, _ts_query_start_byte_for_pattern, _ts_query_end_byte_for_pattern, _ts_query_is_pattern_rooted, _ts_query_is_pattern_non_local, _ts_query_is_pattern_guaranteed_at_step, _ts_query_disable_capture, _ts_query_disable_pattern, _ts_tree_copy, _ts_tree_delete, _ts_init, _ts_parser_new_wasm, _ts_parser_enable_logger_wasm, _ts_parser_parse_wasm, _ts_parser_included_ranges_wasm, _ts_language_type_is_named_wasm, _ts_language_type_is_visible_wasm, _ts_language_metadata_wasm, _ts_language_supertypes_wasm, _ts_language_subtypes_wasm, _ts_tree_root_node_wasm, _ts_tree_root_node_with_offset_wasm, _ts_tree_edit_wasm, _ts_tree_included_ranges_wasm, _ts_tree_get_changed_ranges_wasm, _ts_tree_cursor_new_wasm, _ts_tree_cursor_copy_wasm, _ts_tree_cursor_delete_wasm, _ts_tree_cursor_reset_wasm, _ts_tree_cursor_reset_to_wasm, _ts_tree_cursor_goto_first_child_wasm, _ts_tree_cursor_goto_last_child_wasm, _ts_tree_cursor_goto_first_child_for_index_wasm, _ts_tree_cursor_goto_first_child_for_position_wasm, _ts_tree_cursor_goto_next_sibling_wasm, _ts_tree_cursor_goto_previous_sibling_wasm, _ts_tree_cursor_goto_descendant_wasm, _ts_tree_cursor_goto_parent_wasm, _ts_tree_cursor_current_node_type_id_wasm, _ts_tree_cursor_current_node_state_id_wasm, _ts_tree_cursor_current_node_is_named_wasm, _ts_tree_cursor_current_node_is_missing_wasm, _ts_tree_cursor_current_node_id_wasm, _ts_tree_cursor_start_position_wasm, _ts_tree_cursor_end_position_wasm, _ts_tree_cursor_start_index_wasm, _ts_tree_cursor_end_index_wasm, _ts_tree_cursor_current_field_id_wasm, _ts_tree_cursor_current_depth_wasm, _ts_tree_cursor_current_descendant_index_wasm, _ts_tree_cursor_current_node_wasm, _ts_node_symbol_wasm, _ts_node_field_name_for_child_wasm, _ts_node_field_name_for_named_child_wasm, _ts_node_children_by_field_id_wasm, _ts_node_first_child_for_byte_wasm, _ts_node_first_named_child_for_byte_wasm, _ts_node_grammar_symbol_wasm, _ts_node_child_count_wasm, _ts_node_named_child_count_wasm, _ts_node_child_wasm, _ts_node_named_child_wasm, _ts_node_child_by_field_id_wasm, _ts_node_next_sibling_wasm, _ts_node_prev_sibling_wasm, _ts_node_next_named_sibling_wasm, _ts_node_prev_named_sibling_wasm, _ts_node_descendant_count_wasm, _ts_node_parent_wasm, _ts_node_child_with_descendant_wasm, _ts_node_descendant_for_index_wasm, _ts_node_named_descendant_for_index_wasm, _ts_node_descendant_for_position_wasm, _ts_node_named_descendant_for_position_wasm, _ts_node_start_point_wasm, _ts_node_end_point_wasm, _ts_node_start_index_wasm, _ts_node_end_index_wasm, _ts_node_to_string_wasm, _ts_node_children_wasm, _ts_node_named_children_wasm, _ts_node_descendants_of_type_wasm, _ts_node_is_named_wasm, _ts_node_has_changes_wasm, _ts_node_has_error_wasm, _ts_node_is_error_wasm, _ts_node_is_missing_wasm, _ts_node_is_extra_wasm, _ts_node_parse_state_wasm, _ts_node_next_parse_state_wasm, _ts_query_matches_wasm, _ts_query_captures_wasm, _memset, _memcpy, _memmove, _iswalpha, _iswblank, _iswdigit, _iswlower, _iswpunct, _iswupper, _iswxdigit, _memchr, _strcmp, _strncat, _strncpy, _towlower, _towupper, _setThrew, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, ___wasm_apply_data_relocs;
1513
1513
  function assignWasmExports(wasmExports2) {
1514
1514
  Module["_malloc"] = _malloc = wasmExports2["malloc"];
1515
1515
  Module["_calloc"] = _calloc = wasmExports2["calloc"];
@@ -1526,6 +1526,7 @@ async function Module2(moduleArg = {}) {
1526
1526
  Module["_ts_language_symbol_name"] = _ts_language_symbol_name = wasmExports2["ts_language_symbol_name"];
1527
1527
  Module["_ts_language_symbol_for_name"] = _ts_language_symbol_for_name = wasmExports2["ts_language_symbol_for_name"];
1528
1528
  Module["_strncmp"] = _strncmp = wasmExports2["strncmp"];
1529
+ Module["_strlen"] = _strlen = wasmExports2["strlen"];
1529
1530
  Module["_ts_language_symbol_type"] = _ts_language_symbol_type = wasmExports2["ts_language_symbol_type"];
1530
1531
  Module["_ts_language_field_name_for_id"] = _ts_language_field_name_for_id = wasmExports2["ts_language_field_name_for_id"];
1531
1532
  Module["_ts_lookahead_iterator_new"] = _ts_lookahead_iterator_new = wasmExports2["ts_lookahead_iterator_new"];
@@ -1653,7 +1654,6 @@ async function Module2(moduleArg = {}) {
1653
1654
  Module["_iswupper"] = _iswupper = wasmExports2["iswupper"];
1654
1655
  Module["_iswxdigit"] = _iswxdigit = wasmExports2["iswxdigit"];
1655
1656
  Module["_memchr"] = _memchr = wasmExports2["memchr"];
1656
- Module["_strlen"] = _strlen = wasmExports2["strlen"];
1657
1657
  Module["_strcmp"] = _strcmp = wasmExports2["strcmp"];
1658
1658
  Module["_strncat"] = _strncat = wasmExports2["strncat"];
1659
1659
  Module["_strncpy"] = _strncpy = wasmExports2["strncpy"];
@@ -1949,6 +1949,9 @@ function parsePattern(index, stepType, stepValueId, captureNames, stringValues,
1949
1949
  steps.length = 0;
1950
1950
  }
1951
1951
  }
1952
+ function indexForByteOffset(source, byteOffset) {
1953
+ return new TextEncoder().encodeInto(source, new Uint8Array(byteOffset)).read;
1954
+ }
1952
1955
  var __defProp2, __name, Edit, SIZE_OF_SHORT, SIZE_OF_INT, SIZE_OF_CURSOR, SIZE_OF_NODE, SIZE_OF_POINT, SIZE_OF_RANGE, ZERO_POINT, INTERNAL, C, finalizer, LookaheadIterator, finalizer2, Tree, finalizer3, TreeCursor, Node, LANGUAGE_FUNCTION_REGEX, Language, web_tree_sitter_default, Module3, TRANSFER_BUFFER, LANGUAGE_VERSION, MIN_COMPATIBLE_VERSION, finalizer4, Parser, PREDICATE_STEP_TYPE_CAPTURE, PREDICATE_STEP_TYPE_STRING, QUERY_WORD_REGEX, CaptureQuantifier, isCaptureStep, isStringStep, QueryErrorKind, QueryError, finalizer5, Query;
1953
1956
  var init_web_tree_sitter = __esm({
1954
1957
  "../../node_modules/web-tree-sitter/web-tree-sitter.js"() {
@@ -2267,29 +2270,17 @@ var init_web_tree_sitter = __esm({
2267
2270
  return result;
2268
2271
  }
2269
2272
  };
2270
- finalizer3 = newFinalizer((address) => {
2271
- C._ts_tree_cursor_delete_wasm(address);
2273
+ finalizer3 = newFinalizer((handles) => {
2274
+ marshalTreeCursor({ handles });
2275
+ C._ts_tree_cursor_delete_wasm(0);
2272
2276
  });
2273
2277
  TreeCursor = class _TreeCursor {
2274
2278
  static {
2275
2279
  __name(this, "TreeCursor");
2276
2280
  }
2277
2281
  /** @internal */
2278
- // @ts-expect-error: never read
2279
- [0] = 0;
2280
- // Internal handle for Wasm
2281
- /** @internal */
2282
- // @ts-expect-error: never read
2283
- [1] = 0;
2284
- // Internal handle for Wasm
2285
- /** @internal */
2286
- // @ts-expect-error: never read
2287
- [2] = 0;
2288
- // Internal handle for Wasm
2289
- /** @internal */
2290
- // @ts-expect-error: never read
2291
- [3] = 0;
2292
- // Internal handle for Wasm
2282
+ handles = [0, 0, 0, 0];
2283
+ // Internal handles for Wasm, shared with the finalizer.
2293
2284
  /** @internal */
2294
2285
  tree;
2295
2286
  /** @internal */
@@ -2297,21 +2288,20 @@ var init_web_tree_sitter = __esm({
2297
2288
  assertInternal(internal);
2298
2289
  this.tree = tree;
2299
2290
  unmarshalTreeCursor(this);
2300
- finalizer3?.register(this, this.tree[0], this);
2291
+ finalizer3?.register(this, this.handles, this);
2301
2292
  }
2302
2293
  /** Creates a deep copy of the tree cursor. This allocates new memory. */
2303
2294
  copy() {
2304
- const copy = new _TreeCursor(INTERNAL, this.tree);
2295
+ marshalTreeCursor(this);
2305
2296
  C._ts_tree_cursor_copy_wasm(this.tree[0]);
2306
- unmarshalTreeCursor(copy);
2307
- return copy;
2297
+ return new _TreeCursor(INTERNAL, this.tree);
2308
2298
  }
2309
2299
  /** Delete the tree cursor, freeing its resources. */
2310
2300
  delete() {
2311
2301
  finalizer3?.unregister(this);
2312
2302
  marshalTreeCursor(this);
2313
2303
  C._ts_tree_cursor_delete_wasm(this.tree[0]);
2314
- this[0] = this[1] = this[2] = 0;
2304
+ this.handles.fill(0);
2315
2305
  }
2316
2306
  /** Get the tree cursor's current {@link Node}. */
2317
2307
  get currentNode() {
@@ -2522,10 +2512,10 @@ var init_web_tree_sitter = __esm({
2522
2512
  }
2523
2513
  /**
2524
2514
  * Move this cursor to the first child of its current node that contains or
2525
- * starts after the given byte offset.
2515
+ * starts after the given position.
2526
2516
  *
2527
- * This returns the index of the child node if one was found, and returns
2528
- * `null` if no such child was found.
2517
+ * This returns `true` if the cursor successfully moved to a child node, and returns
2518
+ * `false` if no such child was found.
2529
2519
  */
2530
2520
  gotoFirstChildForPosition(goalPosition) {
2531
2521
  marshalTreeCursor(this);
@@ -2541,8 +2531,9 @@ var init_web_tree_sitter = __esm({
2541
2531
  reset(node) {
2542
2532
  marshalNode(node);
2543
2533
  marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
2544
- C._ts_tree_cursor_reset_wasm(this.tree[0]);
2534
+ C._ts_tree_cursor_reset_wasm(node.tree[0]);
2545
2535
  unmarshalTreeCursor(this);
2536
+ this.tree = node.tree;
2546
2537
  }
2547
2538
  /**
2548
2539
  * Re-initialize a tree cursor to the same position as another cursor.
@@ -2555,6 +2546,7 @@ var init_web_tree_sitter = __esm({
2555
2546
  marshalTreeCursor(cursor, TRANSFER_BUFFER + SIZE_OF_CURSOR);
2556
2547
  C._ts_tree_cursor_reset_to_wasm(this.tree[0], cursor.tree[0]);
2557
2548
  unmarshalTreeCursor(this);
2549
+ this.tree = cursor.tree;
2558
2550
  }
2559
2551
  };
2560
2552
  Node = class {
@@ -2913,16 +2905,14 @@ var init_web_tree_sitter = __esm({
2913
2905
  if (!Array.isArray(types)) types = [types];
2914
2906
  const symbols = [];
2915
2907
  const typesBySymbol = this.tree.language.types;
2916
- for (const node_type of types) {
2917
- if (node_type == "ERROR") {
2918
- symbols.push(65535);
2919
- }
2920
- }
2921
2908
  for (let i2 = 0, n = typesBySymbol.length; i2 < n; i2++) {
2922
2909
  if (types.includes(typesBySymbol[i2])) {
2923
2910
  symbols.push(i2);
2924
2911
  }
2925
2912
  }
2913
+ if (types.includes("ERROR")) {
2914
+ symbols.push(65535);
2915
+ }
2926
2916
  const symbolsAddress = C._malloc(SIZE_OF_INT * symbols.length);
2927
2917
  for (let i2 = 0, n = symbols.length; i2 < n; i2++) {
2928
2918
  C.setValue(symbolsAddress + i2 * SIZE_OF_INT, symbols[i2], "i32");
@@ -3077,31 +3067,9 @@ var init_web_tree_sitter = __esm({
3077
3067
  * you want to keep and continue to use after an edit.
3078
3068
  */
3079
3069
  edit(edit) {
3080
- if (this.startIndex >= edit.oldEndIndex) {
3081
- this.startIndex = edit.newEndIndex + (this.startIndex - edit.oldEndIndex);
3082
- let subbedPointRow;
3083
- let subbedPointColumn;
3084
- if (this.startPosition.row > edit.oldEndPosition.row) {
3085
- subbedPointRow = this.startPosition.row - edit.oldEndPosition.row;
3086
- subbedPointColumn = this.startPosition.column;
3087
- } else {
3088
- subbedPointRow = 0;
3089
- subbedPointColumn = this.startPosition.column;
3090
- if (this.startPosition.column >= edit.oldEndPosition.column) {
3091
- subbedPointColumn = this.startPosition.column - edit.oldEndPosition.column;
3092
- }
3093
- }
3094
- if (subbedPointRow > 0) {
3095
- this.startPosition.row += subbedPointRow;
3096
- this.startPosition.column = subbedPointColumn;
3097
- } else {
3098
- this.startPosition.column += subbedPointColumn;
3099
- }
3100
- } else if (this.startIndex > edit.startIndex) {
3101
- this.startIndex = edit.newEndIndex;
3102
- this.startPosition.row = edit.newEndPosition.row;
3103
- this.startPosition.column = edit.newEndPosition.column;
3104
- }
3070
+ const { point, index } = edit.editPoint(this.startPosition, this.startIndex);
3071
+ this.startPosition = point;
3072
+ this.startIndex = index;
3105
3073
  }
3106
3074
  /** Get the S-expression representation of this node. */
3107
3075
  toString() {
@@ -3622,6 +3590,7 @@ ${JSON.stringify(symbolNames, null, 2)}`);
3622
3590
  __name(parseIsPredicate, "parseIsPredicate");
3623
3591
  __name(parseSetDirective, "parseSetDirective");
3624
3592
  __name(parsePattern, "parsePattern");
3593
+ __name(indexForByteOffset, "indexForByteOffset");
3625
3594
  finalizer5 = newFinalizer((address) => {
3626
3595
  C._ts_query_delete(address);
3627
3596
  });
@@ -3636,6 +3605,8 @@ ${JSON.stringify(symbolNames, null, 2)}`);
3636
3605
  exceededMatchLimit;
3637
3606
  /** @internal */
3638
3607
  textPredicates;
3608
+ /** @internal */
3609
+ source;
3639
3610
  /** The names of the captures used in the query. */
3640
3611
  captureNames;
3641
3612
  /** The quantifiers of the captures used in the query. */
@@ -3774,6 +3745,7 @@ ${JSON.stringify(symbolNames, null, 2)}`);
3774
3745
  this.captureNames = captureNames;
3775
3746
  this.captureQuantifiers = captureQuantifiers;
3776
3747
  this.textPredicates = textPredicates;
3748
+ this.source = source;
3777
3749
  this.predicates = predicates;
3778
3750
  this.setProperties = setProperties;
3779
3751
  this.assertedProperties = assertedProperties;
@@ -4010,23 +3982,25 @@ ${JSON.stringify(symbolNames, null, 2)}`);
4010
3982
  didExceedMatchLimit() {
4011
3983
  return this.exceededMatchLimit;
4012
3984
  }
4013
- /** Get the byte offset where the given pattern starts in the query's source. */
3985
+ /** Get the index where the given pattern starts in the query's source. */
4014
3986
  startIndexForPattern(patternIndex) {
4015
3987
  if (patternIndex >= this.predicates.length) {
4016
3988
  throw new Error(
4017
3989
  `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
4018
3990
  );
4019
3991
  }
4020
- return C._ts_query_start_byte_for_pattern(this[0], patternIndex);
3992
+ const byteOffset = C._ts_query_start_byte_for_pattern(this[0], patternIndex);
3993
+ return indexForByteOffset(this.source, byteOffset);
4021
3994
  }
4022
- /** Get the byte offset where the given pattern ends in the query's source. */
3995
+ /** Get the index where the given pattern ends in the query's source. */
4023
3996
  endIndexForPattern(patternIndex) {
4024
3997
  if (patternIndex >= this.predicates.length) {
4025
3998
  throw new Error(
4026
3999
  `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
4027
4000
  );
4028
4001
  }
4029
- return C._ts_query_end_byte_for_pattern(this[0], patternIndex);
4002
+ const byteOffset = C._ts_query_end_byte_for_pattern(this[0], patternIndex);
4003
+ return indexForByteOffset(this.source, byteOffset);
4030
4004
  }
4031
4005
  /** Get the number of patterns in the query. */
4032
4006
  patternCount() {
@@ -4045,13 +4019,14 @@ ${JSON.stringify(symbolNames, null, 2)}`);
4045
4019
  return C._ts_query_is_pattern_non_local(this[0], patternIndex) === 1;
4046
4020
  }
4047
4021
  /**
4048
- * Check if a given step in a query is 'definite'.
4022
+ * Check if the step at the given index in the query's source is 'definite'.
4049
4023
  *
4050
4024
  * A query step is 'definite' if its parent pattern will be guaranteed to
4051
4025
  * match successfully once it reaches the step.
4052
4026
  */
4053
- isPatternGuaranteedAtStep(byteIndex) {
4054
- return C._ts_query_is_pattern_guaranteed_at_step(this[0], byteIndex) === 1;
4027
+ isPatternGuaranteedAtStep(index) {
4028
+ const byteOffset = C.lengthBytesUTF8(this.source.slice(0, index));
4029
+ return C._ts_query_is_pattern_guaranteed_at_step(this[0], byteOffset) === 1;
4055
4030
  }
4056
4031
  };
4057
4032
  }
@@ -8987,6 +8962,7 @@ function extractJavaImports(tree, cache) {
8987
8962
  function extractJSImportInfo(node) {
8988
8963
  const imports = [];
8989
8964
  const lineNumber = node.startPosition.row + 1;
8965
+ const statementTypeOnly = hasTypeKeyword(node);
8990
8966
  const sourceNode = node.childForFieldName("source");
8991
8967
  const fromPackage = sourceNode ? getNodeText(sourceNode).replace(/['"]/g, "") : null;
8992
8968
  if (!node.childForFieldName("import_clause") && !node.childForFieldName("namespace_import")) {
@@ -9059,7 +9035,8 @@ function extractJSImportInfo(node) {
9059
9035
  from_package: fromPackage,
9060
9036
  alias,
9061
9037
  is_wildcard: false,
9062
- line_number: lineNumber
9038
+ line_number: lineNumber,
9039
+ ...hasTypeKeyword(specifier) ? { is_type_only: true } : {}
9063
9040
  });
9064
9041
  }
9065
9042
  }
@@ -9113,7 +9090,8 @@ function extractJSImportInfo(node) {
9113
9090
  from_package: fromPackage,
9114
9091
  alias,
9115
9092
  is_wildcard: false,
9116
- line_number: lineNumber
9093
+ line_number: lineNumber,
9094
+ ...hasTypeKeyword(specifier) ? { is_type_only: true } : {}
9117
9095
  });
9118
9096
  }
9119
9097
  }
@@ -9121,7 +9099,14 @@ function extractJSImportInfo(node) {
9121
9099
  }
9122
9100
  }
9123
9101
  }
9124
- return imports;
9102
+ return statementTypeOnly ? imports.map((imp) => ({ ...imp, is_type_only: true })) : imports;
9103
+ }
9104
+ function hasTypeKeyword(node) {
9105
+ for (let i2 = 0; i2 < node.childCount; i2++) {
9106
+ const child = node.child(i2);
9107
+ if (child && !child.isNamed && child.type === "type") return true;
9108
+ }
9109
+ return false;
9125
9110
  }
9126
9111
  function findRequireCalls(tree, cache) {
9127
9112
  const imports = [];
@@ -10978,13 +10963,13 @@ function processExpression(expr, startDefId, startUseId, scopeStack, isJavaScrip
10978
10963
  const operand = expr.childForFieldName("operand") ?? expr.child(0) ?? expr.child(1);
10979
10964
  if (operand && operand.type === "identifier") {
10980
10965
  const name2 = getNodeText(operand);
10981
- const reachingDef = findReachingDef(name2, scopeStack);
10966
+ const reachingDef2 = findReachingDef(name2, scopeStack);
10982
10967
  const use = {
10983
10968
  id: useId++,
10984
10969
  variable: name2,
10985
10970
  line: operand.startPosition.row + 1,
10986
10971
  ...jsColumn(operand, isJavaScript),
10987
- def_id: reachingDef
10972
+ def_id: reachingDef2
10988
10973
  };
10989
10974
  uses.push(use);
10990
10975
  const def = {
@@ -11092,16 +11077,16 @@ function extractUses(node, startId, scopeStack, isJavaScript) {
11092
11077
  if (parent.type === "inferred_parameters") return;
11093
11078
  }
11094
11079
  const name2 = getNodeText(n);
11095
- const reachingDef = findReachingDef(name2, scopeStack);
11080
+ const reachingDef2 = findReachingDef(name2, scopeStack);
11096
11081
  uses.push({
11097
11082
  id: id++,
11098
11083
  variable: name2,
11099
11084
  line: n.startPosition.row + 1,
11100
11085
  ...jsColumn(n, isJavaScript),
11101
- def_id: reachingDef
11086
+ def_id: reachingDef2
11102
11087
  });
11103
11088
  for (const alt of findAlternateDefs(name2, scopeStack)) {
11104
- if (alt === reachingDef) continue;
11089
+ if (alt === reachingDef2) continue;
11105
11090
  uses.push({ id: id++, variable: name2, line: n.startPosition.row + 1, ...jsColumn(n, isJavaScript), def_id: alt });
11106
11091
  }
11107
11092
  }
@@ -11704,8 +11689,8 @@ function buildBashDFG(tree) {
11704
11689
  if (varNameNode) {
11705
11690
  const varName = getNodeText(varNameNode);
11706
11691
  if (varName && !varName.startsWith("?") && !varName.startsWith("#")) {
11707
- let reachingDef = positionalDef(varName, node, findReachingDef(varName, scopeStack));
11708
- if (reachingDef === null && !positionalParams.includes(varName)) {
11692
+ let reachingDef2 = positionalDef(varName, node, findReachingDef(varName, scopeStack));
11693
+ if (reachingDef2 === null && !positionalParams.includes(varName)) {
11709
11694
  const def = {
11710
11695
  id: defIdCounter++,
11711
11696
  variable: varName,
@@ -11714,13 +11699,13 @@ function buildBashDFG(tree) {
11714
11699
  };
11715
11700
  defs.push(def);
11716
11701
  scopeStack[0].set(varName, def.id);
11717
- reachingDef = def.id;
11702
+ reachingDef2 = def.id;
11718
11703
  }
11719
11704
  uses.push({
11720
11705
  id: useIdCounter++,
11721
11706
  variable: varName,
11722
11707
  line: node.startPosition.row + 1,
11723
- def_id: reachingDef
11708
+ def_id: reachingDef2
11724
11709
  });
11725
11710
  }
11726
11711
  }
@@ -11728,8 +11713,8 @@ function buildBashDFG(tree) {
11728
11713
  const varNameNode = node.namedChildCount > 0 ? node.namedChild(0) : null;
11729
11714
  if (varNameNode && varNameNode.type === "variable_name") {
11730
11715
  const varName = getNodeText(varNameNode);
11731
- let reachingDef = positionalDef(varName, node, findReachingDef(varName, scopeStack));
11732
- if (reachingDef === null && !positionalParams.includes(varName)) {
11716
+ let reachingDef2 = positionalDef(varName, node, findReachingDef(varName, scopeStack));
11717
+ if (reachingDef2 === null && !positionalParams.includes(varName)) {
11733
11718
  const def = {
11734
11719
  id: defIdCounter++,
11735
11720
  variable: varName,
@@ -11738,13 +11723,13 @@ function buildBashDFG(tree) {
11738
11723
  };
11739
11724
  defs.push(def);
11740
11725
  scopeStack[0].set(varName, def.id);
11741
- reachingDef = def.id;
11726
+ reachingDef2 = def.id;
11742
11727
  }
11743
11728
  uses.push({
11744
11729
  id: useIdCounter++,
11745
11730
  variable: varName,
11746
11731
  line: node.startPosition.row + 1,
11747
- def_id: reachingDef
11732
+ def_id: reachingDef2
11748
11733
  });
11749
11734
  }
11750
11735
  }
@@ -16725,6 +16710,12 @@ var DEFAULT_SANITIZERS = [
16725
16710
  // `code_injection` categorization that `re.compile` currently emits
16726
16711
  // (a re.escape-wrapped pattern cannot execute anything, so both are safe).
16727
16712
  { method: "escape", class: "re", removes: ["redos", "code_injection"] },
16713
+ // JS/TS ReDoS — escaping a request value before `new RegExp(...)` makes it a
16714
+ // literal: lodash `_.escapeRegExp`, the `escape-string-regexp` package, and
16715
+ // the common local helper names.
16716
+ { method: "escapeRegExp", removes: ["redos"] },
16717
+ { method: "escapeStringRegexp", removes: ["redos"] },
16718
+ { method: "escapeRegex", removes: ["redos"] },
16728
16719
  // Python SQLAlchemy — `text(...).bindparams(...)` binds params safely.
16729
16720
  // The `bindparams` call is the sanitizer; the parent `text` wraps the
16730
16721
  // template. Also add `expression.literal` for explicit SQL literals.
@@ -17864,7 +17855,7 @@ function findRustLiteralEqualityGuardSanitizers(code) {
17864
17855
  lineStarts.push(off);
17865
17856
  off += origLines[i2].length + 1;
17866
17857
  }
17867
- const lineOf = (idx) => {
17858
+ const lineOf2 = (idx) => {
17868
17859
  let lo = 0, hi = lineStarts.length - 1;
17869
17860
  while (lo < hi) {
17870
17861
  const mid = lo + hi + 1 >> 1;
@@ -17937,12 +17928,12 @@ function findRustLiteralEqualityGuardSanitizers(code) {
17937
17928
  }
17938
17929
  }
17939
17930
  const mutBinding = mutParam || new RegExp(String.raw`\bmut\s+${name2}\b|\b${name2}\s*:\s*&(?:\s*'\w+)?\s*mut\b`).test(masked.slice(0, at));
17940
- const firstLine = lineOf(close) + 1;
17941
- const lastLine = end === masked.length ? origLines.length - 1 : lineOf(end) - 1;
17931
+ const firstLine = lineOf2(close) + 1;
17932
+ const lastLine = end === masked.length ? origLines.length - 1 : lineOf2(end) - 1;
17942
17933
  let stop2 = lastLine + 1;
17943
17934
  let rebindLine = lastLine + 1;
17944
17935
  const rb = firstRebind(masked, close + 1, end, name2, { mutBinding });
17945
- if (rb >= 0) rebindLine = lineOf(rb);
17936
+ if (rb >= 0) rebindLine = lineOf2(rb);
17946
17937
  if (mutParam) {
17947
17938
  for (let l = firstLine; l < rebindLine && l <= lastLine; l++) {
17948
17939
  if (passesMutParam(maskedLines[l], name2)) {
@@ -17957,8 +17948,8 @@ function findRustLiteralEqualityGuardSanitizers(code) {
17957
17948
  for (const lp of masked.slice(close + 1, end).matchAll(/\b(?:for|while|loop)\b[^{;]*\{/g)) {
17958
17949
  const lpOpen = close + 1 + lp.index + lp[0].length - 1;
17959
17950
  const lpClose = matchBrace(masked, lpOpen);
17960
- const lpLine = lineOf(lpOpen);
17961
- if (lpClose >= 0 && lineOf(lpClose) >= l && lpLine <= l) stop2 = Math.min(stop2, lpLine);
17951
+ const lpLine = lineOf2(lpOpen);
17952
+ if (lpClose >= 0 && lineOf2(lpClose) >= l && lpLine <= l) stop2 = Math.min(stop2, lpLine);
17962
17953
  }
17963
17954
  }
17964
17955
  const mention = new RegExp(String.raw`(?<![\w.])${name2}\b`);
@@ -18753,6 +18744,7 @@ var LanguageSourcesPass = class {
18753
18744
  additionalSanitizers.push(
18754
18745
  ...findJsPathResolveStartsWithGuardSanitizers(code)
18755
18746
  );
18747
+ additionalSanitizers.push(...findJsRelativeRedirectGuardSanitizers(code));
18756
18748
  additionalSanitizers.push(
18757
18749
  ...findJsPathAllowlistHelperSanitizers(code)
18758
18750
  );
@@ -18971,10 +18963,10 @@ function findOopFieldReadSources(types, sourceCode, language) {
18971
18963
  }
18972
18964
  }
18973
18965
  if (!ctor) continue;
18974
- const paramNames = /* @__PURE__ */ new Set();
18966
+ const paramNames2 = /* @__PURE__ */ new Set();
18975
18967
  for (const p of ctor.parameters) {
18976
18968
  if (p.name === "self" || p.name === "this") continue;
18977
- paramNames.add(p.name);
18969
+ paramNames2.add(p.name);
18978
18970
  }
18979
18971
  const fieldTaint = /* @__PURE__ */ new Map();
18980
18972
  const ctorStart = ctor.start_line;
@@ -18995,7 +18987,7 @@ function findOopFieldReadSources(types, sourceCode, language) {
18995
18987
  if (pairs.length === 0) continue;
18996
18988
  for (const { field: fieldName, rhs } of pairs) {
18997
18989
  let sourceType = null;
18998
- if (paramNames.has(rhs)) {
18990
+ if (paramNames2.has(rhs)) {
18999
18991
  sourceType = "interprocedural_param";
19000
18992
  } else if (isJava && javaHttpPattern.test(rhs)) {
19001
18993
  sourceType = "http_param";
@@ -23732,7 +23724,7 @@ function findJsPathResolveStartsWithGuardSanitizers(code) {
23732
23724
  line: c.line,
23733
23725
  sanitizes: ["path_traversal", "external_taint_escape"]
23734
23726
  });
23735
- for (let l = c.line; l < lines.length; l++) {
23727
+ for (const l of jsGuardCreditLines(lines, c.line, c.fullVar)) {
23736
23728
  if (!varRefRe.test(lines[l])) continue;
23737
23729
  sanitizers.push({
23738
23730
  type: "js_path_resolve_startswith_guard",
@@ -23744,6 +23736,85 @@ function findJsPathResolveStartsWithGuardSanitizers(code) {
23744
23736
  }
23745
23737
  return sanitizers;
23746
23738
  }
23739
+ function findJsRelativeRedirectGuardSanitizers(code) {
23740
+ const sanitizers = [];
23741
+ if (!code.includes("startsWith") && !code.includes(".test(")) return sanitizers;
23742
+ const lines = code.split("\n");
23743
+ const quotes = ["'", '"', "`"];
23744
+ const lit = (q, body2) => `${q}${body2}${q}`;
23745
+ const anyQ = (cond, f) => quotes.some((q) => cond.includes(f(q)));
23746
+ const strictRegexes = ["/^\\/(?![\\/\\\\])/.test(", "/^\\/(?!\\/|\\\\)/.test(", "/^\\/[^\\/\\\\]/.test("];
23747
+ const terminatorRe = /\b(?:throw|return|res\s*\.\s*status\s*\([^)]*\)\s*\.\s*(?:send|end|json))/;
23748
+ const varRefFor = (v) => new RegExp(`(?<![\\w$.])${v.replace(/[.$]/g, "\\$&")}(?![\\w$])`);
23749
+ for (let i2 = 0; i2 < lines.length; i2++) {
23750
+ const raw = lines[i2];
23751
+ const cond = raw.replace(/\s+/g, "");
23752
+ const isIf = /\bif\s*\(/.test(raw);
23753
+ if (!isIf && !(cond.includes("?") && cond.includes(":"))) continue;
23754
+ let v;
23755
+ for (const q of quotes) {
23756
+ const at = cond.indexOf(`.startsWith(${lit(q, "//")})`);
23757
+ if (at > 0) {
23758
+ let k = at;
23759
+ while (k > 0 && /[\w$.]/.test(cond[k - 1])) k--;
23760
+ v = cond.slice(k, at).replace(/^!+/, "");
23761
+ break;
23762
+ }
23763
+ }
23764
+ const regexAccept = strictRegexes.find((r) => cond.includes(r));
23765
+ if (!v && regexAccept) {
23766
+ const after = cond.slice(cond.indexOf(regexAccept) + regexAccept.length);
23767
+ const m = /^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\)/.exec(after);
23768
+ v = m?.[1];
23769
+ }
23770
+ if (!v || !/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(v)) continue;
23771
+ const slash = (q) => `${v}.startsWith(${lit(q, "/")})`;
23772
+ const dbl = (q) => `${v}.startsWith(${lit(q, "//")})`;
23773
+ const back = (q) => `${v}.startsWith(${lit(q, "/\\\\")})`;
23774
+ const reject = cond.includes("||") && !cond.includes("&&") && anyQ(cond, (q) => `!${slash(q)}`) && anyQ(cond, dbl) && anyQ(cond, back) && !anyQ(cond, (q) => `!${dbl(q)}`) && !anyQ(cond, (q) => `!${back(q)}`);
23775
+ const accept = cond.includes("&&") && !cond.includes("||") && anyQ(cond, slash) && !anyQ(cond, (q) => `!${slash(q)}`) && anyQ(cond, (q) => `!${dbl(q)}`) && anyQ(cond, (q) => `!${back(q)}`) || !!regexAccept && !cond.includes(`!${regexAccept}`) && !cond.includes("||");
23776
+ const ref = varRefFor(v);
23777
+ if (!isIf) {
23778
+ if (accept && cond.includes(`?${v}:`)) sanitizers.push({ type: "js_relative_redirect_guard", method: "startsWith", line: i2 + 1, sanitizes: ["open_redirect"] });
23779
+ continue;
23780
+ }
23781
+ if (reject && guardRejects(lines, i2, terminatorRe, 2)) {
23782
+ for (const l of jsGuardCreditLines(lines, i2, v)) {
23783
+ if (ref.test(lines[l])) sanitizers.push({ type: "js_relative_redirect_guard", method: "startsWith", line: l + 1, sanitizes: ["open_redirect"] });
23784
+ }
23785
+ } else if (accept) {
23786
+ const block = jsBracedBlockLines(lines, i2);
23787
+ const body2 = block ?? [raw];
23788
+ for (let k = 0; k < body2.length; k++) {
23789
+ if (ref.test(k === 0 ? raw.slice(raw.indexOf(")", raw.indexOf("if")) + 1) : body2[k])) {
23790
+ sanitizers.push({ type: "js_relative_redirect_guard", method: "startsWith", line: i2 + k + 1, sanitizes: ["open_redirect"] });
23791
+ }
23792
+ }
23793
+ }
23794
+ }
23795
+ return sanitizers;
23796
+ }
23797
+ function jsGuardCreditLines(lines, from, v) {
23798
+ const esc = v.replace(/[.$]/g, "\\$&");
23799
+ const reassign = new RegExp(
23800
+ `(?:^|[^\\w$.])(?:(?:let|const|var)\\s+)?${esc}\\s*(?:[+\\-*/%|&^]?=)(?!=)`
23801
+ );
23802
+ const out2 = [];
23803
+ let depth = 0;
23804
+ for (let l = from; l < lines.length; l++) {
23805
+ const line = lines[l];
23806
+ if (l > from && reassign.test(line)) break;
23807
+ out2.push(l);
23808
+ for (const c of line) {
23809
+ if (c === "{") depth++;
23810
+ else if (c === "}") {
23811
+ depth--;
23812
+ if (depth < 0) return out2;
23813
+ }
23814
+ }
23815
+ }
23816
+ return out2;
23817
+ }
23747
23818
  function jsBracedBlockLines(lines, startLineIdx) {
23748
23819
  let depth = 0;
23749
23820
  let started = false;
@@ -27773,10 +27844,96 @@ function findPythonJinjaTemplateSstiFindings(code, file) {
27773
27844
  }
27774
27845
  return findings;
27775
27846
  }
27847
+ function firstJsCallArg(line, start2) {
27848
+ let depth = 0;
27849
+ for (let k = start2; k < line.length; k++) {
27850
+ const ch = line[k];
27851
+ if (ch === "'" || ch === '"' || ch === "`") {
27852
+ const end = line.indexOf(ch, k + 1);
27853
+ if (end < 0) return line.slice(start2);
27854
+ let e = end;
27855
+ while (e > 0 && line[e - 1] === "\\") {
27856
+ const next = line.indexOf(ch, e + 1);
27857
+ if (next < 0) return line.slice(start2);
27858
+ e = next;
27859
+ }
27860
+ k = e;
27861
+ continue;
27862
+ }
27863
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
27864
+ else if (ch === ")" || ch === "]" || ch === "}") {
27865
+ if (depth === 0) return line.slice(start2, k);
27866
+ depth--;
27867
+ } else if (ch === "," && depth === 0) return line.slice(start2, k);
27868
+ }
27869
+ return line.slice(start2);
27870
+ }
27871
+ function jsDestructuredFromRequest(stmt, reqRe) {
27872
+ const kw = ["const ", "let ", "var "].find((k) => stmt.startsWith(k));
27873
+ if (!kw) return null;
27874
+ const t = stmt.slice(kw.length).trimStart();
27875
+ if (!t.startsWith("{")) return null;
27876
+ const close = t.indexOf("}");
27877
+ if (close < 0) return null;
27878
+ const rest = t.slice(close + 1).trimStart();
27879
+ if (!rest.startsWith("=") || !reqRe.test(blankJsStringText(rest.slice(1)))) return null;
27880
+ const names = [];
27881
+ for (const raw of t.slice(1, close).split(",")) {
27882
+ let p = raw.trim();
27883
+ const eq = p.indexOf("=");
27884
+ if (eq >= 0) p = p.slice(0, eq).trim();
27885
+ const colon = p.indexOf(":");
27886
+ const bound = (colon >= 0 ? p.slice(colon + 1) : p).trim();
27887
+ if (/^[A-Za-z_$][\w$]*$/.test(bound)) names.push(bound);
27888
+ }
27889
+ return names.length > 0 ? names : null;
27890
+ }
27891
+ function blankJsStringText(expr) {
27892
+ let out2 = "";
27893
+ let k = 0;
27894
+ while (k < expr.length) {
27895
+ const ch = expr[k];
27896
+ if (ch === "'" || ch === '"') {
27897
+ let e = k + 1;
27898
+ while (e < expr.length && expr[e] !== ch) e += expr[e] === "\\" ? 2 : 1;
27899
+ out2 += "''";
27900
+ k = e + 1;
27901
+ continue;
27902
+ }
27903
+ if (ch === "`") {
27904
+ let e = k + 1;
27905
+ let subs = "";
27906
+ while (e < expr.length && expr[e] !== "`") {
27907
+ if (expr[e] === "\\") {
27908
+ e += 2;
27909
+ continue;
27910
+ }
27911
+ if (expr[e] === "$" && expr[e + 1] === "{") {
27912
+ const close = expr.indexOf("}", e + 2);
27913
+ if (close < 0) {
27914
+ subs += ` ${expr.slice(e + 2)}`;
27915
+ e = expr.length;
27916
+ break;
27917
+ }
27918
+ subs += ` ${expr.slice(e + 2, close)}`;
27919
+ e = close + 1;
27920
+ continue;
27921
+ }
27922
+ e++;
27923
+ }
27924
+ out2 += `''${subs}`;
27925
+ k = e + 1;
27926
+ continue;
27927
+ }
27928
+ out2 += ch;
27929
+ k++;
27930
+ }
27931
+ return out2;
27932
+ }
27776
27933
  function findJsTemplateInjectionSstiFindings(code, file) {
27777
27934
  const findings = [];
27778
27935
  if (typeof code !== "string" || code.length === 0) return findings;
27779
- if (!/\bHandlebars\s*\.\s*compile\s*\(/.test(code) && !/\bejs\s*\.\s*(?:render|compile)\s*\(/.test(code)) {
27936
+ if (!/\b[Hh]andlebars\s*\.\s*compile\s*\(/.test(code) && !/\b(?:ejs|pug)\s*\.\s*(?:render|compile)\s*\(/.test(code) && !/\bnunjucks\s*\.\s*renderString\s*\(/.test(code)) {
27780
27937
  return findings;
27781
27938
  }
27782
27939
  if (!/\breq\s*\.\s*(?:query|body|params|headers|cookies)\b/.test(code)) {
@@ -27790,10 +27947,15 @@ function findJsTemplateInjectionSstiFindings(code, file) {
27790
27947
  for (let i2 = 0; i2 < lines.length; i2++) {
27791
27948
  const t = lines[i2].trim();
27792
27949
  if (t.startsWith("//")) continue;
27950
+ const destructured = jsDestructuredFromRequest(t, reqExtractRe);
27951
+ if (destructured) {
27952
+ for (const name2 of destructured) taintedVars.add(name2);
27953
+ continue;
27954
+ }
27793
27955
  const m = t.match(/^(?:const|let|var)\s+(\w+)(?:\s*:\s*[^=]+)?\s*=\s*(.+?);?$/);
27794
27956
  if (!m) continue;
27795
27957
  const lhs = m[1];
27796
- const rhs = m[2];
27958
+ const rhs = blankJsStringText(m[2]);
27797
27959
  if (taintedVars.has(lhs)) continue;
27798
27960
  if (reqExtractRe.test(rhs)) {
27799
27961
  taintedVars.add(lhs);
@@ -27809,14 +27971,15 @@ function findJsTemplateInjectionSstiFindings(code, file) {
27809
27971
  if (taintedVars.size === before) break;
27810
27972
  }
27811
27973
  if (taintedVars.size === 0) return findings;
27812
- const callRe = /\b(Handlebars\s*\.\s*compile|ejs\s*\.\s*(?:render|compile))\s*\(\s*([^,)]+)/;
27974
+ const callRe = /\b([Hh]andlebars\s*\.\s*compile|(?:ejs|pug)\s*\.\s*(?:render|compile)|nunjucks\s*\.\s*renderString)\s*\(/;
27813
27975
  const seen = /* @__PURE__ */ new Set();
27814
27976
  for (let i2 = 0; i2 < lines.length; i2++) {
27815
27977
  const line = lines[i2];
27816
27978
  if (line.trim().startsWith("//")) continue;
27817
27979
  const m = line.match(callRe);
27818
- if (!m) continue;
27819
- const arg = m[2].trim();
27980
+ if (!m || m.index === void 0) continue;
27981
+ const arg = blankJsStringText(firstJsCallArg(line, m.index + m[0].length)).trim();
27982
+ if (arg === "") continue;
27820
27983
  let tainted = reqExtractRe.test(arg);
27821
27984
  if (!tainted) {
27822
27985
  for (const v of taintedVars) {
@@ -27837,7 +28000,7 @@ function findJsTemplateInjectionSstiFindings(code, file) {
27837
28000
  cwe: "CWE-1336",
27838
28001
  severity: "critical",
27839
28002
  level: "error",
27840
- message: "Server-side template injection: compiling/rendering a template whose source is attacker-controlled (`Handlebars.compile(...)` / `ejs.render(...)`) opens helper-shadowing and prototype-gadget RCE paths. Use a fixed template and pass user data as context.",
28003
+ message: "Server-side template injection: compiling/rendering a template whose source is attacker-controlled (`Handlebars.compile(...)` / `ejs.render(...)` / `pug.render(...)` / `nunjucks.renderString(...)`) opens helper-shadowing, prototype-gadget and template-code RCE paths. Use a fixed template and pass user data as context.",
27841
28004
  file,
27842
28005
  line: i2 + 1,
27843
28006
  snippet: line.trim()
@@ -30625,8 +30788,8 @@ function findSanitizers(calls, types, patterns, sourceLines, language) {
30625
30788
  for (const method of type.methods) {
30626
30789
  const bodySize = method.end_line - method.start_line;
30627
30790
  if (bodySize < 0 || bodySize > 2) continue;
30628
- const paramNames = new Set(method.parameters.map((p) => p.name));
30629
- if (paramNames.size === 0) continue;
30791
+ const paramNames2 = new Set(method.parameters.map((p) => p.name));
30792
+ if (paramNames2.size === 0) continue;
30630
30793
  const inside = [];
30631
30794
  for (const c of calls) {
30632
30795
  if (c.location.line < method.start_line || c.location.line > method.end_line) continue;
@@ -30663,7 +30826,7 @@ function findSanitizers(calls, types, patterns, sourceLines, language) {
30663
30826
  let argOk = false;
30664
30827
  if (replaceChainHelper) {
30665
30828
  const recv = innerCall.receiver?.trim() ?? "";
30666
- for (const p of paramNames) {
30829
+ for (const p of paramNames2) {
30667
30830
  if (recv === p || recv.startsWith(`${p}.`)) {
30668
30831
  argOk = true;
30669
30832
  break;
@@ -30671,7 +30834,7 @@ function findSanitizers(calls, types, patterns, sourceLines, language) {
30671
30834
  }
30672
30835
  } else {
30673
30836
  for (const arg of innerCall.arguments) {
30674
- if (arg.variable && paramNames.has(arg.variable)) {
30837
+ if (arg.variable && paramNames2.has(arg.variable)) {
30675
30838
  argOk = true;
30676
30839
  break;
30677
30840
  }
@@ -30685,7 +30848,7 @@ function findSanitizers(calls, types, patterns, sourceLines, language) {
30685
30848
  if (!returnMatch) continue;
30686
30849
  const after = returnMatch[1].replace(/;\s*$/, "").trimEnd();
30687
30850
  if (replaceChainHelper) {
30688
- const startsWithParam = [...paramNames].some(
30851
+ const startsWithParam = [...paramNames2].some(
30689
30852
  (p) => after === p || after.startsWith(`${p}.`)
30690
30853
  );
30691
30854
  if (!startsWithParam) continue;
@@ -30714,8 +30877,8 @@ function findSanitizers(calls, types, patterns, sourceLines, language) {
30714
30877
  if (wrapperSanitizers.has(method.name)) continue;
30715
30878
  const bodySize = method.end_line - method.start_line;
30716
30879
  if (bodySize < 0 || bodySize > 2) continue;
30717
- const paramNames = new Set(method.parameters.map((p) => p.name));
30718
- if (paramNames.size === 0) continue;
30880
+ const paramNames2 = new Set(method.parameters.map((p) => p.name));
30881
+ if (paramNames2.size === 0) continue;
30719
30882
  const inside = [];
30720
30883
  for (const c of calls) {
30721
30884
  if (c.location.line < method.start_line || c.location.line > method.end_line) continue;
@@ -30728,7 +30891,7 @@ function findSanitizers(calls, types, patterns, sourceLines, language) {
30728
30891
  if (!delegateRemoves || delegateRemoves.length === 0) continue;
30729
30892
  let argOk = false;
30730
30893
  for (const arg of innerCall.arguments) {
30731
- if (arg.variable && paramNames.has(arg.variable)) {
30894
+ if (arg.variable && paramNames2.has(arg.variable)) {
30732
30895
  argOk = true;
30733
30896
  break;
30734
30897
  }
@@ -31346,6 +31509,10 @@ function walkBackwardDefs(startDefId, chainsByToDef, defById, options = {}) {
31346
31509
  // src/analysis/findings.ts
31347
31510
  function canSourceReachSink(sourceType, sinkType) {
31348
31511
  const sourceToSinkMapping = {
31512
+ // redos added to http_*: a request value used as
31513
+ // the pattern of `new RegExp(req.query.p)` on one line never produced the
31514
+ // inline flow. The colocation detector only emits it when the value sits
31515
+ // in the sink's pattern argument (`redosColocatedInPatternArg`).
31349
31516
  // code_injection added to http_param/http_query/http_header/http_cookie:
31350
31517
  // `eval(req.query.x)`, `Function(req.header('x'))`, `vm.runInThisContext(req.cookies.c)`
31351
31518
  // are all real RCE patterns in JS web apps (cognium-dev #83).
@@ -31396,20 +31563,24 @@ function canSourceReachSink(sourceType, sinkType) {
31396
31563
  // pairing was gated out and generateFindings dropped it — same class as the
31397
31564
  // #129 log_injection/format_string/nosql_injection drop. Mirrors how
31398
31565
  // deserialization already sits on both http_param and http_query.
31566
+ // deserialization added to http_cookie: a cookie value reaching node-serialize's
31567
+ // unserialize (or any deserialization sink) is the classic JS RCE (CVE-2017-5941 came in
31568
+ // through a cookie). The reach map had it on http_param/http_query/http_body only, so
31569
+ // `serialize.unserialize(req.cookies.profile)` was dropped while the req.body form fired.
31399
31570
  // cache_poisoning added (cognium-dev #900): request-derived strings written
31400
31571
  // into a shared in-memory cache (Map.set value arg, OIDC/mr-title-frag shapes).
31401
- http_param: ["sql_injection", "command_injection", "path_traversal", "xss", "xpath_injection", "ldap_injection", "ssrf", "mybatis_mapper_call", "code_injection", "crlf", "mass_assignment", "open_redirect", "trust_boundary", "deserialization", "xxe", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning"],
31402
- http_body: ["sql_injection", "command_injection", "deserialization", "xxe", "xss", "code_injection", "mybatis_mapper_call", "crlf", "mass_assignment", "open_redirect", "trust_boundary", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning"],
31403
- http_header: ["sql_injection", "xss", "ssrf", "mybatis_mapper_call", "code_injection", "crlf", "open_redirect", "trust_boundary", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning"],
31404
- http_cookie: ["sql_injection", "xss", "mybatis_mapper_call", "code_injection", "crlf", "open_redirect", "trust_boundary", "log_injection", "format_string", "nosql_injection", "prompt_injection"],
31572
+ http_param: ["sql_injection", "command_injection", "path_traversal", "xss", "xpath_injection", "ldap_injection", "ssrf", "mybatis_mapper_call", "code_injection", "crlf", "mass_assignment", "open_redirect", "trust_boundary", "deserialization", "xxe", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning", "redos"],
31573
+ http_body: ["sql_injection", "command_injection", "deserialization", "xxe", "xss", "code_injection", "mybatis_mapper_call", "crlf", "mass_assignment", "open_redirect", "trust_boundary", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning", "redos"],
31574
+ http_header: ["sql_injection", "xss", "ssrf", "mybatis_mapper_call", "code_injection", "crlf", "open_redirect", "trust_boundary", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning", "redos"],
31575
+ http_cookie: ["sql_injection", "xss", "mybatis_mapper_call", "code_injection", "crlf", "open_redirect", "trust_boundary", "deserialization", "log_injection", "format_string", "nosql_injection", "prompt_injection", "redos"],
31405
31576
  // xss added cognium-dev 3.163.0: URL path components (getRequestURI,
31406
31577
  // getRequestURL, getPathInfo, getServletPath) reflected back into HTML
31407
31578
  // output are a classic reflected-XSS vector — cf. Basic35 in
31408
31579
  // SecuriBench Micro where `writer.println(req.getRequestURL())` is
31409
31580
  // annotated `/* BAD */`. Prior to 3.163.0 the reach map omitted xss
31410
31581
  // so http_path → xss inline-colocation flows were silently dropped.
31411
- http_path: ["path_traversal", "sql_injection", "ssrf", "mybatis_mapper_call", "open_redirect", "trust_boundary", "xss", "log_injection", "format_string", "prompt_injection"],
31412
- http_query: ["sql_injection", "command_injection", "xss", "ssrf", "mybatis_mapper_call", "code_injection", "crlf", "mass_assignment", "open_redirect", "trust_boundary", "deserialization", "xxe", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning"],
31582
+ http_path: ["path_traversal", "sql_injection", "ssrf", "mybatis_mapper_call", "open_redirect", "trust_boundary", "xss", "log_injection", "format_string", "prompt_injection", "redos"],
31583
+ http_query: ["sql_injection", "command_injection", "xss", "ssrf", "mybatis_mapper_call", "code_injection", "crlf", "mass_assignment", "open_redirect", "trust_boundary", "deserialization", "xxe", "log_injection", "format_string", "nosql_injection", "prompt_injection", "cache_poisoning", "redos"],
31413
31584
  // ssrf added Sprint 57 #200: bash CGI/webhook handlers and scripts that
31414
31585
  // take a URL on stdin or as a positional CLI arg (`curl "$1"`,
31415
31586
  // `wget "$(read line)"`) and curl/wget it server-side are textbook SSRF
@@ -39757,16 +39928,16 @@ var ConstantPropagator = class _ConstantPropagator {
39757
39928
  }
39758
39929
  if (node.type === "identifier") {
39759
39930
  let isTainted = false;
39760
- let boundName = null;
39931
+ let boundName2 = null;
39761
39932
  for (const candidate of this.getScopedNameCandidates(text)) {
39762
39933
  if (this.tainted.has(candidate)) {
39763
39934
  isTainted = true;
39764
- boundName = candidate;
39935
+ boundName2 = candidate;
39765
39936
  break;
39766
39937
  }
39767
39938
  }
39768
- if (isTainted && boundName) {
39769
- if (this.isExcludedByCondition(boundName) || this.isExcludedByCondition(text)) {
39939
+ if (isTainted && boundName2) {
39940
+ if (this.isExcludedByCondition(boundName2) || this.isExcludedByCondition(text)) {
39770
39941
  return false;
39771
39942
  }
39772
39943
  }
@@ -45732,12 +45903,12 @@ var HELPER_RETURN_GATED_SINKS = /* @__PURE__ */ new Set([
45732
45903
  ]);
45733
45904
  function calleeReturnMayCarryParam(code, startLine, endLine, sourceVars) {
45734
45905
  const raw = code.split("\n").slice(startLine - 1, endLine);
45735
- const paramNames = [...sourceVars, ...javaMethodParamNames(raw)];
45906
+ const paramNames2 = [...sourceVars, ...javaMethodParamNames(raw)];
45736
45907
  const dead = computeDeadJavaBranchLines(raw);
45737
45908
  const inlined = /* @__PURE__ */ new Set();
45738
45909
  const slice = joinWrappedStatements(raw, inlined);
45739
45910
  const text = slice.join("\n");
45740
- const seeds = new Set(paramNames);
45911
+ const seeds = new Set(paramNames2);
45741
45912
  const mutated = /* @__PURE__ */ new Set();
45742
45913
  let live = new Set(seeds);
45743
45914
  for (let round = 0; round < 8; round++) {
@@ -45955,12 +46126,12 @@ function javaHelperCallHasInstanceReceiver(graph, edge) {
45955
46126
  }
45956
46127
  function skipPassThroughTrustBoundaryWithoutHttpArg(graph, fileCode, edge, calleeStart, calleeEnd, fileSources, paramVars) {
45957
46128
  const lines = fileCode.split("\n");
45958
- const paramNames = javaMethodParamNames(lines.slice(calleeStart - 1, calleeEnd));
46129
+ const paramNames2 = javaMethodParamNames(lines.slice(calleeStart - 1, calleeEnd));
45959
46130
  const callSite = graph.ir.calls?.find(
45960
46131
  (c) => c.location.line === edge.callLine && (c.in_method ?? null) === edge.callerMethod
45961
46132
  );
45962
46133
  for (const paramVar of paramVars) {
45963
- const idx = paramNames.indexOf(paramVar);
46134
+ const idx = paramNames2.indexOf(paramVar);
45964
46135
  if (idx < 0) continue;
45965
46136
  const fromCall = callSite?.arguments?.find((a) => a.position === idx);
45966
46137
  const argVar = fromCall?.variable ?? (fromCall?.expression && /^[A-Za-z_]\w*$/.test(fromCall.expression.trim()) ? fromCall.expression.trim() : void 0);
@@ -52733,10 +52904,10 @@ function shouldGateCSharpPatPermsLibraryParamFlow(flow, sources, sinks, types, c
52733
52904
  ctx
52734
52905
  );
52735
52906
  }
52736
- function compoundArgParamNames(expression, paramNames) {
52907
+ function compoundArgParamNames(expression, paramNames2) {
52737
52908
  const stripped = expression.replace(/(['"`])(?:\\.|(?!\1)[^\\\n\r\u2028\u2029])*\1/g, (m) => " ".repeat(m.length));
52738
52909
  const matched = [];
52739
- for (const raw of paramNames) {
52910
+ for (const raw of paramNames2) {
52740
52911
  const name2 = raw.startsWith("*") ? raw.slice(1) : raw;
52741
52912
  if (!/^[\w$]+$/.test(name2)) continue;
52742
52913
  const re = new RegExp(
@@ -52843,7 +53014,7 @@ function csharpMethodScopedAliases(code, seeds, methods, fieldNames) {
52843
53014
  const declRe = /^\s*(?:public|private|protected|internal|static|readonly|const|\s)*\s*(?:[A-Za-z_][\w.]*(?:\s*<[^>]*>)?(?:\s*\[\s*\])*\??)\s+([A-Za-z_]\w*)\s*=\s*(.+?);\s*$/;
52844
53015
  const assignRe = /^\s*(?:this\s*\.\s*)?([A-Za-z_]\w*)\s*=\s*(.+?);\s*$/;
52845
53016
  const returnRe = /^\s*return\s+(.+?);\s*$/;
52846
- const KEYWORDS3 = /* @__PURE__ */ new Set(["return", "throw", "new", "await", "yield", "else", "case", "using", "var"]);
53017
+ const KEYWORDS4 = /* @__PURE__ */ new Set(["return", "throw", "new", "await", "yield", "else", "case", "using", "var"]);
52847
53018
  const codeOf = (rhs) => rhs.replace(/\$@?"(?:[^"\\]|\\.)*"/g, (lit) => " " + [...lit.matchAll(/\{([^}]*)\}/g)].map((x) => x[1]).join(" ") + " ").replace(/@?"(?:[^"\\]|\\.)*"/g, " ").replace(/'(?:[^'\\]|\\.)'/g, " ");
52848
53019
  const local = /* @__PURE__ */ new Map();
52849
53020
  const taintedFields = /* @__PURE__ */ new Set();
@@ -52898,7 +53069,7 @@ function csharpMethodScopedAliases(code, seeds, methods, fieldNames) {
52898
53069
  }
52899
53070
  if (!d) continue;
52900
53071
  const [, lhs, rhs] = d;
52901
- if (KEYWORDS3.has(lhs)) continue;
53072
+ if (KEYWORDS4.has(lhs)) continue;
52902
53073
  const isField = fieldNames.has(lhs) && !declRe.test(text);
52903
53074
  if (isField ? taintedFields.has(lhs) : here.has(lhs)) continue;
52904
53075
  const rhsCode = codeOf(rhs);
@@ -53530,6 +53701,15 @@ function sinkNestedInJsTsParseArgs(lineText, sinkMethod) {
53530
53701
  }
53531
53702
  return false;
53532
53703
  }
53704
+ function redosColocatedInPatternArg(source, sink, calls) {
53705
+ if (source.variable) return false;
53706
+ const loc = source.location ?? "";
53707
+ const at = loc.indexOf(" in ");
53708
+ const expr = (at >= 0 ? loc.slice(0, at) : loc).trim();
53709
+ if (expr.length < 3) return false;
53710
+ const positions = sink.argPositions && sink.argPositions.length > 0 ? sink.argPositions : [0];
53711
+ return calls.some((c) => c.location.line === sink.line && c.method_name === sink.method && c.arguments.some((a) => positions.includes(a.position) && (a.expression ?? "").includes(expr)));
53712
+ }
53533
53713
  function detectExpressionScanFlows(calls, sources, sinks, sanitizers, unreachableLines, tainted, code, language, types) {
53534
53714
  const flows = [];
53535
53715
  const methodRanges = (langs) => language && langs.includes(language) && types ? types.flatMap((t) => t.methods.map((m) => [m.start_line, m.end_line])) : [];
@@ -54050,7 +54230,7 @@ function detectExpressionScanFlows(calls, sources, sinks, sanitizers, unreachabl
54050
54230
  };
54051
54231
  const argListRe = /(?<![\w.])(\w+)\s*\.\s*(StartInfo\s*\.\s*)?ArgumentList\s*\.\s*Add\s*\(\s*(.+?)\s*\)\s*;?\s*(?:\/\/.*)?$/;
54052
54232
  const shellFlagRe = /^(?:[-/](?:c|k|command|encodedcommand|ec))$/i;
54053
- const splitTopLevel2 = (text) => {
54233
+ const splitTopLevel3 = (text) => {
54054
54234
  const parts2 = [];
54055
54235
  let depth = 0;
54056
54236
  let quote = "";
@@ -54098,10 +54278,10 @@ function detectExpressionScanFlows(calls, sources, sinks, sanitizers, unreachabl
54098
54278
  const m = /new\s+ProcessStartInfo\s*(?:\(([^()]*)\))?\s*(?:\{([\s\S]*)\})?\s*;/.exec(text);
54099
54279
  if (!m) return { program: null };
54100
54280
  let program;
54101
- const ctorArgs = splitTopLevel2(m[1] ?? "");
54281
+ const ctorArgs = splitTopLevel3(m[1] ?? "");
54102
54282
  if (ctorArgs.length > 1) return { program: null };
54103
54283
  if (ctorArgs.length === 1) program = constLiteral(ctorArgs[0]);
54104
- for (const member of splitTopLevel2(m[2] ?? "")) {
54284
+ for (const member of splitTopLevel3(m[2] ?? "")) {
54105
54285
  const em = /^(\w+)\s*=(?!=)\s*([\s\S]*)$/.exec(member);
54106
54286
  if (!em) return { program: null };
54107
54287
  if (em[1] === "FileName") {
@@ -54448,6 +54628,7 @@ function detectExpressionScanFlows(calls, sources, sinks, sanitizers, unreachabl
54448
54628
  for (const source of colocSources) {
54449
54629
  if (!canSourceReachSink(source.type, sink.type)) continue;
54450
54630
  if (!sourceSemanticsAllowed(source, sink.type)) continue;
54631
+ if (sink.type === "redos" && !redosColocatedInPatternArg(source, sink, calls)) continue;
54451
54632
  const colocLineText = sink.code ?? "";
54452
54633
  if (colocLineText && (language === "javascript" || language === "typescript") && source.type === "io_input" && typeof source.location === "string" && source.location.includes(".parse()") && sinkNestedInJsTsParseArgs(colocLineText, sink.method)) {
54453
54634
  continue;
@@ -57604,8 +57785,8 @@ var BlockingMainThreadPass = class {
57604
57785
  isRequestHandler(method) {
57605
57786
  if (method.annotations.some((a) => HTTP_DECORATORS.has(a))) return true;
57606
57787
  if (HANDLER_METHOD_NAMES.has(method.name)) return true;
57607
- const paramNames = method.parameters.map((p) => p.name.toLowerCase());
57608
- return paramNames.some((n) => HANDLER_PARAM_NAMES.has(n));
57788
+ const paramNames2 = method.parameters.map((p) => p.name.toLowerCase());
57789
+ return paramNames2.some((n) => HANDLER_PARAM_NAMES.has(n));
57609
57790
  }
57610
57791
  };
57611
57792
 
@@ -59542,6 +59723,76 @@ var InsecureCookiePass = class {
59542
59723
  }
59543
59724
  };
59544
59725
 
59726
+ // src/analysis/passes/_js-crypto-binding.ts
59727
+ var CRYPTO_MODULES = /* @__PURE__ */ new Set(["crypto", "node:crypto"]);
59728
+ var IMPORT_DECL_SPAN = 3;
59729
+ var REQUIRE_CRYPTO_RE = /^require\(\s*(['"])(?:node:)?crypto\1\s*\)$/;
59730
+ function jsCryptoBindings(imports, declarations) {
59731
+ const modules = /* @__PURE__ */ new Set();
59732
+ const named2 = /* @__PURE__ */ new Map();
59733
+ const importLine = /* @__PURE__ */ new Map();
59734
+ for (const imp of imports ?? []) {
59735
+ if (!imp.from_package || !CRYPTO_MODULES.has(imp.from_package)) continue;
59736
+ if (imp.is_type_only) continue;
59737
+ if (imp.is_wildcard || imp.imported_name === "*" || imp.imported_name === "default") {
59738
+ if (imp.alias) {
59739
+ modules.add(imp.alias);
59740
+ importLine.set(imp.alias, imp.line_number);
59741
+ }
59742
+ continue;
59743
+ }
59744
+ const local = imp.alias ?? imp.imported_name;
59745
+ named2.set(local, imp.imported_name);
59746
+ importLine.set(local, imp.line_number);
59747
+ }
59748
+ if (declarations && importLine.size > 0) {
59749
+ for (const name2 of redeclaredNames(importLine, declarations)) {
59750
+ modules.delete(name2);
59751
+ named2.delete(name2);
59752
+ }
59753
+ }
59754
+ return { modules, named: named2 };
59755
+ }
59756
+ function redeclaredNames(importLine, decl) {
59757
+ const out2 = /* @__PURE__ */ new Set();
59758
+ const defs = decl.dfg?.defs ?? [];
59759
+ const ownDef = /* @__PURE__ */ new Map();
59760
+ for (const def of defs) {
59761
+ const line = importLine.get(def.variable);
59762
+ if (line == null || def.kind !== "local") continue;
59763
+ const gap = line - def.line;
59764
+ if (gap < 0 || gap > IMPORT_DECL_SPAN) continue;
59765
+ const prev = ownDef.get(def.variable);
59766
+ if (!prev || def.line > prev.line) ownDef.set(def.variable, def);
59767
+ }
59768
+ for (const def of defs) {
59769
+ if (!importLine.has(def.variable)) continue;
59770
+ if (ownDef.get(def.variable) === def) continue;
59771
+ out2.add(def.variable);
59772
+ }
59773
+ for (const type of decl.types ?? []) {
59774
+ for (const method of type.methods) {
59775
+ if (type.name === "<module>" && importLine.has(method.name)) out2.add(method.name);
59776
+ for (const param of method.parameters) {
59777
+ if (importLine.has(param.name)) out2.add(param.name);
59778
+ }
59779
+ }
59780
+ }
59781
+ return out2;
59782
+ }
59783
+ function cryptoCallAsMember(call, bindings2) {
59784
+ const receiver = (call.receiver ?? "").trim();
59785
+ if (receiver === "crypto") return call;
59786
+ if (!receiver) {
59787
+ const api = bindings2.named.get(call.method_name);
59788
+ return api ? { ...call, receiver: "crypto", method_name: api } : call;
59789
+ }
59790
+ if (bindings2.modules.has(receiver) || REQUIRE_CRYPTO_RE.test(receiver)) {
59791
+ return { ...call, receiver: "crypto" };
59792
+ }
59793
+ return call;
59794
+ }
59795
+
59545
59796
  // src/analysis/passes/weak-hash-pass.ts
59546
59797
  var WEAK_HASH_NAMES = /* @__PURE__ */ new Set([
59547
59798
  "md2",
@@ -59786,7 +60037,10 @@ var WeakHashPass = class {
59786
60037
  const findings = [];
59787
60038
  const constProp = ctx.hasResult("constant-propagation") ? ctx.getResult("constant-propagation") : null;
59788
60039
  const javaBindings = language === "java" ? scanJavaStringBindings(code) : /* @__PURE__ */ new Map();
59789
- for (const call of graph.ir.calls) {
60040
+ const isJs2 = language === "javascript" || language === "typescript";
60041
+ const cryptoBindings = isJs2 ? jsCryptoBindings(graph.ir.imports, graph.ir) : null;
60042
+ for (const irCall of graph.ir.calls) {
60043
+ const call = cryptoBindings ? cryptoCallAsMember(irCall, cryptoBindings) : irCall;
59790
60044
  const enclosing = language === "java" ? graph.methodAtLine(call.location.line) : null;
59791
60045
  const methodRange = enclosing ? { start: enclosing.method.start_line, end: enclosing.method.end_line } : null;
59792
60046
  const detection = this.detect(call, language, constProp, javaBindings, code, ctx.resources, methodRange);
@@ -60152,7 +60406,10 @@ var WeakCryptoPass = class {
60152
60406
  evidence: { ...det, language }
60153
60407
  });
60154
60408
  };
60155
- for (const call of graph.ir.calls) {
60409
+ const isJs2 = language === "javascript" || language === "typescript";
60410
+ const cryptoBindings = isJs2 ? jsCryptoBindings(graph.ir.imports, graph.ir) : null;
60411
+ for (const irCall of graph.ir.calls) {
60412
+ const call = cryptoBindings ? cryptoCallAsMember(irCall, cryptoBindings) : irCall;
60156
60413
  for (const det of this.detect(call, language, constProp, literalBindings)) {
60157
60414
  emit(call.location.line, det);
60158
60415
  }
@@ -60726,7 +60983,10 @@ var WeakPasswordHashPass = class {
60726
60983
  return { findings: [] };
60727
60984
  }
60728
60985
  const findings = [];
60729
- for (const call of graph.ir.calls) {
60986
+ const isJs2 = language === "javascript" || language === "typescript";
60987
+ const cryptoBindings = isJs2 ? jsCryptoBindings(graph.ir.imports, graph.ir) : null;
60988
+ for (const irCall of graph.ir.calls) {
60989
+ const call = cryptoBindings ? cryptoCallAsMember(irCall, cryptoBindings) : irCall;
60730
60990
  const detection = this.detect(call, language);
60731
60991
  if (!detection) continue;
60732
60992
  const { kind, api } = detection;
@@ -62940,9 +63200,9 @@ function isSecretName(name2) {
62940
63200
  const ws = words(name2);
62941
63201
  if (ws.length === 0) return false;
62942
63202
  if (ws.length > 1 && FLAG_PREFIXES.includes(ws[0])) return false;
62943
- const norm = ws.join("");
62944
- if (SECRET_NAMES.has(norm)) return true;
62945
- return SECRET_SUFFIXES.some((s) => norm.length > s.length && norm.endsWith(s));
63203
+ const norm2 = ws.join("");
63204
+ if (SECRET_NAMES.has(norm2)) return true;
63205
+ return SECRET_SUFFIXES.some((s) => norm2.length > s.length && norm2.endsWith(s));
62946
63206
  }
62947
63207
  function isIdentStart(ch) {
62948
63208
  return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_" || ch === "$";
@@ -63217,9 +63477,1498 @@ var SensitiveDataInLogPass = class {
63217
63477
  }
63218
63478
  };
63219
63479
 
63480
+ // src/analysis/passes/redos-regex-literal-pass.ts
63481
+ var Unsupported = class extends Error {
63482
+ };
63483
+ var MAX_GROUP_DEPTH = 100;
63484
+ var MAX_SOURCE_LENGTH = 1e4;
63485
+ function isDigit(ch) {
63486
+ return ch !== void 0 && ch >= "0" && ch <= "9";
63487
+ }
63488
+ function parseRegex(source) {
63489
+ if (source.length > MAX_SOURCE_LENGTH) return null;
63490
+ let i2 = 0;
63491
+ let depth = 0;
63492
+ const n = source.length;
63493
+ function readEscape() {
63494
+ const c = source[i2 + 1];
63495
+ if (c === void 0) throw new Unsupported();
63496
+ if (c >= "1" && c <= "9") throw new Unsupported();
63497
+ if (c === "k" && source[i2 + 2] === "<") throw new Unsupported();
63498
+ if (c === "b" || c === "B") {
63499
+ i2 += 2;
63500
+ return { kind: "assert" };
63501
+ }
63502
+ if (c === "u" && source[i2 + 2] === "{") {
63503
+ const close = source.indexOf("}", i2 + 3);
63504
+ if (close < 0) throw new Unsupported();
63505
+ i2 = close + 1;
63506
+ return { kind: "char" };
63507
+ }
63508
+ if ((c === "p" || c === "P") && source[i2 + 2] === "{") {
63509
+ const close = source.indexOf("}", i2 + 3);
63510
+ if (close < 0) throw new Unsupported();
63511
+ i2 = close + 1;
63512
+ return { kind: "char" };
63513
+ }
63514
+ if (c === "u") {
63515
+ i2 += 6;
63516
+ return { kind: "char" };
63517
+ }
63518
+ if (c === "x") {
63519
+ i2 += 4;
63520
+ return { kind: "char" };
63521
+ }
63522
+ if (c === "c") {
63523
+ i2 += 3;
63524
+ return { kind: "char" };
63525
+ }
63526
+ i2 += 2;
63527
+ return { kind: "char" };
63528
+ }
63529
+ function readClass() {
63530
+ i2++;
63531
+ if (source[i2] === "^") i2++;
63532
+ while (i2 < n) {
63533
+ const ch = source[i2];
63534
+ if (ch === "\\") {
63535
+ i2 += 2;
63536
+ continue;
63537
+ }
63538
+ i2++;
63539
+ if (ch === "]") return { kind: "char" };
63540
+ }
63541
+ throw new Unsupported();
63542
+ }
63543
+ function readQuantifier() {
63544
+ const ch = source[i2];
63545
+ let q = null;
63546
+ if (ch === "*") {
63547
+ q = { min: 0, max: Infinity };
63548
+ i2++;
63549
+ } else if (ch === "+") {
63550
+ q = { min: 1, max: Infinity };
63551
+ i2++;
63552
+ } else if (ch === "?") {
63553
+ q = { min: 0, max: 1 };
63554
+ i2++;
63555
+ } else if (ch === "{") {
63556
+ let j = i2 + 1;
63557
+ let a = "";
63558
+ while (isDigit(source[j])) a += source[j++];
63559
+ if (a === "") return null;
63560
+ let max = Number(a);
63561
+ if (source[j] === ",") {
63562
+ j++;
63563
+ let b = "";
63564
+ while (isDigit(source[j])) b += source[j++];
63565
+ max = b === "" ? Infinity : Number(b);
63566
+ }
63567
+ if (source[j] !== "}") return null;
63568
+ q = { min: Number(a), max };
63569
+ i2 = j + 1;
63570
+ }
63571
+ if (q && source[i2] === "?") i2++;
63572
+ return q;
63573
+ }
63574
+ function readAlts(inGroup) {
63575
+ const alts = [[]];
63576
+ while (i2 < n) {
63577
+ const ch = source[i2];
63578
+ if (ch === "|") {
63579
+ alts.push([]);
63580
+ i2++;
63581
+ continue;
63582
+ }
63583
+ if (ch === ")") {
63584
+ if (!inGroup) throw new Unsupported();
63585
+ return alts;
63586
+ }
63587
+ let atom;
63588
+ if (ch === "\\") atom = readEscape();
63589
+ else if (ch === "[") atom = readClass();
63590
+ else if (ch === "^") {
63591
+ atom = { kind: "assert" };
63592
+ i2++;
63593
+ } else if (ch === "$") {
63594
+ atom = { kind: "end" };
63595
+ i2++;
63596
+ } else if (ch === "(") {
63597
+ let lookaround = false;
63598
+ if (source[i2 + 1] === "?") {
63599
+ const k = source[i2 + 2];
63600
+ if (k === ":") i2 += 3;
63601
+ else if (k === "=" || k === "!") {
63602
+ lookaround = true;
63603
+ i2 += 3;
63604
+ } else if (k === "<" && (source[i2 + 3] === "=" || source[i2 + 3] === "!")) {
63605
+ lookaround = true;
63606
+ i2 += 4;
63607
+ } else if (k === "<") {
63608
+ const close = source.indexOf(">", i2 + 3);
63609
+ if (close < 0) throw new Unsupported();
63610
+ i2 = close + 1;
63611
+ } else throw new Unsupported();
63612
+ } else i2++;
63613
+ if (++depth > MAX_GROUP_DEPTH) throw new Unsupported();
63614
+ const inner = readAlts(true);
63615
+ depth--;
63616
+ if (source[i2] !== ")") throw new Unsupported();
63617
+ i2++;
63618
+ atom = lookaround ? { kind: "assert" } : { kind: "group", alts: inner };
63619
+ } else {
63620
+ atom = { kind: "char" };
63621
+ i2++;
63622
+ }
63623
+ const q = readQuantifier();
63624
+ alts[alts.length - 1].push({ atom, min: q ? q.min : 1, max: q ? q.max : 1 });
63625
+ }
63626
+ if (inGroup) throw new Unsupported();
63627
+ return alts;
63628
+ }
63629
+ try {
63630
+ const alts = readAlts(false);
63631
+ return i2 === n ? alts : null;
63632
+ } catch (e) {
63633
+ if (e instanceof Unsupported) return null;
63634
+ throw e;
63635
+ }
63636
+ }
63637
+ function canMatchNonEmpty(atom) {
63638
+ if (atom.kind === "char") return true;
63639
+ if (atom.kind !== "group") return false;
63640
+ return atom.alts.some((alt) => alt.some((t) => t.max > 0 && canMatchNonEmpty(t.atom)));
63641
+ }
63642
+ function loopsAlone(t) {
63643
+ if (t.max === 0) return false;
63644
+ if (t.max === Infinity && canMatchNonEmpty(t.atom)) return true;
63645
+ return t.atom.kind === "group" && t.atom.alts.some(altLoopsAlone);
63646
+ }
63647
+ function altLoopsAlone(alt) {
63648
+ for (let i2 = 0; i2 < alt.length; i2++) {
63649
+ if (!loopsAlone(alt[i2])) continue;
63650
+ if (alt.every((t, j) => j === i2 || t.min === 0)) return true;
63651
+ }
63652
+ return false;
63653
+ }
63654
+ function isMandatory(t) {
63655
+ return t.min >= 1 && (t.atom.kind === "end" || canMatchNonEmpty(t.atom));
63656
+ }
63657
+ function isExponentialRegex(source, flags2 = "") {
63658
+ if (flags2.includes("v")) return false;
63659
+ const alts = parseRegex(source);
63660
+ if (!alts) return false;
63661
+ const visit = (seqs, followed) => {
63662
+ for (const seq of seqs) {
63663
+ for (let i2 = 0; i2 < seq.length; i2++) {
63664
+ const t = seq[i2];
63665
+ const after = followed || seq.slice(i2 + 1).some(isMandatory);
63666
+ if (t.atom.kind !== "group") continue;
63667
+ if (t.max === Infinity && after && t.atom.alts.some(altLoopsAlone)) return true;
63668
+ if (visit(t.atom.alts, after)) return true;
63669
+ }
63670
+ }
63671
+ return false;
63672
+ };
63673
+ return visit(alts, false);
63674
+ }
63675
+ function splitRegexLiteral(text) {
63676
+ const t = text.trim();
63677
+ if (t.length < 3 || t[0] !== "/" || t[1] === "/" || t[1] === "*") return null;
63678
+ const end = t.lastIndexOf("/");
63679
+ if (end <= 0) return null;
63680
+ const flags2 = t.slice(end + 1);
63681
+ for (const ch of flags2) if (ch < "a" || ch > "z") return null;
63682
+ const source = t.slice(1, end);
63683
+ let inClass = false;
63684
+ for (let k = 0; k < source.length; k++) {
63685
+ const ch = source[k];
63686
+ if (ch === "\\") {
63687
+ k++;
63688
+ continue;
63689
+ }
63690
+ if (ch === "[") inClass = true;
63691
+ else if (ch === "]") inClass = false;
63692
+ else if (ch === "/" && !inClass) return null;
63693
+ else if (ch === "\n") return null;
63694
+ }
63695
+ return { source, flags: flags2 };
63696
+ }
63697
+ var REQ_NAMES = /* @__PURE__ */ new Set(["req", "request"]);
63698
+ var REQ_PARTS = /* @__PURE__ */ new Set(["query", "body", "params", "headers", "cookies"]);
63699
+ var PRESERVING_METHODS = [".trim()", ".toString()", ".toLowerCase()", ".toUpperCase()"];
63700
+ function isIdentStart2(ch) {
63701
+ return ch !== void 0 && (ch === "_" || ch === "$" || ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z");
63702
+ }
63703
+ function isIdentChar2(ch) {
63704
+ return isIdentStart2(ch) || isDigit(ch);
63705
+ }
63706
+ function isIdentifier(s) {
63707
+ if (!isIdentStart2(s[0])) return false;
63708
+ for (const ch of s) if (!isIdentChar2(ch)) return false;
63709
+ return true;
63710
+ }
63711
+ function isQuotedEmptyish(s) {
63712
+ const t = s.trim();
63713
+ return t.length >= 2 && (t[0] === "'" || t[0] === '"') && t[t.length - 1] === t[0] && !t.slice(1, -1).includes(t[0]);
63714
+ }
63715
+ function stripWrappers(expr) {
63716
+ let e = expr.trim();
63717
+ for (let guard = 0; guard < 8; guard++) {
63718
+ const before = e;
63719
+ if (e.endsWith(";")) e = e.slice(0, -1).trim();
63720
+ if (e.endsWith("!")) e = e.slice(0, -1).trim();
63721
+ const asAt = e.lastIndexOf(" as ");
63722
+ if (asAt > 0 && isIdentifier(e.slice(asAt + 4).trim())) e = e.slice(0, asAt).trim();
63723
+ for (const op of [" || ", " ?? "]) {
63724
+ const at = e.lastIndexOf(op);
63725
+ if (at > 0 && isQuotedEmptyish(e.slice(at + op.length))) e = e.slice(0, at).trim();
63726
+ }
63727
+ for (const m of PRESERVING_METHODS) if (e.endsWith(m)) e = e.slice(0, -m.length).trim();
63728
+ if (e.startsWith("String(") && e.endsWith(")")) e = e.slice("String(".length, -1).trim();
63729
+ if (e.startsWith("(") && e.endsWith(")") && balancedInner(e)) e = e.slice(1, -1).trim();
63730
+ if (e === before) break;
63731
+ }
63732
+ return e;
63733
+ }
63734
+ function balancedInner(e) {
63735
+ let depth = 0;
63736
+ for (let k = 0; k < e.length; k++) {
63737
+ if (e[k] === "(") depth++;
63738
+ else if (e[k] === ")") {
63739
+ depth--;
63740
+ if (depth === 0 && k !== e.length - 1) return false;
63741
+ }
63742
+ }
63743
+ return depth === 0;
63744
+ }
63745
+ function requestMemberBase(expr) {
63746
+ const e = stripWrappers(expr);
63747
+ const dot = e.indexOf(".");
63748
+ if (dot <= 0) return null;
63749
+ const base = e.slice(0, dot);
63750
+ if (!REQ_NAMES.has(base)) return null;
63751
+ let k = dot + 1;
63752
+ let part = "";
63753
+ while (isIdentChar2(e[k])) part += e[k++];
63754
+ if (!REQ_PARTS.has(part)) return null;
63755
+ let segments = 0;
63756
+ while (k < e.length) {
63757
+ if (e[k] === ".") {
63758
+ k++;
63759
+ const start2 = k;
63760
+ while (isIdentChar2(e[k])) k++;
63761
+ if (k === start2) return null;
63762
+ const seg = e.slice(start2, k);
63763
+ if (seg === "length") return null;
63764
+ segments++;
63765
+ } else if (e[k] === "[") {
63766
+ const q = e[k + 1];
63767
+ if (q !== "'" && q !== '"') return null;
63768
+ const close = e.indexOf(q, k + 2);
63769
+ if (close < 0 || e[close + 1] !== "]") return null;
63770
+ k = close + 2;
63771
+ segments++;
63772
+ } else return null;
63773
+ }
63774
+ if (segments === 0 && part !== "body") return null;
63775
+ return base;
63776
+ }
63777
+ function reachingDef(lk, variable, line) {
63778
+ for (const u of lk.dfg.uses) {
63779
+ if (u.variable !== variable || u.line !== line || u.def_id === null) continue;
63780
+ return lk.defsById.get(u.def_id) ?? null;
63781
+ }
63782
+ return null;
63783
+ }
63784
+ function isParamAt(lk, base, line) {
63785
+ const d = reachingDef(lk, base, line);
63786
+ return d !== null && d.kind === "param";
63787
+ }
63788
+ function destructuresName(pattern, name2) {
63789
+ for (const raw of pattern.split(",")) {
63790
+ let p = raw.trim();
63791
+ const eq = p.indexOf("=");
63792
+ if (eq >= 0) p = p.slice(0, eq).trim();
63793
+ const colon = p.indexOf(":");
63794
+ const bound = colon >= 0 ? p.slice(colon + 1).trim() : p;
63795
+ if (bound === name2) return true;
63796
+ }
63797
+ return false;
63798
+ }
63799
+ function isRequestValue(lk, expr, line, depth) {
63800
+ const e = stripWrappers(expr);
63801
+ const base = requestMemberBase(e);
63802
+ if (base) return isParamAt(lk, base, line);
63803
+ if (!isIdentifier(e) || depth <= 0) return false;
63804
+ const def = reachingDef(lk, e, line);
63805
+ if (!def || def.kind !== "local") return false;
63806
+ const text = (lk.lines[def.line - 1] ?? "").trim();
63807
+ const rhs = definitionRhs(text, e);
63808
+ if (rhs === null) return false;
63809
+ if (rhs.destructured) {
63810
+ const b = requestMemberBase(rhs.expr) ?? (REQ_NAMES.has(rhs.expr.split(".")[0]) ? partOnly(rhs.expr) : null);
63811
+ return b !== null && isParamAt(lk, b, def.line);
63812
+ }
63813
+ return isRequestValue(lk, rhs.expr, def.line, depth - 1);
63814
+ }
63815
+ function partOnly(expr) {
63816
+ const e = stripWrappers(expr);
63817
+ const dot = e.indexOf(".");
63818
+ if (dot <= 0) return null;
63819
+ const base = e.slice(0, dot);
63820
+ return REQ_NAMES.has(base) && REQ_PARTS.has(e.slice(dot + 1)) ? base : null;
63821
+ }
63822
+ function definitionRhs(text, name2) {
63823
+ let t = text;
63824
+ for (const kw of ["const ", "let ", "var "]) if (t.startsWith(kw)) {
63825
+ t = t.slice(kw.length).trim();
63826
+ break;
63827
+ }
63828
+ if (t.startsWith("{")) {
63829
+ const close = t.indexOf("}");
63830
+ if (close < 0) return null;
63831
+ if (!destructuresName(t.slice(1, close), name2)) return null;
63832
+ const rest2 = t.slice(close + 1).trim();
63833
+ if (!rest2.startsWith("=")) return null;
63834
+ return { expr: trimStatement(rest2.slice(1)), destructured: true };
63835
+ }
63836
+ if (!t.startsWith(name2)) return null;
63837
+ let rest = t.slice(name2.length);
63838
+ if (isIdentChar2(rest[0])) return null;
63839
+ rest = rest.trim();
63840
+ if (rest.startsWith(":")) {
63841
+ const eq = rest.indexOf("=");
63842
+ if (eq < 0) return null;
63843
+ rest = rest.slice(eq);
63844
+ }
63845
+ if (!rest.startsWith("=") || rest.startsWith("==") || rest.startsWith("=>")) return null;
63846
+ return { expr: trimStatement(rest.slice(1)), destructured: false };
63847
+ }
63848
+ function trimStatement(s) {
63849
+ let e = s.trim();
63850
+ if (e.endsWith(";")) e = e.slice(0, -1).trim();
63851
+ return e;
63852
+ }
63853
+ function regexOf(lk, text) {
63854
+ const t = text.trim();
63855
+ const direct = splitRegexLiteral(t);
63856
+ if (direct) return { ...direct, literal: t };
63857
+ if (!isIdentifier(t)) return null;
63858
+ const defs = lk.dfg.defs.filter((d) => d.variable === t);
63859
+ if (defs.length !== 1) return null;
63860
+ const line = (lk.lines[defs[0].line - 1] ?? "").trim();
63861
+ if (!line.startsWith("const ")) return null;
63862
+ const rhs = definitionRhs(line, t);
63863
+ if (!rhs || rhs.destructured) return null;
63864
+ const lit = splitRegexLiteral(rhs.expr);
63865
+ return lit ? { ...lit, literal: rhs.expr } : null;
63866
+ }
63867
+ var RECEIVER_REGEX_METHODS = /* @__PURE__ */ new Set(["test", "exec"]);
63868
+ var STRING_REGEX_METHODS = /* @__PURE__ */ new Set(["match", "matchAll", "search", "replace", "replaceAll", "split"]);
63869
+ function regexApplication(call) {
63870
+ const receiver = (call.receiver ?? "").trim();
63871
+ if (!receiver) return null;
63872
+ const arg0 = call.arguments.find((a) => a.position === 0)?.expression?.trim();
63873
+ if (!arg0) return null;
63874
+ if (RECEIVER_REGEX_METHODS.has(call.method_name)) return { regex: receiver, subject: arg0 };
63875
+ if (STRING_REGEX_METHODS.has(call.method_name)) return { regex: arg0, subject: receiver };
63876
+ return null;
63877
+ }
63878
+ var RedosRegexLiteralPass = class {
63879
+ name = "redos-regex-literal";
63880
+ category = "security";
63881
+ run(ctx) {
63882
+ const { graph, language, code } = ctx;
63883
+ const findings = [];
63884
+ if (language !== "javascript" && language !== "typescript") return { findings };
63885
+ const dfg = graph.ir.dfg;
63886
+ if (!dfg) return { findings };
63887
+ const lk = { dfg, lines: code.split("\n"), defsById: new Map(dfg.defs.map((d) => [d.id, d])) };
63888
+ const file = graph.ir.meta.file;
63889
+ const seen = /* @__PURE__ */ new Set();
63890
+ for (const call of graph.ir.calls) {
63891
+ const app = regexApplication(call);
63892
+ if (!app) continue;
63893
+ const line = call.location.line;
63894
+ if (seen.has(line)) continue;
63895
+ const re = regexOf(lk, app.regex);
63896
+ if (!re || !isExponentialRegex(re.source, re.flags)) continue;
63897
+ if (!isRequestValue(lk, app.subject, line, 3)) continue;
63898
+ seen.add(line);
63899
+ findings.push({ line, regex: re.literal, subject: app.subject });
63900
+ ctx.addFinding({
63901
+ id: `${this.name}-${file}-${line}`,
63902
+ pass: this.name,
63903
+ category: this.category,
63904
+ rule_id: this.name,
63905
+ cwe: "CWE-1333",
63906
+ severity: "medium",
63907
+ level: "warning",
63908
+ message: `Request value \`${app.subject}\` is matched against \`${re.literal}\`, a regex with a repeated group whose body can repeat on its own. A crafted input that almost matches makes the engine try exponentially many splits and blocks the event loop.`,
63909
+ file,
63910
+ line,
63911
+ fix: "Rewrite the pattern so each input character has one way to match: drop the outer repetition (`^[a-z0-9]+$` rather than `^([a-z0-9]+)*$`), or make the repeated body start with a required separator (`^\\w+(\\s\\w+)*$`). Bounding the input length limits but does not remove the cost.",
63912
+ evidence: { regex: re.literal, subject: app.subject, language }
63913
+ });
63914
+ }
63915
+ return { findings };
63916
+ }
63917
+ };
63918
+
63919
+ // src/analysis/passes/hardcoded-secret-argument-pass.ts
63920
+ var CRYPTO = ["crypto", "node:crypto"];
63921
+ var MYSQL = ["mysql", "mysql2", "mysql2/promise"];
63922
+ var RULES = [
63923
+ { packages: ["jsonwebtoken"], name: "sign", form: "member", positions: [{ kind: "arg", index: 1 }], label: "jwt.sign signing key" },
63924
+ { packages: ["jsonwebtoken"], name: "verify", form: "member", positions: [{ kind: "arg", index: 1 }], label: "jwt.verify key" },
63925
+ { packages: CRYPTO, name: "createHmac", form: "member", positions: [{ kind: "arg", index: 1 }], label: "HMAC key" },
63926
+ { packages: CRYPTO, name: "createHmac", form: "bare", positions: [{ kind: "arg", index: 1 }], label: "HMAC key" },
63927
+ { packages: CRYPTO, name: "createCipheriv", form: "member", positions: [{ kind: "arg", index: 1 }], label: "cipher key" },
63928
+ { packages: CRYPTO, name: "createCipheriv", form: "bare", positions: [{ kind: "arg", index: 1 }], label: "cipher key" },
63929
+ { packages: CRYPTO, name: "createDecipheriv", form: "member", positions: [{ kind: "arg", index: 1 }], label: "cipher key" },
63930
+ { packages: CRYPTO, name: "createDecipheriv", form: "bare", positions: [{ kind: "arg", index: 1 }], label: "cipher key" },
63931
+ { packages: ["express-session"], name: "*", form: "bare", positions: [{ kind: "prop", index: 0, path: ["secret"], arrays: true }], label: "session secret" },
63932
+ {
63933
+ packages: ["cookie-session"],
63934
+ name: "*",
63935
+ form: "bare",
63936
+ positions: [{ kind: "prop", index: 0, path: ["secret"] }, { kind: "prop", index: 0, path: ["keys"], arrays: true }],
63937
+ label: "cookie-session key"
63938
+ },
63939
+ { packages: ["cookie-parser"], name: "*", form: "bare", positions: [{ kind: "arg", index: 0, arrays: true }], label: "cookie-parser secret" },
63940
+ { packages: ["express-jwt"], name: "*", form: "bare", positions: [{ kind: "prop", index: 0, path: ["secret"] }], label: "express-jwt secret" },
63941
+ { packages: ["passport-jwt"], name: "JwtStrategy", form: "bare", nameFallback: true, positions: [{ kind: "prop", index: 0, path: ["secretOrKey"] }], label: "passport-jwt secretOrKey" },
63942
+ { packages: ["passport-jwt"], name: "Strategy", form: "bare", positions: [{ kind: "prop", index: 0, path: ["secretOrKey"] }], label: "passport-jwt secretOrKey" },
63943
+ { packages: MYSQL, name: "createConnection", form: "member", positions: [{ kind: "prop", index: 0, path: ["password"] }], label: "database password" },
63944
+ { packages: MYSQL, name: "createPool", form: "member", positions: [{ kind: "prop", index: 0, path: ["password"] }], label: "database password" },
63945
+ { packages: ["pg"], name: "Pool", form: "bare", positions: [{ kind: "prop", index: 0, path: ["password"] }], label: "database password" },
63946
+ { packages: ["pg"], name: "Client", form: "bare", positions: [{ kind: "prop", index: 0, path: ["password"] }], label: "database password" },
63947
+ { packages: ["pg"], name: "Pool", form: "member", positions: [{ kind: "prop", index: 0, path: ["password"] }], label: "database password" },
63948
+ { packages: ["pg"], name: "Client", form: "member", positions: [{ kind: "prop", index: 0, path: ["password"] }], label: "database password" },
63949
+ { packages: ["sequelize"], name: "Sequelize", form: "bare", positions: [{ kind: "arg", index: 2 }], label: "database password" },
63950
+ { packages: ["nodemailer"], name: "createTransport", form: "member", positions: [{ kind: "prop", index: 0, path: ["auth", "pass"] }], label: "SMTP password" }
63951
+ ];
63952
+ function bindings(imports) {
63953
+ const m = /* @__PURE__ */ new Map();
63954
+ for (const imp of imports) {
63955
+ if (!imp.from_package) continue;
63956
+ const local = imp.alias ?? (imp.imported_name !== "default" && imp.imported_name !== "*" ? imp.imported_name : null);
63957
+ if (local) m.set(local, imp.from_package);
63958
+ }
63959
+ return m;
63960
+ }
63961
+ function importsName(imports, local) {
63962
+ return imports.find((i2) => (i2.alias ?? i2.imported_name) === local && i2.from_package != null);
63963
+ }
63964
+ function skipString2(s, i2) {
63965
+ const q = s[i2];
63966
+ for (let j = i2 + 1; j < s.length; j++) {
63967
+ if (s[j] === "\\") {
63968
+ j++;
63969
+ continue;
63970
+ }
63971
+ if (s[j] === q) return j + 1;
63972
+ }
63973
+ return -1;
63974
+ }
63975
+ function splitTopLevel2(s, sep) {
63976
+ const out2 = [];
63977
+ let depth = 0;
63978
+ let start2 = 0;
63979
+ for (let i2 = 0; i2 < s.length; i2++) {
63980
+ const ch = s[i2];
63981
+ if (ch === '"' || ch === "'" || ch === "`") {
63982
+ const end = skipString2(s, i2);
63983
+ if (end < 0) return null;
63984
+ i2 = end - 1;
63985
+ continue;
63986
+ }
63987
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
63988
+ else if (ch === ")" || ch === "]" || ch === "}") {
63989
+ depth--;
63990
+ if (depth < 0) return null;
63991
+ } else if (ch === sep && depth === 0) {
63992
+ out2.push(s.slice(start2, i2));
63993
+ start2 = i2 + 1;
63994
+ }
63995
+ }
63996
+ if (depth !== 0) return null;
63997
+ out2.push(s.slice(start2));
63998
+ return out2;
63999
+ }
64000
+ function stringLiteralValue(expr) {
64001
+ const e = expr.trim();
64002
+ if (e.length < 2) return null;
64003
+ const q = e[0];
64004
+ if (q !== '"' && q !== "'" && q !== "`" || e[e.length - 1] !== q) return null;
64005
+ if (skipString2(e, 0) !== e.length) return null;
64006
+ const body2 = e.slice(1, -1);
64007
+ if (q === "`" && body2.includes("${")) return null;
64008
+ return body2;
64009
+ }
64010
+ function literalValues(expr, arrays) {
64011
+ const one = stringLiteralValue(expr);
64012
+ if (one !== null) return [one];
64013
+ if (!arrays) return null;
64014
+ const e = expr.trim();
64015
+ if (!e.startsWith("[") || !e.endsWith("]")) return null;
64016
+ const parts2 = splitTopLevel2(e.slice(1, -1), ",");
64017
+ if (!parts2) return null;
64018
+ const vals = [];
64019
+ for (const p of parts2) {
64020
+ if (p.trim() === "") continue;
64021
+ const v = stringLiteralValue(p);
64022
+ if (v === null) return null;
64023
+ vals.push(v);
64024
+ }
64025
+ return vals.length > 0 ? vals : null;
64026
+ }
64027
+ function propertyValue(expr, path) {
64028
+ let cur = expr.trim();
64029
+ for (const key of path) {
64030
+ if (!cur.startsWith("{") || !cur.endsWith("}")) return null;
64031
+ const entries = splitTopLevel2(cur.slice(1, -1), ",");
64032
+ if (!entries) return null;
64033
+ let found = null;
64034
+ for (const entry of entries) {
64035
+ const colon = topLevelColon2(entry);
64036
+ if (colon < 0) continue;
64037
+ let k = (entry.slice(0, colon).split("\n").pop() ?? "").trim();
64038
+ const kq = stringLiteralValue(k);
64039
+ if (kq !== null) k = kq;
64040
+ if (k === key) found = entry.slice(colon + 1).trim();
64041
+ }
64042
+ if (found === null) return null;
64043
+ cur = found;
64044
+ }
64045
+ return cur;
64046
+ }
64047
+ function topLevelColon2(entry) {
64048
+ let depth = 0;
64049
+ for (let i2 = 0; i2 < entry.length; i2++) {
64050
+ const ch = entry[i2];
64051
+ if (ch === '"' || ch === "'" || ch === "`") {
64052
+ const end = skipString2(entry, i2);
64053
+ if (end < 0) return -1;
64054
+ i2 = end - 1;
64055
+ continue;
64056
+ }
64057
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
64058
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
64059
+ else if (ch === ":" && depth === 0) return i2;
64060
+ }
64061
+ return -1;
64062
+ }
64063
+ var SLOT_NAMES = /* @__PURE__ */ new Set(["password", "passwd", "pass", "secret", "key", "username", "user", "token"]);
64064
+ function isRealSecret(v) {
64065
+ if (v.trim() === "") return false;
64066
+ if (PLACEHOLDER_RE.test(v)) return false;
64067
+ if (SLOT_NAMES.has(v.trim().toLowerCase())) return false;
64068
+ return true;
64069
+ }
64070
+ function isSqliteSequelize(call) {
64071
+ const opts = call.arguments.find((a) => a.position === 3)?.expression;
64072
+ if (!opts) return false;
64073
+ const dialect = propertyValue(opts, ["dialect"]);
64074
+ return dialect !== null && stringLiteralValue(dialect) === "sqlite";
64075
+ }
64076
+ function matchRule(call, imports) {
64077
+ const binds = bindings(imports);
64078
+ const receiver = (call.receiver ?? "").trim();
64079
+ for (const rule of RULES) {
64080
+ if (rule.form === "member") {
64081
+ if (!receiver || call.method_name !== rule.name) continue;
64082
+ const root = receiver.split(".")[0];
64083
+ const pkg = binds.get(root);
64084
+ if (pkg && rule.packages.includes(pkg)) return rule;
64085
+ continue;
64086
+ }
64087
+ if (receiver) continue;
64088
+ const imp = importsName(imports, call.method_name);
64089
+ if (imp && imp.from_package && rule.packages.includes(imp.from_package)) {
64090
+ if (rule.name === "*") return rule;
64091
+ if (call.method_name === rule.name || imp.imported_name === rule.name) return rule;
64092
+ continue;
64093
+ }
64094
+ if (!imp && rule.nameFallback && call.method_name === rule.name) return rule;
64095
+ }
64096
+ return null;
64097
+ }
64098
+ var HardcodedSecretArgumentPass = class {
64099
+ name = "hardcoded-secret-argument";
64100
+ category = "security";
64101
+ run(ctx) {
64102
+ const { graph, language } = ctx;
64103
+ const findings = [];
64104
+ if (language !== "javascript" && language !== "typescript") return { findings };
64105
+ const file = graph.ir.meta.file;
64106
+ if (isTestFile(file) || isGeneratedFile(file)) return { findings };
64107
+ const imports = graph.ir.imports ?? [];
64108
+ if (imports.length === 0 && !ctx.code.includes("JwtStrategy")) return { findings };
64109
+ const seen = /* @__PURE__ */ new Set();
64110
+ for (const f of ctx.getFindings?.() ?? []) {
64111
+ if (f.file === file && (f.rule_id === "hardcoded-credential" || f.rule_id === "hardcoded-credential-entropy")) seen.add(f.line);
64112
+ }
64113
+ const lineStarts = [0];
64114
+ for (let i2 = 0; i2 < ctx.code.length; i2++) if (ctx.code[i2] === "\n") lineStarts.push(i2 + 1);
64115
+ const lineAt = (offset) => {
64116
+ let lo = 0, hi = lineStarts.length - 1;
64117
+ while (lo < hi) {
64118
+ const mid = lo + hi + 1 >> 1;
64119
+ if (lineStarts[mid] <= offset) lo = mid;
64120
+ else hi = mid - 1;
64121
+ }
64122
+ return lo + 1;
64123
+ };
64124
+ for (const call of graph.ir.calls) {
64125
+ const rule = matchRule(call, imports);
64126
+ if (!rule) continue;
64127
+ if (rule.name === "Sequelize" && isSqliteSequelize(call)) continue;
64128
+ for (const pos of rule.positions) {
64129
+ const arg = call.arguments.find((a) => a.position === pos.index);
64130
+ if (!arg || !arg.expression) continue;
64131
+ const valueText = pos.kind === "arg" ? arg.expression : propertyValue(arg.expression, pos.path);
64132
+ if (valueText === null) continue;
64133
+ const vals = literalValues(valueText, pos.arrays === true);
64134
+ if (!vals || !vals.some(isRealSecret)) continue;
64135
+ let line = call.location.line;
64136
+ const from = lineStarts[Math.max(0, call.location.line - 1)] ?? 0;
64137
+ const argAt = ctx.code.indexOf(arg.expression, from);
64138
+ if (argAt >= 0) {
64139
+ const inArg = pos.kind === "arg" ? 0 : arg.expression.lastIndexOf(valueText);
64140
+ if (inArg >= 0) line = lineAt(argAt + inArg);
64141
+ }
64142
+ if (seen.has(line)) continue;
64143
+ seen.add(line);
64144
+ const api = call.receiver ? `${call.receiver}.${call.method_name}` : call.method_name;
64145
+ findings.push({ line, api, label: rule.label });
64146
+ ctx.addFinding({
64147
+ id: `hardcoded-credential-${file}-${line}`,
64148
+ pass: this.name,
64149
+ category: this.category,
64150
+ rule_id: "hardcoded-credential",
64151
+ cwe: "CWE-798",
64152
+ severity: "high",
64153
+ level: "error",
64154
+ message: `Hardcoded credential: a string literal is passed as the ${rule.label} of \`${api}\`. Anyone who can read the source can sign, decrypt or log in with it.`,
64155
+ file,
64156
+ line,
64157
+ fix: "Load the secret from the environment or a secrets manager (for example `process.env.JWT_SECRET`), and rotate the exposed value.",
64158
+ evidence: { kind: "secret-argument", api, position: rule.label, language }
64159
+ });
64160
+ }
64161
+ }
64162
+ return { findings };
64163
+ }
64164
+ };
64165
+
64166
+ // src/analysis/passes/missing-auth-middleware-pass.ts
64167
+ var ROUTE_METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete", "all"]);
64168
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
64169
+ var AUTHN_NAMES = /* @__PURE__ */ new Set([
64170
+ "auth",
64171
+ "authenticate",
64172
+ "authenticated",
64173
+ "isauthenticated",
64174
+ "ensureauthenticated",
64175
+ "ensureauth",
64176
+ "ensureloggedin",
64177
+ "isloggedin",
64178
+ "loggedin",
64179
+ "requireauth",
64180
+ "requireauthentication",
64181
+ "requirelogin",
64182
+ "requireslogin",
64183
+ "mustbeloggedin",
64184
+ "requireuser",
64185
+ "requiresuser",
64186
+ "authmiddleware",
64187
+ "authrequired",
64188
+ "loginrequired",
64189
+ "verifytoken",
64190
+ "verifyjwt",
64191
+ "checkjwt",
64192
+ "jwt",
64193
+ "expressjwt",
64194
+ "jwtauth",
64195
+ "checkauth",
64196
+ "protect",
64197
+ "authguard",
64198
+ "requiresession",
64199
+ "withauth",
64200
+ "needsauth",
64201
+ "isauth",
64202
+ "isuser"
64203
+ ]);
64204
+ var AUTHZ_NAMES = /* @__PURE__ */ new Set([
64205
+ "authorize",
64206
+ "authorized",
64207
+ "isauthorized",
64208
+ "isadmin",
64209
+ "requireadmin",
64210
+ "adminonly",
64211
+ "ensureadmin",
64212
+ "hasrole",
64213
+ "requirerole",
64214
+ "checkrole",
64215
+ "restrictto",
64216
+ "permit",
64217
+ "haspermission",
64218
+ "requirepermission",
64219
+ "checkpermission",
64220
+ "denyall",
64221
+ "isowner",
64222
+ "requireowner",
64223
+ "checkowner"
64224
+ ]);
64225
+ function isIdentChar3(ch) {
64226
+ return ch !== void 0 && (ch === "_" || ch === "$" || ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9");
64227
+ }
64228
+ function isIdentifier2(s) {
64229
+ if (s.length === 0 || s[0] >= "0" && s[0] <= "9") return false;
64230
+ for (const ch of s) if (!isIdentChar3(ch)) return false;
64231
+ return true;
64232
+ }
64233
+ function middlewareName(expr) {
64234
+ let e = expr.trim();
64235
+ const paren = e.indexOf("(");
64236
+ if (paren >= 0) {
64237
+ if (!e.endsWith(")")) return null;
64238
+ e = e.slice(0, paren).trim();
64239
+ }
64240
+ const segs = e.split(".");
64241
+ for (const s of segs) if (!isIdentifier2(s.trim())) return null;
64242
+ return segs[segs.length - 1].trim();
64243
+ }
64244
+ function norm(name2) {
64245
+ let out2 = "";
64246
+ for (const ch of name2) if (ch !== "_" && ch !== "-" && ch !== "$") out2 += ch.toLowerCase();
64247
+ return out2;
64248
+ }
64249
+ function guardKind(expr) {
64250
+ const name2 = middlewareName(expr);
64251
+ if (!name2) return null;
64252
+ const n = norm(name2);
64253
+ if (AUTHN_NAMES.has(n)) return "authn";
64254
+ if (AUTHZ_NAMES.has(n)) return "authz";
64255
+ return null;
64256
+ }
64257
+ function stringLiteral2(expr) {
64258
+ const e = (expr ?? "").trim();
64259
+ if (e.length < 2) return null;
64260
+ const q = e[0];
64261
+ if (q !== "'" && q !== '"' && q !== "`" || e[e.length - 1] !== q) return null;
64262
+ const body2 = e.slice(1, -1);
64263
+ if (body2.includes(q) || body2.includes("\\") || q === "`" && body2.includes("${")) return null;
64264
+ return body2;
64265
+ }
64266
+ function resourceOf(path) {
64267
+ for (const raw of path.split("/")) {
64268
+ const s = raw.trim().toLowerCase();
64269
+ if (s === "" || s.startsWith(":") || s === "*") continue;
64270
+ if (s === "api") continue;
64271
+ if (s.length >= 2 && s[0] === "v" && [...s.slice(1)].every((c) => c >= "0" && c <= "9")) continue;
64272
+ return s;
64273
+ }
64274
+ return "";
64275
+ }
64276
+ function hasParamSegment(path) {
64277
+ return path.split("/").some((s) => s.startsWith(":") && s.length > 1);
64278
+ }
64279
+ var SELF_CHECK_MARKERS = [
64280
+ "req.user",
64281
+ "req.session",
64282
+ "req.auth",
64283
+ "request.user",
64284
+ "request.session",
64285
+ "res.locals.user",
64286
+ "isAuthenticated(",
64287
+ "status(401)",
64288
+ "status(403)",
64289
+ "sendStatus(401)",
64290
+ "sendStatus(403)"
64291
+ ];
64292
+ function checksCallerItself(text) {
64293
+ return SELF_CHECK_MARKERS.some((m) => text.includes(m));
64294
+ }
64295
+ function sameFileFunctionText(lines, name2) {
64296
+ for (let i2 = 0; i2 < lines.length; i2++) {
64297
+ const t = lines[i2].trimStart();
64298
+ const isDecl = t.startsWith(`function ${name2}(`) || t.startsWith(`async function ${name2}(`) || t.startsWith(`export function ${name2}(`) || t.startsWith(`export async function ${name2}(`) || t.startsWith(`const ${name2} =`) || t.startsWith(`export const ${name2} =`);
64299
+ if (!isDecl) continue;
64300
+ const out2 = [];
64301
+ for (let j = i2; j < lines.length && j < i2 + 200; j++) {
64302
+ out2.push(lines[j]);
64303
+ if (j > i2 && lines[j].startsWith("}")) break;
64304
+ if (j === i2 && lines[j].trimEnd().endsWith(";") && !lines[j].includes("{")) break;
64305
+ }
64306
+ return out2.join("\n");
64307
+ }
64308
+ return null;
64309
+ }
64310
+ function routeOf(call) {
64311
+ if (!ROUTE_METHODS.has(call.method_name)) return null;
64312
+ const receiver = (call.receiver ?? "").trim();
64313
+ if (!isIdentifier2(receiver)) return null;
64314
+ const args2 = [...call.arguments].sort((a, b) => a.position - b.position);
64315
+ if (args2.length < 2) return null;
64316
+ const path = stringLiteral2(args2[0].expression);
64317
+ if (path === null || !path.startsWith("/")) return null;
64318
+ let guard = null;
64319
+ const exprs = [];
64320
+ for (const a of args2.slice(1)) {
64321
+ const e = (a.expression ?? "").trim();
64322
+ if (e.startsWith("[") && e.endsWith("]")) exprs.push(...e.slice(1, -1).split(","));
64323
+ else exprs.push(e);
64324
+ }
64325
+ for (const e of exprs) {
64326
+ const k = guardKind(e);
64327
+ if (k === "authn") {
64328
+ guard = "authn";
64329
+ break;
64330
+ }
64331
+ if (k === "authz") guard = "authz";
64332
+ }
64333
+ return {
64334
+ call,
64335
+ receiver,
64336
+ method: call.method_name,
64337
+ path,
64338
+ resource: resourceOf(path),
64339
+ guard,
64340
+ handler: (args2[args2.length - 1].expression ?? "").trim(),
64341
+ middlewareCount: args2.length - 2
64342
+ };
64343
+ }
64344
+ var MissingAuthMiddlewarePass = class {
64345
+ name = "missing-auth-middleware";
64346
+ category = "security";
64347
+ run(ctx) {
64348
+ const { graph, language, code } = ctx;
64349
+ const findings = [];
64350
+ if (language !== "javascript" && language !== "typescript") return { findings };
64351
+ const calls = graph.ir.calls;
64352
+ for (const c of calls) {
64353
+ if (c.method_name !== "use") continue;
64354
+ if (c.arguments.some((a) => guardKind(a.expression ?? "") !== null)) return { findings };
64355
+ }
64356
+ const routes = calls.map(routeOf).filter((r) => r !== null);
64357
+ if (routes.length < 2) return { findings };
64358
+ const lines = code.split("\n");
64359
+ const file = graph.ir.meta.file;
64360
+ const seen = /* @__PURE__ */ new Set();
64361
+ for (const r of routes) {
64362
+ if (r.guard !== null || r.middlewareCount > 0) continue;
64363
+ if (!MUTATING_METHODS.has(r.method) || !hasParamSegment(r.path) || r.resource === "") continue;
64364
+ const sibling = routes.find((s) => s !== r && s.receiver === r.receiver && s.resource === r.resource && s.guard === "authn");
64365
+ if (!sibling) continue;
64366
+ const handlerText = isIdentifier2(r.handler) ? sameFileFunctionText(lines, r.handler) ?? "" : r.handler;
64367
+ if (checksCallerItself(handlerText)) continue;
64368
+ const line = r.call.location.line;
64369
+ if (seen.has(line)) continue;
64370
+ seen.add(line);
64371
+ const route = `${r.method.toUpperCase()} ${r.path}`;
64372
+ const siblingRoute = `${sibling.method.toUpperCase()} ${sibling.path}`;
64373
+ findings.push({ line, route, guardedBy: siblingRoute });
64374
+ ctx.addFinding({
64375
+ id: `${this.name}-${file}-${line}`,
64376
+ pass: this.name,
64377
+ category: this.category,
64378
+ rule_id: this.name,
64379
+ cwe: "CWE-862",
64380
+ severity: "high",
64381
+ level: "error",
64382
+ message: `\`${r.receiver}.${r.method}('${r.path}')\` changes a record addressed by a path parameter with no authentication middleware, while \`${siblingRoute}\` on the same router requires one. Anyone can call this route.`,
64383
+ file,
64384
+ line,
64385
+ fix: `Add the same authentication middleware as \`${siblingRoute}\` to this route (and check that the caller may change this record), or guard the whole router with \`router.use(...)\`.`,
64386
+ evidence: { route, guardedSibling: siblingRoute, receiver: r.receiver, language }
64387
+ });
64388
+ }
64389
+ return { findings };
64390
+ }
64391
+ };
64392
+
64393
+ // src/analysis/passes/prototype-pollution-pass.ts
64394
+ var KEYWORDS2 = /* @__PURE__ */ new Set([
64395
+ "if",
64396
+ "for",
64397
+ "while",
64398
+ "switch",
64399
+ "catch",
64400
+ "with",
64401
+ "return",
64402
+ "typeof",
64403
+ "function",
64404
+ "new",
64405
+ "await",
64406
+ "yield",
64407
+ "delete",
64408
+ "void",
64409
+ "in",
64410
+ "of",
64411
+ "do",
64412
+ "else",
64413
+ "try",
64414
+ "finally",
64415
+ "throw",
64416
+ "case",
64417
+ "super"
64418
+ ]);
64419
+ var PATH_NAME_WORDS = ["path", "keys", "segments", "segs", "parts", "props", "keypath", "fields"];
64420
+ var GUARD_NAME_WORDS = [
64421
+ "safe",
64422
+ "proto",
64423
+ "pollut",
64424
+ "forbid",
64425
+ "unsafe",
64426
+ "danger",
64427
+ "block",
64428
+ "allow",
64429
+ "reserved",
64430
+ "valid",
64431
+ "deny",
64432
+ "illegal"
64433
+ ];
64434
+ var REQUEST_ROOTS = /* @__PURE__ */ new Set(["req", "request"]);
64435
+ var REQUEST_BAGS = /* @__PURE__ */ new Set(["body", "query", "params"]);
64436
+ var MAX_CODE_LENGTH = 1e6;
64437
+ function isIdentStart3(ch) {
64438
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_" || ch === "$";
64439
+ }
64440
+ function isIdentChar4(ch) {
64441
+ return isIdentStart3(ch) || ch >= "0" && ch <= "9";
64442
+ }
64443
+ function isIdent(t) {
64444
+ return !!t && isIdentStart3(t[0]) && !KEYWORDS2.has(t);
64445
+ }
64446
+ function maskLiterals(code) {
64447
+ const out2 = code.split("");
64448
+ let i2 = 0;
64449
+ const n = code.length;
64450
+ while (i2 < n) {
64451
+ const ch = code[i2];
64452
+ if (ch === "/" && code[i2 + 1] === "/") {
64453
+ while (i2 < n && code[i2] !== "\n") out2[i2++] = " ";
64454
+ continue;
64455
+ }
64456
+ if (ch === "/" && code[i2 + 1] === "*") {
64457
+ out2[i2] = " ";
64458
+ out2[i2 + 1] = " ";
64459
+ i2 += 2;
64460
+ while (i2 < n && !(code[i2] === "*" && code[i2 + 1] === "/")) {
64461
+ if (code[i2] !== "\n") out2[i2] = " ";
64462
+ i2++;
64463
+ }
64464
+ if (i2 < n) {
64465
+ out2[i2] = " ";
64466
+ out2[i2 + 1] = " ";
64467
+ i2 += 2;
64468
+ }
64469
+ continue;
64470
+ }
64471
+ if (ch === '"' || ch === "'" || ch === "`") {
64472
+ i2++;
64473
+ while (i2 < n && code[i2] !== ch) {
64474
+ if (code[i2] === "\n" && ch !== "`") break;
64475
+ if (code[i2] === "\\") {
64476
+ out2[i2] = " ";
64477
+ i2++;
64478
+ if (i2 < n && code[i2] !== "\n") out2[i2] = " ";
64479
+ i2++;
64480
+ continue;
64481
+ }
64482
+ if (code[i2] !== "\n") out2[i2] = " ";
64483
+ i2++;
64484
+ }
64485
+ i2++;
64486
+ continue;
64487
+ }
64488
+ i2++;
64489
+ }
64490
+ return out2.join("");
64491
+ }
64492
+ var PUNCT3 = ["===", "!==", "??=", "||=", "&&=", "..."];
64493
+ var PUNCT2 = ["==", "!=", "=>", "||", "&&", "??", "<=", ">=", "+=", "-=", "?.", "++", "--"];
64494
+ function tokenize(masked) {
64495
+ const toks = [];
64496
+ let i2 = 0;
64497
+ const n = masked.length;
64498
+ while (i2 < n) {
64499
+ const ch = masked[i2];
64500
+ if (ch === " " || ch === "\n" || ch === " " || ch === "\r") {
64501
+ i2++;
64502
+ continue;
64503
+ }
64504
+ if (isIdentStart3(ch)) {
64505
+ const s = i2;
64506
+ while (i2 < n && isIdentChar4(masked[i2])) i2++;
64507
+ toks.push({ t: masked.slice(s, i2), pos: s, m: -1 });
64508
+ continue;
64509
+ }
64510
+ if (ch >= "0" && ch <= "9") {
64511
+ const s = i2;
64512
+ while (i2 < n && (isIdentChar4(masked[i2]) || masked[i2] === ".")) i2++;
64513
+ toks.push({ t: masked.slice(s, i2), pos: s, m: -1 });
64514
+ continue;
64515
+ }
64516
+ if (ch === '"' || ch === "'" || ch === "`") {
64517
+ const s = i2;
64518
+ i2++;
64519
+ while (i2 < n && masked[i2] !== ch && masked[i2] !== "\n") i2++;
64520
+ i2++;
64521
+ toks.push({ t: '"', pos: s, m: -1 });
64522
+ continue;
64523
+ }
64524
+ const three = masked.slice(i2, i2 + 3);
64525
+ if (PUNCT3.includes(three)) {
64526
+ toks.push({ t: three, pos: i2, m: -1 });
64527
+ i2 += 3;
64528
+ continue;
64529
+ }
64530
+ const two = masked.slice(i2, i2 + 2);
64531
+ if (PUNCT2.includes(two)) {
64532
+ toks.push({ t: two, pos: i2, m: -1 });
64533
+ i2 += 2;
64534
+ continue;
64535
+ }
64536
+ toks.push({ t: ch, pos: i2, m: -1 });
64537
+ i2++;
64538
+ }
64539
+ const stack = [];
64540
+ for (let j = 0; j < toks.length; j++) {
64541
+ const t = toks[j].t;
64542
+ if (t === "(" || t === "[" || t === "{") stack.push(j);
64543
+ else if (t === ")" || t === "]" || t === "}") {
64544
+ const want = t === ")" ? "(" : t === "]" ? "[" : "{";
64545
+ while (stack.length > 0 && toks[stack[stack.length - 1]].t !== want) stack.pop();
64546
+ const o = stack.pop();
64547
+ if (o !== void 0) {
64548
+ toks[o].m = j;
64549
+ toks[j].m = o;
64550
+ }
64551
+ }
64552
+ }
64553
+ return toks;
64554
+ }
64555
+ function matchClose(toks, i2) {
64556
+ return toks[i2]?.m ?? -1;
64557
+ }
64558
+ function matchOpen(toks, i2) {
64559
+ return toks[i2]?.m ?? -1;
64560
+ }
64561
+ function paramNames(toks, open, close) {
64562
+ const out2 = [];
64563
+ let depth = 0;
64564
+ let expectName = true;
64565
+ for (let j = open + 1; j < close; j++) {
64566
+ const t = toks[j].t;
64567
+ if (t === "(" || t === "[" || t === "{") depth++;
64568
+ else if (t === ")" || t === "]" || t === "}") depth--;
64569
+ else if (depth === 0 && t === ",") {
64570
+ expectName = true;
64571
+ continue;
64572
+ }
64573
+ if (depth === 0 && expectName && isIdent(t) && t !== "this") {
64574
+ out2.push(t);
64575
+ expectName = false;
64576
+ } else if (depth === 0 && t !== "...") expectName = false;
64577
+ }
64578
+ return out2;
64579
+ }
64580
+ function boundName(toks, start2) {
64581
+ let k = start2 - 1;
64582
+ if (toks[k]?.t === "async") k--;
64583
+ if (toks[k]?.t === "=" || toks[k]?.t === ":") return isIdent(toks[k - 1]?.t) ? toks[k - 1].t : null;
64584
+ return null;
64585
+ }
64586
+ function findFunctions(toks) {
64587
+ const fns = [];
64588
+ for (let i2 = 0; i2 < toks.length; i2++) {
64589
+ if (toks[i2].t !== "{") continue;
64590
+ const prev = toks[i2 - 1]?.t;
64591
+ let fn = null;
64592
+ if (prev === "=>") {
64593
+ const close = matchClose(toks, i2);
64594
+ if (close < 0) continue;
64595
+ let start2 = i2 - 2;
64596
+ let params = [];
64597
+ if (toks[start2]?.t === ")") {
64598
+ const po = matchOpen(toks, start2);
64599
+ if (po < 0) continue;
64600
+ params = paramNames(toks, po, start2);
64601
+ start2 = po;
64602
+ } else if (isIdent(toks[start2]?.t)) {
64603
+ params = [toks[start2].t];
64604
+ }
64605
+ fn = { name: boundName(toks, start2), open: i2, close, params };
64606
+ } else if (prev === ")") {
64607
+ const pc = i2 - 1;
64608
+ const po = matchOpen(toks, pc);
64609
+ if (po < 1) continue;
64610
+ const before = toks[po - 1].t;
64611
+ const close = matchClose(toks, i2);
64612
+ if (close < 0) continue;
64613
+ const params = paramNames(toks, po, pc);
64614
+ if (before === "function") {
64615
+ fn = { name: boundName(toks, po - 1), open: i2, close, params };
64616
+ } else if (isIdent(before)) {
64617
+ const kw = toks[po - 2]?.t;
64618
+ if (kw === "function") fn = { name: before, open: i2, close, params };
64619
+ else if (kw !== "." && kw !== "new") fn = { name: before, open: i2, close, params };
64620
+ }
64621
+ }
64622
+ if (!fn && prev !== void 0 && prev !== "=>" && prev !== ")") {
64623
+ for (let j = i2 - 1; j > Math.max(0, i2 - 16); j--) {
64624
+ if (toks[j].t === ":" && toks[j - 1]?.t === ")") {
64625
+ const pc = j - 1;
64626
+ const po = matchOpen(toks, pc);
64627
+ if (po < 1) break;
64628
+ const before = toks[po - 1].t;
64629
+ const close = matchClose(toks, i2);
64630
+ if (close < 0) break;
64631
+ const params = paramNames(toks, po, pc);
64632
+ if (before === "function") fn = { name: boundName(toks, po - 1), open: i2, close, params };
64633
+ else if (isIdent(before) && toks[po - 2]?.t !== ".") fn = { name: before, open: i2, close, params };
64634
+ break;
64635
+ }
64636
+ if (toks[j].t === "{" || toks[j].t === "}" || toks[j].t === ";") break;
64637
+ }
64638
+ }
64639
+ if (fn) fns.push(fn);
64640
+ }
64641
+ return fns;
64642
+ }
64643
+ function chainAt(toks, i2) {
64644
+ if (!isIdent(toks[i2]?.t) && toks[i2]?.t !== "this") return null;
64645
+ let text = toks[i2].t;
64646
+ let j = i2 + 1;
64647
+ while ((toks[j]?.t === "." || toks[j]?.t === "?.") && isIdent(toks[j + 1]?.t)) {
64648
+ text += "." + toks[j + 1].t;
64649
+ j += 2;
64650
+ }
64651
+ return { text, end: j };
64652
+ }
64653
+ function isAssign2(t) {
64654
+ return t === "=" || t === "||=" || t === "??=" || t === "&&=";
64655
+ }
64656
+ function lineOf(code, pos) {
64657
+ let line = 1;
64658
+ for (let i2 = code.lastIndexOf("\n", pos - 1); i2 >= 0; i2 = code.lastIndexOf("\n", i2 - 1)) line++;
64659
+ return line;
64660
+ }
64661
+ function hasGuard(raw, toks, from, to, keys) {
64662
+ if (raw.includes("__proto__") || raw.includes("constructor") || raw.includes("prototype")) return true;
64663
+ for (let j = from; j < to; j++) {
64664
+ const t = toks[j].t;
64665
+ if (!isIdent(t) || toks[j + 1]?.t !== "(") continue;
64666
+ const lower = t.toLowerCase();
64667
+ const membership = toks[j - 1]?.t === "." && (t === "has" || t === "includes" || t === "indexOf");
64668
+ if (!membership && !GUARD_NAME_WORDS.some((w) => lower.includes(w))) continue;
64669
+ const close = matchClose(toks, j + 1);
64670
+ for (let k = j + 2; k < close; k++) if (keys.has(toks[k].t)) return true;
64671
+ }
64672
+ return false;
64673
+ }
64674
+ function nullProtoNames(toks, from, to) {
64675
+ const out2 = /* @__PURE__ */ new Set();
64676
+ for (let j = from; j + 6 < to; j++) {
64677
+ if (toks[j + 1].t === "=" && isIdent(toks[j].t) && toks[j + 2].t === "Object" && toks[j + 3].t === "." && toks[j + 4].t === "create" && toks[j + 5].t === "(" && toks[j + 6].t === "null") out2.add(toks[j].t);
64678
+ }
64679
+ return out2;
64680
+ }
64681
+ function keyLoops(toks, from, to) {
64682
+ const out2 = [];
64683
+ for (let j = from; j < to; j++) {
64684
+ const t = toks[j].t;
64685
+ if (t === "for" && toks[j + 1]?.t === "(") {
64686
+ let k = j + 2;
64687
+ if (toks[k]?.t === "const" || toks[k]?.t === "let" || toks[k]?.t === "var") k++;
64688
+ let key = null;
64689
+ if (isIdent(toks[k]?.t)) {
64690
+ key = toks[k].t;
64691
+ k++;
64692
+ } else if (toks[k]?.t === "[" && isIdent(toks[k + 1]?.t)) {
64693
+ key = toks[k + 1].t;
64694
+ const c = matchClose(toks, k);
64695
+ if (c < 0) continue;
64696
+ k = c + 1;
64697
+ }
64698
+ if (!key) continue;
64699
+ if (toks[k]?.t === "in") {
64700
+ const c = chainAt(toks, k + 1);
64701
+ if (c && toks[c.end]?.t === ")") out2.push({ key, source: c.text });
64702
+ } else if (toks[k]?.t === "of" && toks[k + 1]?.t === "Object" && toks[k + 2]?.t === "." && ["keys", "entries", "getOwnPropertyNames"].includes(toks[k + 3]?.t ?? "") && toks[k + 4]?.t === "(") {
64703
+ const c = chainAt(toks, k + 5);
64704
+ if (c && toks[c.end]?.t === ")") out2.push({ key, source: c.text });
64705
+ }
64706
+ } else if (t === "Object" && toks[j + 1]?.t === "." && (toks[j + 2]?.t === "keys" || toks[j + 2]?.t === "entries") && toks[j + 3]?.t === "(") {
64707
+ const c = chainAt(toks, j + 4);
64708
+ if (!c || toks[c.end]?.t !== ")") continue;
64709
+ let k = c.end + 1;
64710
+ if (toks[k]?.t !== "." || toks[k + 1]?.t !== "forEach" || toks[k + 2]?.t !== "(") continue;
64711
+ k += 3;
64712
+ if (toks[k]?.t === "function") k++;
64713
+ if (toks[k]?.t === "(") k++;
64714
+ if (toks[k]?.t === "[") k++;
64715
+ if (isIdent(toks[k]?.t)) out2.push({ key: toks[k].t, source: c.text });
64716
+ }
64717
+ }
64718
+ return out2;
64719
+ }
64720
+ function chainBefore(toks, k) {
64721
+ let j = k - 1;
64722
+ if (!isIdent(toks[j]?.t) && toks[j]?.t !== "this") return null;
64723
+ const parts2 = [toks[j].t];
64724
+ while ((toks[j - 1]?.t === "." || toks[j - 1]?.t === "?.") && (isIdent(toks[j - 2]?.t) || toks[j - 2]?.t === "this")) {
64725
+ parts2.unshift(toks[j - 2].t);
64726
+ j -= 2;
64727
+ }
64728
+ return parts2.join(".");
64729
+ }
64730
+ function recursiveMerge(toks, fn) {
64731
+ if (!fn.name) return [];
64732
+ const out2 = [];
64733
+ for (const loop of keyLoops(toks, fn.open, fn.close)) {
64734
+ const recursedTargets = /* @__PURE__ */ new Set();
64735
+ for (let j = fn.open + 1; j < fn.close; j++) {
64736
+ if (toks[j].t !== fn.name || toks[j + 1]?.t !== "(") continue;
64737
+ const prev = toks[j - 1]?.t;
64738
+ if (prev === "function" || prev === "." && toks[j - 2]?.t !== "this") continue;
64739
+ const close = matchClose(toks, j + 1);
64740
+ for (let k = j + 2; k + 2 < close; k++) {
64741
+ if (toks[k].t === "[" && toks[k + 1].t === loop.key && toks[k + 2].t === "]") {
64742
+ const t = chainBefore(toks, k);
64743
+ if (t && t !== loop.source) recursedTargets.add(t);
64744
+ }
64745
+ }
64746
+ }
64747
+ if (recursedTargets.size === 0) continue;
64748
+ for (let j = fn.open + 1; j < fn.close; j++) {
64749
+ if (toks[j - 1]?.t === ".") continue;
64750
+ const c = chainAt(toks, j);
64751
+ if (!c) continue;
64752
+ const k = c.end;
64753
+ if (recursedTargets.has(c.text) && toks[k]?.t === "[" && toks[k + 1]?.t === loop.key && toks[k + 2]?.t === "]" && isAssign2(toks[k + 3]?.t)) {
64754
+ out2.push({ pos: toks[j].pos, target: c.text, key: loop.key });
64755
+ break;
64756
+ }
64757
+ }
64758
+ }
64759
+ return out2;
64760
+ }
64761
+ function isPathName(name2) {
64762
+ const lower = name2.toLowerCase();
64763
+ return PATH_NAME_WORDS.some((w) => lower === w || lower.endsWith(w));
64764
+ }
64765
+ function setByPath(toks, raw, base, fn) {
64766
+ let hasLoop = false;
64767
+ let pathEvidence = false;
64768
+ const pathNames = /* @__PURE__ */ new Set();
64769
+ for (let j = fn.open + 1; j < fn.close; j++) {
64770
+ const t = toks[j].t;
64771
+ if (t === "for" || t === "while" || t === "forEach" || t === "reduce") hasLoop = true;
64772
+ if (t === "split" && toks[j - 1]?.t === "." && toks[j + 1]?.t === "(") {
64773
+ const arg = toks[j + 2];
64774
+ let real = false;
64775
+ if (arg && arg.t === '"') {
64776
+ const q = raw[arg.pos - base];
64777
+ real = raw[arg.pos - base + 1] !== q;
64778
+ } else if (arg && arg.t === "/") {
64779
+ real = true;
64780
+ }
64781
+ if (real) {
64782
+ pathEvidence = true;
64783
+ let k = j - 2;
64784
+ while (k > fn.open && (isIdent(toks[k]?.t) || toks[k]?.t === "." || toks[k]?.t === ")" || toks[k]?.t === "(")) {
64785
+ if (toks[k].t === ")") {
64786
+ const o = matchOpen(toks, k);
64787
+ if (o < 0) break;
64788
+ k = o - 1;
64789
+ continue;
64790
+ }
64791
+ k--;
64792
+ }
64793
+ if (toks[k]?.t === "=" && isIdent(toks[k - 1]?.t)) pathNames.add(toks[k - 1].t);
64794
+ }
64795
+ }
64796
+ if (t === "for" && toks[j + 1]?.t === "(") {
64797
+ const close = matchClose(toks, j + 1);
64798
+ for (let k = j + 2; k < close; k++) {
64799
+ if (toks[k].t === "of" || toks[k].t === "in") {
64800
+ const c = chainAt(toks, k + 1);
64801
+ const last = c ? c.text.split(".").pop() ?? "" : "";
64802
+ if (c && (isPathName(last) || pathNames.has(last))) {
64803
+ pathEvidence = true;
64804
+ if (isIdent(toks[k - 1]?.t)) pathNames.add(toks[k - 1].t);
64805
+ }
64806
+ }
64807
+ }
64808
+ }
64809
+ if ((t === "forEach" || t === "reduce") && toks[j - 1]?.t === ".") {
64810
+ const coll = toks[j - 2]?.t;
64811
+ const isSplit = toks[j - 2]?.t === ")" && toks[matchOpen(toks, j - 2) - 1]?.t === "split";
64812
+ if (isIdent(coll) && (isPathName(coll) || pathNames.has(coll)) || isSplit) {
64813
+ pathEvidence = true;
64814
+ let k = j + 2;
64815
+ if (toks[k]?.t === "function") k++;
64816
+ if (toks[k]?.t === "(") {
64817
+ const c = matchClose(toks, k);
64818
+ for (const n of paramNames(toks, k, c)) pathNames.add(n);
64819
+ } else if (isIdent(toks[k]?.t)) {
64820
+ pathNames.add(toks[k].t);
64821
+ }
64822
+ }
64823
+ }
64824
+ }
64825
+ if (!hasLoop || !pathEvidence) return [];
64826
+ for (let j = fn.open + 1; j < fn.close; j++) {
64827
+ if ((toks[j].t === "const" || toks[j].t === "let" || toks[j].t === "var") && isIdent(toks[j + 1]?.t) && toks[j + 2]?.t === "=" && pathNames.has(toks[j + 3]?.t ?? "") && (toks[j + 4]?.t === "[" || toks[j + 4]?.t === ".")) {
64828
+ pathNames.add(toks[j + 1].t);
64829
+ }
64830
+ }
64831
+ const cursors = /* @__PURE__ */ new Set();
64832
+ for (let j = fn.open + 1; j < fn.close; j++) {
64833
+ const x = toks[j].t;
64834
+ if (x === "reduce" && toks[j - 1]?.t === "." && toks[j + 1]?.t === "(" && toks[j + 2]?.t === "(" && isIdent(toks[j + 3]?.t)) {
64835
+ cursors.add(toks[j + 3].t);
64836
+ }
64837
+ if (!isIdent(x) || toks[j - 1]?.t === ".") continue;
64838
+ if (toks[j + 1]?.t === "=" && toks[j + 2]?.t === x && toks[j + 3]?.t === "[") cursors.add(x);
64839
+ }
64840
+ const out2 = [];
64841
+ for (const x of cursors) {
64842
+ for (let j = fn.open + 1; j < fn.close; j++) {
64843
+ if (toks[j].t !== x || toks[j - 1]?.t === "." || toks[j + 1]?.t !== "[") continue;
64844
+ const c = matchClose(toks, j + 1);
64845
+ if (c < 0 || !isAssign2(toks[c + 1]?.t)) continue;
64846
+ let key = null;
64847
+ for (let k = j + 2; k < c; k++) if (pathNames.has(toks[k].t)) {
64848
+ key = toks[k].t;
64849
+ break;
64850
+ }
64851
+ if (!key) continue;
64852
+ out2.push({ pos: toks[j].pos, target: x, key });
64853
+ break;
64854
+ }
64855
+ }
64856
+ return out2;
64857
+ }
64858
+ function requestNames(toks, from, to) {
64859
+ const out2 = /* @__PURE__ */ new Set();
64860
+ const isBag = (k) => REQUEST_ROOTS.has(toks[k]?.t ?? "") && toks[k + 1]?.t === "." && REQUEST_BAGS.has(toks[k + 2]?.t ?? "");
64861
+ for (let j = from; j < to; j++) {
64862
+ const t = toks[j].t;
64863
+ if (t !== "const" && t !== "let" && t !== "var") continue;
64864
+ if (toks[j + 1]?.t === "{") {
64865
+ const close = matchClose(toks, j + 1);
64866
+ if (close < 0 || toks[close + 1]?.t !== "=" || !isBag(close + 2)) continue;
64867
+ let depth = 0;
64868
+ for (let k = j + 2; k < close; k++) {
64869
+ const s = toks[k].t;
64870
+ if (s === "{" || s === "[") depth++;
64871
+ else if (s === "}" || s === "]") depth--;
64872
+ else if (depth === 0 && isIdent(s) && toks[k + 1]?.t !== ":") out2.add(s);
64873
+ }
64874
+ } else if (isIdent(toks[j + 1]?.t) && toks[j + 2]?.t === "=" && isBag(j + 3)) {
64875
+ out2.add(toks[j + 1].t);
64876
+ }
64877
+ }
64878
+ return out2;
64879
+ }
64880
+ function requestKey(toks, open, close, names) {
64881
+ if (close === open + 2 && names.has(toks[open + 1].t)) return toks[open + 1].t;
64882
+ const k = open + 1;
64883
+ if (REQUEST_ROOTS.has(toks[k]?.t ?? "") && toks[k + 1]?.t === "." && REQUEST_BAGS.has(toks[k + 2]?.t ?? "") && toks[k + 3]?.t === "." && isIdent(toks[k + 4]?.t) && close === k + 5) {
64884
+ return `${toks[k].t}.${toks[k + 2].t}.${toks[k + 4].t}`;
64885
+ }
64886
+ return null;
64887
+ }
64888
+ function requestKeys(toks, fn) {
64889
+ const names = requestNames(toks, fn.open, fn.close);
64890
+ const out2 = [];
64891
+ for (let j = fn.open + 1; j < fn.close; j++) {
64892
+ if (toks[j - 1]?.t === ".") continue;
64893
+ const c = chainAt(toks, j);
64894
+ if (!c || toks[c.end]?.t !== "[") continue;
64895
+ const c1 = matchClose(toks, c.end);
64896
+ if (c1 < 0 || toks[c1 + 1]?.t !== "[") continue;
64897
+ const c2 = matchClose(toks, c1 + 1);
64898
+ if (c2 < 0 || !isAssign2(toks[c2 + 1]?.t)) continue;
64899
+ const k1 = requestKey(toks, c.end, c1, names);
64900
+ const k2 = requestKey(toks, c1 + 1, c2, names);
64901
+ if (k1 && k2) out2.push({ pos: toks[j].pos, target: c.text, key: `${k1}, ${k2}` });
64902
+ }
64903
+ return out2;
64904
+ }
64905
+ function detectPrototypePollution(code) {
64906
+ if (code.length > MAX_CODE_LENGTH) return [];
64907
+ const masked = maskLiterals(code);
64908
+ const toks = tokenize(masked);
64909
+ const fns = findFunctions(toks);
64910
+ const fileNullProto = nullProtoNames(toks, 0, toks.length);
64911
+ const hits = [];
64912
+ const seen = /* @__PURE__ */ new Set();
64913
+ for (const fn of fns) {
64914
+ const base = toks[fn.open].pos;
64915
+ const raw = code.slice(base, toks[fn.close].pos + 1);
64916
+ const found = [];
64917
+ for (const h of recursiveMerge(toks, fn)) found.push({ ...h, shape: "recursive-merge" });
64918
+ for (const h of setByPath(toks, raw, base, fn)) found.push({ ...h, shape: "set-by-path" });
64919
+ for (const h of requestKeys(toks, fn)) found.push({ ...h, shape: "request-keys" });
64920
+ if (found.length === 0) continue;
64921
+ const keys = /* @__PURE__ */ new Set();
64922
+ for (const h of found) for (const k of h.key.split(", ")) keys.add(k);
64923
+ if (hasGuard(raw, toks, fn.open, fn.close, keys)) continue;
64924
+ const nullProto = nullProtoNames(toks, fn.open, fn.close);
64925
+ for (const h of found) {
64926
+ const root = h.target.split(".")[0];
64927
+ if (nullProto.has(root) || fileNullProto.has(root)) continue;
64928
+ const line = lineOf(code, h.pos);
64929
+ if (seen.has(line)) continue;
64930
+ seen.add(line);
64931
+ hits.push({ line, shape: h.shape, target: h.target, key: h.key, fn: fn.name });
64932
+ }
64933
+ }
64934
+ return hits.sort((a, b) => a.line - b.line);
64935
+ }
64936
+ var MESSAGES = {
64937
+ "recursive-merge": (h) => `Recursive merge${h.fn ? ` \`${h.fn}\`` : ""} copies every key into \`${h.target}\` without rejecting \`__proto__\`, \`constructor\` or \`prototype\`: a source object with a \`__proto__\` key (for example from \`JSON.parse\`) writes into \`Object.prototype\`.`,
64938
+ "set-by-path": (h) => `Set-by-path${h.fn ? ` \`${h.fn}\`` : ""} walks \`${h.target}\` along a key path without rejecting \`__proto__\`, \`constructor\` or \`prototype\`: a path such as \`__proto__.isAdmin\` writes into \`Object.prototype\`.`,
64939
+ "request-keys": (h) => `\`${h.target}[\u2026][\u2026]\` is written with keys from the request (${h.key}): \`__proto__\` as the first key writes the second key into \`Object.prototype\`.`
64940
+ };
64941
+ var PrototypePollutionPass = class {
64942
+ name = "prototype-pollution";
64943
+ category = "security";
64944
+ run(ctx) {
64945
+ const { language } = ctx;
64946
+ if (language !== "javascript" && language !== "typescript") return { findings: [] };
64947
+ const file = ctx.graph.ir.meta.file;
64948
+ const findings = detectPrototypePollution(ctx.code);
64949
+ for (const h of findings) {
64950
+ ctx.addFinding({
64951
+ id: `${this.name}-${file}-${h.line}`,
64952
+ pass: this.name,
64953
+ category: this.category,
64954
+ rule_id: this.name,
64955
+ cwe: "CWE-1321",
64956
+ severity: h.shape === "request-keys" ? "high" : "medium",
64957
+ level: h.shape === "request-keys" ? "error" : "warning",
64958
+ message: MESSAGES[h.shape](h),
64959
+ file,
64960
+ line: h.line,
64961
+ fix: "Skip the keys `__proto__`, `constructor` and `prototype` before writing, or write into an object made with `Object.create(null)` or a `Map`.",
64962
+ evidence: { shape: h.shape, target: h.target, key: h.key, ...h.fn ? { function: h.fn } : {} }
64963
+ });
64964
+ }
64965
+ return { findings };
64966
+ }
64967
+ };
64968
+
63220
64969
  // src/analysis/passes/csrf-samesite-none-session-pass.ts
63221
64970
  var SESSION_FACTORIES = /* @__PURE__ */ new Set(["session", "cookieSession", "expressSession"]);
63222
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
64971
+ var MUTATING_METHODS2 = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
63223
64972
  var DEFENCE_MARKERS = ["csrf", "csurf", "xsrf", "lusca"];
63224
64973
  var ORIGIN_CHECK_MARKERS = [
63225
64974
  "headers.origin",
@@ -63237,7 +64986,7 @@ var ORIGIN_CHECK_MARKERS = [
63237
64986
  "header('referer')",
63238
64987
  'header("referer")'
63239
64988
  ];
63240
- function isIdentChar2(ch) {
64989
+ function isIdentChar5(ch) {
63241
64990
  return ch !== void 0 && (ch === "_" || ch === "$" || ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9");
63242
64991
  }
63243
64992
  function sameSiteSetting(options) {
@@ -63247,7 +64996,7 @@ function sameSiteSetting(options) {
63247
64996
  const at = options.indexOf("sameSite", from);
63248
64997
  if (at < 0) return result;
63249
64998
  from = at + "sameSite".length;
63250
- if (isIdentChar2(options[at - 1]) || isIdentChar2(options[from])) continue;
64999
+ if (isIdentChar5(options[at - 1]) || isIdentChar5(options[from])) continue;
63251
65000
  let k = from;
63252
65001
  if (options[k] === "'" || options[k] === '"') k++;
63253
65002
  while (options[k] === " ") k++;
@@ -63279,9 +65028,9 @@ function sessionOptions(useCall) {
63279
65028
  return null;
63280
65029
  }
63281
65030
  function isStateChangingRoute(call) {
63282
- if (!MUTATING_METHODS.has(call.method_name)) return false;
65031
+ if (!MUTATING_METHODS2.has(call.method_name)) return false;
63283
65032
  const receiver = (call.receiver ?? "").trim();
63284
- if (!receiver || [...receiver].some((ch) => !isIdentChar2(ch))) return false;
65033
+ if (!receiver || [...receiver].some((ch) => !isIdentChar5(ch))) return false;
63285
65034
  const path = (call.arguments.find((a) => a.position === 0)?.expression ?? "").trim();
63286
65035
  return path.length >= 3 && (path[0] === "'" || path[0] === '"' || path[0] === "`") && path[1] === "/" && call.arguments.length >= 2;
63287
65036
  }
@@ -63905,7 +65654,7 @@ var ComplexityMetricsPass = class {
63905
65654
  };
63906
65655
 
63907
65656
  // src/analysis/metrics/passes/halstead-metrics-pass.ts
63908
- var KEYWORDS2 = /* @__PURE__ */ new Set([
65657
+ var KEYWORDS3 = /* @__PURE__ */ new Set([
63909
65658
  "if",
63910
65659
  "else",
63911
65660
  "for",
@@ -63996,7 +65745,7 @@ var HalsteadMetricsPass = class {
63996
65745
  const { code } = ctx;
63997
65746
  const allKeywords = Array.from(code.matchAll(KEYWORD_RE), (m) => m[0]);
63998
65747
  const allSymbols = Array.from(code.matchAll(SYMBOL_RE), (m) => m[0]);
63999
- const allIdents = Array.from(code.matchAll(IDENT_RE), (m) => m[0]).filter((t) => !KEYWORDS2.has(t));
65748
+ const allIdents = Array.from(code.matchAll(IDENT_RE), (m) => m[0]).filter((t) => !KEYWORDS3.has(t));
64000
65749
  const allLiterals = Array.from(code.matchAll(LITERAL_RE), (m) => m[0]);
64001
65750
  const operators = [...allKeywords, ...allSymbols];
64002
65751
  const operands = [...allIdents, ...allLiterals];
@@ -65231,6 +66980,10 @@ async function analyzeFile(code, filePath, language, options) {
65231
66980
  if (!disabledPasses.has("cache-no-vary")) pipeline.add(new CacheNoVaryPass());
65232
66981
  if (!disabledPasses.has("jwt-verify-disabled")) pipeline.add(new JwtVerifyDisabledPass());
65233
66982
  if (!disabledPasses.has("sensitive-data-in-log")) pipeline.add(new SensitiveDataInLogPass());
66983
+ if (!disabledPasses.has("redos-regex-literal")) pipeline.add(new RedosRegexLiteralPass());
66984
+ if (!disabledPasses.has("hardcoded-secret-argument")) pipeline.add(new HardcodedSecretArgumentPass());
66985
+ if (!disabledPasses.has("missing-auth-middleware")) pipeline.add(new MissingAuthMiddlewarePass());
66986
+ if (!disabledPasses.has("prototype-pollution")) pipeline.add(new PrototypePollutionPass());
65234
66987
  if (!disabledPasses.has("csrf-protection-disabled")) pipeline.add(new CsrfProtectionDisabledPass());
65235
66988
  if (!disabledPasses.has("csrf-samesite-none-session")) pipeline.add(new CsrfSameSiteNoneSessionPass());
65236
66989
  if (!disabledPasses.has("xml-entity-expansion")) pipeline.add(new XmlEntityExpansionPass());