@jshookmcp/jshook 0.3.3 → 0.3.4

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 (311) hide show
  1. package/README.md +19 -4
  2. package/README.zh.md +19 -4
  3. package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
  4. package/dist/{BrowserSessionCoordinator-QIt3tetp.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
  5. package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
  6. package/dist/CodeInjector-B099WO6x.mjs +1 -0
  7. package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
  8. package/dist/CpuEngine-BC8jayy9.mjs +1 -0
  9. package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
  10. package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
  11. package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
  12. package/dist/{DetailedDataManager-Z77fDl9Z.mjs → DetailedDataManager-Dgh402Gp.mjs} +2 -2
  13. package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
  14. package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
  15. package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
  16. package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
  17. package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
  18. package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
  19. package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
  20. package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
  21. package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
  22. package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
  23. package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
  24. package/dist/MemoryController-CCsGuGJS.mjs +2 -0
  25. package/dist/{MemoryScanSession-zfoVZJB0.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
  26. package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
  27. package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
  28. package/dist/{NativeMemoryManager.utils-Bu8srMEF.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
  29. package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
  30. package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
  31. package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
  32. package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
  33. package/dist/QuickJSSandbox-CIde-jzG.mjs +299 -0
  34. package/dist/{ResponseBuilder-nPXl_khE.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
  35. package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
  36. package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
  37. package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
  38. package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
  39. package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
  40. package/dist/{ToolProbe-DQiREmNp.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
  41. package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
  42. package/dist/{ToolRouter.policy-UKBlFlbh.mjs → ToolRouter.policy-Bgb3S8jc.mjs} +2 -2
  43. package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
  44. package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
  45. package/dist/Win32API-G7QPyckq.mjs +1 -0
  46. package/dist/{Win32Debug-DwF8mQGm.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
  47. package/dist/allocation-track-CiI-CnaI.mjs +1 -0
  48. package/dist/analysis-CojUzwX-.mjs +27 -0
  49. package/dist/{antidebug-CsnpOR9z.mjs → antidebug-CgU84TE1.mjs} +1 -1
  50. package/dist/apk-DrPBsOq8.mjs +1 -0
  51. package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
  52. package/dist/artifacts-Bx9GLx4J.mjs +1 -0
  53. package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
  54. package/dist/ast-utils-B9E5k_v1.mjs +1 -0
  55. package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
  56. package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
  57. package/dist/browser-QDUu5ML9.mjs +29 -0
  58. package/dist/{canvas-396ieNv5.mjs → canvas-g5kmLdY-.mjs} +1098 -24
  59. package/dist/{capabilities-L1ax5EHS.mjs → capabilities-DwzyxL2w.mjs} +1 -1
  60. package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
  61. package/dist/collector-Cld4i-E4.mjs +1 -0
  62. package/dist/config-5ODJ3Aj0.mjs +3 -0
  63. package/dist/constants-nvsLpSri.mjs +1 -0
  64. package/dist/coordination-C6y2gM9O.mjs +98 -0
  65. package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
  66. package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
  67. package/dist/debugger-C2SpiXoO.mjs +1 -0
  68. package/dist/definitions-0mtilYzG.mjs +1 -0
  69. package/dist/definitions-9csunmeX.mjs +1 -0
  70. package/dist/definitions-B11MudW_.mjs +1 -0
  71. package/dist/definitions-BKpRDjcI.mjs +1 -0
  72. package/dist/definitions-BXE3H4re.mjs +1 -0
  73. package/dist/definitions-BlPHe5DX.mjs +1 -0
  74. package/dist/definitions-Bob4XMxI.mjs +27 -0
  75. package/dist/definitions-BpIQN2nm.mjs +1 -0
  76. package/dist/{definitions-Ym8niHDb.mjs → definitions-BvolWeSu.mjs} +1 -1
  77. package/dist/definitions-C-6j3Ejl.mjs +1 -0
  78. package/dist/definitions-C-AdFfFu.mjs +1 -0
  79. package/dist/definitions-CArdw_9T.mjs +1 -0
  80. package/dist/definitions-CCvIcRrT.mjs +1 -0
  81. package/dist/definitions-CJPE5PIl.mjs +1 -0
  82. package/dist/definitions-CbqeW06u.mjs +1 -0
  83. package/dist/definitions-Cexmkypg.mjs +1 -0
  84. package/dist/definitions-D1dxl8qt.mjs +1 -0
  85. package/dist/definitions-D3uT-ZbU.mjs +1 -0
  86. package/dist/definitions-DtOY5iUc.mjs +1 -0
  87. package/dist/{definitions-Cv5r8xwq.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
  88. package/dist/definitions-ihxOqOC4.mjs +1 -0
  89. package/dist/deopt-trace-qnAcC931.mjs +17 -0
  90. package/dist/disasm-DoxSucGp.mjs +1 -0
  91. package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
  92. package/dist/encoding-UMtwgy4M.mjs +2 -0
  93. package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
  94. package/dist/factory-BeND77hf.mjs +2 -0
  95. package/dist/graphql-CF7QKJME.mjs +68 -0
  96. package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
  97. package/dist/handlers--qCl9vNv.mjs +1 -0
  98. package/dist/handlers-BHIu1LqA.mjs +1 -0
  99. package/dist/{handlers-DB6xVVWq.mjs → handlers-BQ4K8Jbr.mjs} +1 -1
  100. package/dist/handlers-BxQv-wtf.mjs +8 -0
  101. package/dist/handlers-ByYG27-5.mjs +1 -0
  102. package/dist/handlers-C0I9-BtX.mjs +5 -0
  103. package/dist/{handlers-CWKBBjai.mjs → handlers-CL0Iokmw.mjs} +1 -1
  104. package/dist/handlers-CNbhIdSK.mjs +4 -0
  105. package/dist/handlers-CnTTSJFs.mjs +109 -0
  106. package/dist/handlers-CoDx6akJ2.mjs +49 -0
  107. package/dist/{handlers-BbLxNbbT.mjs → handlers-DASJI0Pn.mjs} +1 -1
  108. package/dist/handlers-DRKMaA-_.mjs +74 -0
  109. package/dist/handlers-Dalu0olz.mjs +2 -0
  110. package/dist/handlers-KY0g31ny.mjs +9 -0
  111. package/dist/handlers-oGo60aVv.mjs +1 -0
  112. package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
  113. package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
  114. package/dist/{hooks-DPouiS7I.mjs → hooks-COK3t5rT.mjs} +51 -32
  115. package/dist/index.mjs +11 -11
  116. package/dist/logger-BGCcd-jJ.mjs +1 -0
  117. package/dist/macro-nUYUjKNZ.mjs +2 -0
  118. package/dist/maintenance-CfnE7ZKU.mjs +4 -0
  119. package/dist/manifest-7EOTUc0D.mjs +1 -0
  120. package/dist/manifest-B5ujuQmf.mjs +1 -0
  121. package/dist/manifest-BErXl3zn.mjs +1 -0
  122. package/dist/manifest-BKA-mD3J.mjs +1 -0
  123. package/dist/manifest-BUXj23bX.mjs +1 -0
  124. package/dist/manifest-BfXt9cau.mjs +1 -0
  125. package/dist/manifest-Bx-tpURK.mjs +1 -0
  126. package/dist/manifest-C0owVAdq.mjs +1 -0
  127. package/dist/manifest-C5XqYc9o.mjs +1 -0
  128. package/dist/manifest-CVKzLjsA.mjs +1 -0
  129. package/dist/manifest-CaeFjdhj.mjs +1 -0
  130. package/dist/manifest-CegBgip0.mjs +1 -0
  131. package/dist/manifest-CoJHqlgS.mjs +1 -0
  132. package/dist/manifest-D0dbtDqd.mjs +1 -0
  133. package/dist/manifest-D5Gr8ujd.mjs +12 -0
  134. package/dist/manifest-D82z-5og.mjs +1 -0
  135. package/dist/manifest-DA2afIwh.mjs +1 -0
  136. package/dist/manifest-DAbiFP5o.mjs +1 -0
  137. package/dist/manifest-DEY0s1O72.mjs +1 -0
  138. package/dist/manifest-DTOqNqiA.mjs +1 -0
  139. package/dist/manifest-DZ6ELNgX.mjs +1 -0
  140. package/dist/manifest-DjHkjddT.mjs +1 -0
  141. package/dist/manifest-DocA_itf2.mjs +1 -0
  142. package/dist/manifest-Dpnhvfq0.mjs +1 -0
  143. package/dist/manifest-DucPMG_a.mjs +1 -0
  144. package/dist/manifest-Dw5yYEac.mjs +1 -0
  145. package/dist/manifest-Ic_Cg66S.mjs +1 -0
  146. package/dist/manifest-JHaG6GMN.mjs +1 -0
  147. package/dist/manifest-QdkIzmYM.mjs +1 -0
  148. package/dist/manifest-YZqaCe25.mjs +1 -0
  149. package/dist/manifest-f0lUeXwq.mjs +1 -0
  150. package/dist/manifest-h-Ebisf8.mjs +1 -0
  151. package/dist/manifest-oOfTymBS.mjs +1 -0
  152. package/dist/manifest-qXqrO6KC.mjs +2 -0
  153. package/dist/mapsParser-DrJoeC0c.mjs +1 -0
  154. package/dist/modules-CC_ADmwi.mjs +333 -0
  155. package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
  156. package/dist/native-D9ouskXO.mjs +961 -0
  157. package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
  158. package/dist/network-C5Y-S87J.mjs +7 -0
  159. package/dist/one-gadget-CiWFE17F.mjs +1 -0
  160. package/dist/outputPaths-CHtELDyi.mjs +1 -0
  161. package/dist/parse-args-B6dwWc9k.mjs +1 -0
  162. package/dist/platform-BIXgJaM3.mjs +94 -0
  163. package/dist/process-aDIfLC0v.mjs +6 -0
  164. package/dist/proxy-DsHsQ1I4.mjs +2 -0
  165. package/dist/registry-7h8jJ9y9.mjs +1 -0
  166. package/dist/{registry-xB8Wgmyj.mjs → registry-DJDnkQW2.mjs} +1 -1
  167. package/dist/response-R8ghbZSb.mjs +1 -0
  168. package/dist/retry-policy-DtYv0kDi.mjs +1 -0
  169. package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
  170. package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
  171. package/dist/{search-defaults-CJik67or.mjs → search-defaults-BBRJNAzC.mjs} +1 -1
  172. package/dist/server/search/EmbeddingWorker.d.mts +1 -0
  173. package/dist/server/search/EmbeddingWorker.mjs +1 -0
  174. package/dist/shared-BKtWZDGN.mjs +1 -0
  175. package/dist/sourcemap-2VIeVeKw.mjs +3 -0
  176. package/dist/streaming-DkpE3GGU.mjs +15 -0
  177. package/dist/syscall-DGZoYM_U.mjs +1 -0
  178. package/dist/transform-BJqsBC_-.mjs +105 -0
  179. package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
  180. package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
  181. package/dist/types-CWSvzmIh.mjs +1 -0
  182. package/dist/v8-inspector-CTJo08-K.mjs +297 -0
  183. package/dist/wasm-DX4Qm2Vs.mjs +235 -0
  184. package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
  185. package/dist/webgpu-D4-DxbxZ.mjs +6 -0
  186. package/dist/workflow-DHktRNF2.mjs +108 -0
  187. package/package.json +33 -27
  188. package/dist/AntiCheatDetector-CUpZBh5O.mjs +0 -1
  189. package/dist/CodeInjector-Btj9upnf.mjs +0 -1
  190. package/dist/ConsoleMonitor-DIjN5Afa.mjs +0 -306
  191. package/dist/DarwinAPI-BuMPGzHm.mjs +0 -1
  192. package/dist/ExtensionManager.tools-CIGOWViz.mjs +0 -1
  193. package/dist/FingerprintManager-BkDSsjjP.mjs +0 -1
  194. package/dist/HardwareBreakpoint-DMAMcPyB.mjs +0 -1
  195. package/dist/HeapAnalyzer-Yj348FYt.mjs +0 -1
  196. package/dist/InstrumentationSession-c5qZyp7d.mjs +0 -1
  197. package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +0 -1
  198. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +0 -1
  199. package/dist/MemoryController-DjtgiING.mjs +0 -2
  200. package/dist/MemoryScanner-Dxd657li.mjs +0 -1
  201. package/dist/PEAnalyzer-CMu9Ua9T.mjs +0 -1
  202. package/dist/PointerChainEngine-CaSC1Mry.mjs +0 -1
  203. package/dist/ProcessRegistry-D5y1yuP2.mjs +0 -1
  204. package/dist/ReverseEvidenceGraph-BksOpsPs.mjs +0 -2
  205. package/dist/ServerRuntimeState-CgqBBwfd.mjs +0 -1
  206. package/dist/Speedhack-pwXTHxOY.mjs +0 -1
  207. package/dist/StructureAnalyzer-BseGzsSl.mjs +0 -2
  208. package/dist/ToolCatalog-DgmQXdsm.mjs +0 -1
  209. package/dist/ToolHandlerMap-7HWoIgQO.mjs +0 -1
  210. package/dist/ToolRegistry-eMZEBiR1.mjs +0 -1
  211. package/dist/TraceRecorder-B5ktv3nP.mjs +0 -272
  212. package/dist/VersionDetector-CmPJmaJg.mjs +0 -1
  213. package/dist/Win32API-DoP3MMHS.mjs +0 -1
  214. package/dist/WorkflowEngine-CldHG5b4.mjs +0 -1
  215. package/dist/analysis-C-ln0Brh.mjs +0 -6
  216. package/dist/artifactRetention-DkYKLOvi.mjs +0 -1
  217. package/dist/artifacts-D-4pSS_N.mjs +0 -1
  218. package/dist/binary-instrument-BeZ224mZ.mjs +0 -9
  219. package/dist/boringssl-inspector-ZOCkaipa.mjs +0 -2
  220. package/dist/browser-BUaB25bk.mjs +0 -11
  221. package/dist/collector-CB2syQEg.mjs +0 -1
  222. package/dist/constants-DMv3svps.mjs +0 -2
  223. package/dist/coordination-Dbohmj6D.mjs +0 -1
  224. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  225. package/dist/debugger-CLzkObIO.mjs +0 -1
  226. package/dist/definitions-0hxnrDU72.mjs +0 -1
  227. package/dist/definitions-B3a9QC2t.mjs +0 -1
  228. package/dist/definitions-BOvju5t2.mjs +0 -1
  229. package/dist/definitions-CXj_cEVt.mjs +0 -1
  230. package/dist/definitions-Co6AvTjH.mjs +0 -1
  231. package/dist/definitions-DBYSxChX.mjs +0 -1
  232. package/dist/definitions-D_dTDX9B.mjs +0 -1
  233. package/dist/definitions-Db9t2ddh.mjs +0 -1
  234. package/dist/definitions-DbN2CjI2.mjs +0 -1
  235. package/dist/definitions-DlmmHmZc.mjs +0 -1
  236. package/dist/definitions-DnYpoGig.mjs +0 -1
  237. package/dist/definitions-DtZ6Ktx2.mjs +0 -1
  238. package/dist/definitions-DuIPS8gq.mjs +0 -1
  239. package/dist/definitions-DywfwPMb.mjs +0 -1
  240. package/dist/definitions-EGmqr85H.mjs +0 -1
  241. package/dist/definitions-Fetw_Cge.mjs +0 -26
  242. package/dist/definitions-LdkeuOeA.mjs +0 -1
  243. package/dist/definitions-cnG6tj17.mjs +0 -1
  244. package/dist/encoding-B4xZWErf.mjs +0 -2
  245. package/dist/ensure-browser-core-JHwDo5ql.mjs +0 -285
  246. package/dist/factory-BxNdBiZa.mjs +0 -1
  247. package/dist/graphql-GBWsZ9xC.mjs +0 -62
  248. package/dist/handlers-5nzR8B0a.mjs +0 -5
  249. package/dist/handlers-6iNsXOVT.mjs +0 -7
  250. package/dist/handlers-BZ8n6Hvf.mjs +0 -1
  251. package/dist/handlers-BbS4hssc.mjs +0 -4
  252. package/dist/handlers-CIKOP4aI.mjs +0 -2
  253. package/dist/handlers-Cmb6SoRC.mjs +0 -1
  254. package/dist/handlers-CrJsKnEI.mjs +0 -1
  255. package/dist/handlers-DOOCWUNR.mjs +0 -31
  256. package/dist/handlers-Z_B5aVaU.mjs +0 -54
  257. package/dist/handlers-gVscChvl.mjs +0 -1
  258. package/dist/handlers-xFvI9P_y.mjs +0 -1
  259. package/dist/handlers.impl-BsFTW6SD.mjs +0 -1
  260. package/dist/logger-CCikqqvj.mjs +0 -1
  261. package/dist/macro-p8kuJVcm.mjs +0 -2
  262. package/dist/maintenance-DAqADb6Z.mjs +0 -302
  263. package/dist/manifest-4lmM6MZR.mjs +0 -1
  264. package/dist/manifest-AxaxRSt6.mjs +0 -2
  265. package/dist/manifest-BIqRE1Qz.mjs +0 -1
  266. package/dist/manifest-Box-jWfr.mjs +0 -1
  267. package/dist/manifest-Bp33di0Q.mjs +0 -1
  268. package/dist/manifest-BvRX4nRP.mjs +0 -1
  269. package/dist/manifest-C6KoB1XE.mjs +0 -1
  270. package/dist/manifest-C7TdXCWY.mjs +0 -1
  271. package/dist/manifest-CM-n64K0.mjs +0 -1
  272. package/dist/manifest-CUokxCUN.mjs +0 -1
  273. package/dist/manifest-CWJS45iO.mjs +0 -1
  274. package/dist/manifest-Cdxdgo-D.mjs +0 -1
  275. package/dist/manifest-Cf6SmamD.mjs +0 -1
  276. package/dist/manifest-Cgxu2qdv.mjs +0 -1
  277. package/dist/manifest-CowGSURa2.mjs +0 -1
  278. package/dist/manifest-CsGIrh34.mjs +0 -1
  279. package/dist/manifest-CvDpVToN.mjs +0 -1
  280. package/dist/manifest-D8TL9RLE.mjs +0 -1
  281. package/dist/manifest-DIhtCBe6.mjs +0 -1
  282. package/dist/manifest-DJbruNOg.mjs +0 -1
  283. package/dist/manifest-DLGtZH-0.mjs +0 -1
  284. package/dist/manifest-DXHdPt2T.mjs +0 -1
  285. package/dist/manifest-Dg5ScOyW.mjs +0 -1
  286. package/dist/manifest-DzGoTS0R.mjs +0 -1
  287. package/dist/manifest-G2H52LKz.mjs +0 -131
  288. package/dist/manifest-P0Futrgb.mjs +0 -1
  289. package/dist/manifest-Qw7xgvjv.mjs +0 -1
  290. package/dist/manifest-W3qvVrP2.mjs +0 -1
  291. package/dist/manifest-dG6MuR1U.mjs +0 -1
  292. package/dist/manifest-nWXtgq5Y2.mjs +0 -1
  293. package/dist/manifest-vp1upSSq.mjs +0 -1
  294. package/dist/modules-DO3jXCgj.mjs +0 -333
  295. package/dist/mojo-ipc-Be-ccWrc.mjs +0 -9
  296. package/dist/native-g095qhpK.mjs +0 -961
  297. package/dist/network-Dvxm7eEI.mjs +0 -7
  298. package/dist/outputPaths-D2ddHrOJ.mjs +0 -2
  299. package/dist/parse-args-ngRrvF9e.mjs +0 -1
  300. package/dist/platform-DjWbuiF8.mjs +0 -93
  301. package/dist/process-Dq5I-KZW.mjs +0 -2
  302. package/dist/proxy-DPNgM7TE.mjs +0 -2
  303. package/dist/renderer-pid-7jbTR8f5.mjs +0 -1
  304. package/dist/response-B1RuVVfD.mjs +0 -1
  305. package/dist/sourcemap-DqEW15Ao.mjs +0 -1
  306. package/dist/streaming-Dbk4eStJ.mjs +0 -1
  307. package/dist/transform-D-peM3aO.mjs +0 -103
  308. package/dist/wasm-CZajRaad.mjs +0 -174
  309. package/dist/webcrack-phEfVt5y.mjs +0 -46
  310. package/dist/workflow-wkXb3x-U.mjs +0 -101
  311. /package/dist/{chunk-88NL7fhV.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
@@ -0,0 +1,6 @@
1
+ import{t as e}from"./logger-BGCcd-jJ.mjs";import{i as t,r as n}from"./constants-nvsLpSri.mjs";import{p as r}from"./ensure-browser-core-BP70x0TB.mjs";import{n as i,t as a}from"./native-D9ouskXO.mjs";import{C as o,a as s,b as c,f as l,n as u,p as d,s as f,t as p,u as m,w as h,x as g}from"./Win32API-G7QPyckq.mjs";import{t as _}from"./factory-BeND77hf.mjs";import{t as v}from"./PEAnalyzer-CB_kaTis.mjs";import{c as y,i as b,l as x,n as S}from"./parse-args-B6dwWc9k.mjs";import{r as C}from"./ResponseBuilder-BLicSCjn.mjs";import{c as w,l as T,t as E}from"./IntegrityScanner-BB7sw-SA.mjs";import"./definitions-C-6j3Ejl.mjs";import{readdirSync as ee}from"node:fs";import{readFile as D}from"node:fs/promises";import{promisify as te}from"node:util";import{exec as ne}from"node:child_process";import*as re from"@babel/parser";import ie from"@babel/traverse";import O from"koffi";const ae=new Set([`hex`,`int32`,`int64`,`float`,`double`,`string`]);function k(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Error(`Invalid PID: ${JSON.stringify(e)}`);return t}function A(e,t){if(typeof e!=`string`||e.length===0)throw Error(`${t} must be a non-empty string`);return e}function oe(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)throw Error(`${t} must be a positive number`);return n}function j(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`${t} must be a string`);return e.length>0?e:void 0}}function M(e){if(e==null||e===``)return`hex`;if(typeof e==`string`&&ae.has(e))return e;throw Error(`patternType must be one of: ${[...ae].join(`, `)}`)}function N(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function P(e){return typeof e==`string`&&e.length>0?e:void 0}function se(e){return e===`hex`||e===`base64`?e:void 0}function ce(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function F(e,t){if(e!==void 0){if(e===`hex`||e===`base64`)return e;throw Error(`${t} must be "hex" or "base64"`)}}function le(e,t){if(e!==void 0){if(e===`strict`||e===`balanced`||e===`permissive`||e===`disabled`)return e;throw Error(`${t} must be one of: strict, balanced, permissive, disabled`)}}function I(e,t){if(t===`hex`){let t=e.replace(/\s+/g,``);return Math.ceil(t.length/2)}return Buffer.from(e,`base64`).length}var ue=class{processManager;memoryManager;platform;auditTrail;constructor(e){this.processManager=e.processManager,this.memoryManager=e.memoryManager,this.platform=e.platform,this.auditTrail=e.auditTrail}async buildMemoryDiagnostics(e){let t=new Set,n=await this.memoryManager.checkAvailability();n.available||t.add(`Run as administrator`);let r=await this.resolveProcessInfo(e.pid);e.pid!==void 0&&e.pid!==null&&!r&&t.add(`Check if process is still running`);let i=await this.queryProtection(e);(i.queryFailed||i.info?.success===!1)&&t.add(`Verify address is within valid memory region`),e.size!==void 0&&e.size!==null&&i.info?.regionSize!==void 0&&i.info.regionSize!==null&&e.size>i.info.regionSize&&t.add(`Reduce the requested size to fit the target memory region`),e.operation===`memory_read`&&i.info?.success&&i.info.isReadable===!1&&t.add(`Ensure target memory region is readable`),e.operation===`memory_write`&&i.info?.success&&i.info.isWritable===!1&&t.add(`Ensure target memory region is writable`);let a=await this.enumerateModulesSafe(e.pid);e.pid!==void 0&&e.pid!==null&&e.address&&t.add(`Re-resolve the address after the process restarts because ASLR can shift module addresses`);let o=e.error?.toLowerCase()??``;(o.includes(`access denied`)||o.includes(`permission`)||o.includes(`privilege`)||o.includes(`administrator`))&&t.add(`Run as administrator`);let s=a.enumerated?a.count&&a.count>0?`Enumerated ${a.count} module(s). Treat absolute addresses as session-specific because ASLR can shift module bases between launches.`:`Module enumeration succeeded but returned no modules. Absolute addresses may still change across process launches because of ASLR.`:`Module enumeration was unavailable. Assume ASLR may shift absolute addresses between launches and re-resolve addresses after restarts.`;return{permission:{available:n.available,reason:n.reason,platform:this.platform},process:{exists:e.pid!==void 0&&e.pid!==null?!!r:null,pid:e.pid??null,name:r?.name??null},address:{queried:e.pid!==void 0&&e.pid!==null&&!!e.address,valid:e.pid!==void 0&&e.pid!==null&&e.address?i.info?.success??null:null,protection:i.info?.protection??null,regionStart:i.info?.regionStart??null,regionSize:i.info?.regionSize??null},aslr:{heuristic:!0,note:s},recommendedActions:Array.from(t)}}async safeBuildMemoryDiagnostics(t){try{return await this.buildMemoryDiagnostics(t)}catch(t){e.warn(`Memory diagnostics generation failed:`,t);return}}recordMemoryAudit(t){try{this.auditTrail.record(t)}catch(t){e.warn(`Memory audit trail recording failed:`,t)}}get platformValue(){return this.platform}exportMemoryAuditEntries(){return JSON.parse(this.auditTrail.exportJson())}clearMemoryAuditEntries(){this.auditTrail.clear()}getMemoryAuditCount(){return this.auditTrail.size()}async handleProcessList(t){try{let e=await this.processManager.findProcesses(``);return{content:[{type:`text`,text:JSON.stringify({success:!0,count:e.length,processes:e.map(e=>({pid:e.pid,name:e.name,path:e.executablePath,windowTitle:e.windowTitle,windowHandle:e.windowHandle,memoryMB:e.memoryUsage?Math.round(e.memoryUsage/1024/1024):void 0}))},null,2)}]}}catch(t){return e.error(`Process list failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessFind(t){try{let e=A(t.pattern,`pattern`),n=await this.processManager.findProcesses(e);return{content:[{type:`text`,text:JSON.stringify({success:!0,pattern:e,count:n.length,processes:n.map(e=>({pid:e.pid,name:e.name,path:e.executablePath,windowTitle:e.windowTitle,windowHandle:e.windowHandle,memoryMB:e.memoryUsage?Math.round(e.memoryUsage/1024/1024):void 0}))},null,2)}]}}catch(t){return e.error(`Process find failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessGet(t){try{let e=k(t.pid),n=await this.processManager.getProcessByPid(e);if(!n)return{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Process with PID ${e} not found`},null,2)}]};let r=await this.processManager.getProcessCommandLine(e),i=await this.processManager.checkDebugPort(e,{commandLine:r.commandLine});return{content:[{type:`text`,text:JSON.stringify({success:!0,process:{...n,commandLine:r.commandLine,parentPid:r.parentPid,debugPort:i}},null,2)}]}}catch(t){return e.error(`Process get failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessWindows(t){try{let e=k(t.pid),n=await this.processManager.getProcessWindows(e);return{content:[{type:`text`,text:JSON.stringify({success:!0,pid:e,windowCount:n.length,windows:n.map(e=>({handle:e.handle,title:e.title,className:e.className,processId:e.processId}))},null,2)}]}}catch(t){return e.error(`Process windows failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessCheckDebugPort(t){try{let e=k(t.pid),n=await this.processManager.checkDebugPort(e);return{content:[{type:`text`,text:JSON.stringify({success:!0,pid:e,debugPort:n,canAttach:n!==null,attachUrl:n?`http://localhost:${n}`:null},null,2)}]}}catch(t){return e.error(`Check debug port failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessLaunchDebug(t){try{let e=A(t.executablePath,`executablePath`),n=b(t,`debugPort`,9222),r=x(t,`args`),i=await this.processManager.launchWithDebug(e,n,r);return i?{content:[{type:`text`,text:JSON.stringify({success:!0,process:{pid:i.pid,name:i.name,path:i.executablePath},debugPort:n,attachUrl:`http://localhost:${n}`},null,2)}]}:{content:[{type:`text`,text:JSON.stringify({success:!1,message:`Failed to launch process`},null,2)}]}}catch(t){return e.error(`Launch debug failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessKill(t){try{let e=k(t.pid),n=await this.processManager.killProcess(e);return{content:[{type:`text`,text:JSON.stringify({success:n,pid:e,message:n?`Process ${e} killed successfully`:`Failed to kill process ${e}`},null,2)}]}}catch(t){return e.error(`Process kill failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async resolveProcessInfo(e){if(e==null)return null;try{let t=await this.processManager.getProcessByPid(e);return t?{pid:t.pid,name:t.name,executablePath:t.executablePath,windowTitle:t.windowTitle,windowHandle:t.windowHandle,memoryUsage:t.memoryUsage}:null}catch{return null}}async queryProtection(e){if(e.pid===void 0||e.pid===null||!e.address)return{info:null,queryFailed:!1};let t=!1,n=null;try{n=await this.memoryManager.checkMemoryProtection(e.pid,e.address)}catch{t=!0}return{info:n,queryFailed:t}}async enumerateModulesSafe(e){if(e==null)return{enumerated:!1,count:null};try{let t=await this.memoryManager.enumerateModules(e);return{enumerated:t.success,count:t.modules?.length??null}}catch{return{enumerated:!1,count:null}}}},de=class{memoryManager;processManager;platform;host;ctx;constructor(e,t){this.memoryManager=e.memoryManager,this.processManager=e.processManager,this.platform=e.platform,this.host=t,this.ctx=e.ctx}async handleMemoryRead(t){let n=Date.now();try{let e=await this.resolvePid(t.pid),r=A(t.address,`address`),i=oe(t.size,`size`),a=await this.memoryManager.checkAvailability();if(!a.available)return this.auditedUnavailableResponse({operation:`memory_read`,pid:e,address:r,size:i,startedAt:n,reason:a.reason,extra:{requestedAddress:r,requestedSize:i}});let o=await this.memoryManager.readMemory(e,r,i);return this.auditedResultResponse({operation:`memory_read`,pid:e,address:r,size:i,startedAt:n,result:o,payload:{success:o.success,data:o.data,error:o.error,pid:e,address:r,size:i,platform:this.platform}})}catch(r){return e.error(`Memory read failed:`,r),this.auditedExceptionResponse({operation:`memory_read`,pid:N(t.pid)??null,address:P(t.address)??null,size:ce(t.size)??null,startedAt:n,error:r})}}async handleMemoryWrite(t){let n=Date.now();try{let e=await this.resolvePid(t.pid),r=A(t.address,`address`),i=A(t.data,`data`),a=F(t.encoding,`encoding`)??`hex`,o=I(i,a),s=await this.memoryManager.checkAvailability();if(!s.available)return this.auditedUnavailableResponse({operation:`memory_write`,pid:e,address:r,size:o,startedAt:n,reason:s.reason,extra:{requestedAddress:r,dataLength:i.length,encoding:a}});let c=await this.memoryManager.writeMemory(e,r,i,a);return this.auditedResultResponse({operation:`memory_write`,pid:e,address:r,size:o,startedAt:n,result:c,payload:{success:c.success,bytesWritten:c.bytesWritten,error:c.error,pid:e,address:r,dataLength:i.length,encoding:a,platform:this.platform}})}catch(r){e.error(`Memory write failed:`,r);let i=P(t.data),a=se(t.encoding)??`hex`;return this.auditedExceptionResponse({operation:`memory_write`,pid:N(t.pid)??null,address:P(t.address)??null,size:i?I(i,a):null,startedAt:n,error:r})}}async handleMemoryScan(t){let n=Date.now();try{let e=await this.resolvePid(t.pid),r=A(t.pattern,`pattern`),i=M(t.patternType),a=t.suspendTarget===!0,o=await this.memoryManager.checkAvailability();if(!o.available)return this.auditedUnavailableResponse({operation:`memory_scan`,pid:e,address:null,size:null,startedAt:n,reason:o.reason,extra:{requestedPattern:r,patternType:i}});let s=await this.memoryManager.scanMemory(e,r,i,a);return this.auditedResultResponse({operation:`memory_scan`,pid:e,address:null,size:null,startedAt:n,result:s,payload:{success:s.success,addresses:s.addresses,error:s.error,pid:e,pattern:r,patternType:i,platform:this.platform}})}catch(r){return e.error(`Memory scan failed:`,r),this.auditedExceptionResponse({operation:`memory_scan`,pid:N(t.pid)??null,address:null,size:null,startedAt:n,error:r})}}async handleMemoryAuditExport(t){try{let e=this.host.exportMemoryAuditEntries(),n=t.clear===!0,r=this.host.getMemoryAuditCount();return n&&this.host.clearMemoryAuditEntries(),this.jsonResponse({success:!0,count:r,cleared:n,entries:e})}catch(t){return e.error(`Memory audit export failed:`,t),this.errorResponse(t)}}async handleMemoryCheckProtection(t){try{let e=await this.resolvePid(t.pid),n=A(t.address,`address`),r=await this.memoryManager.checkMemoryProtection(e,n);return this.jsonResponse(r)}catch(t){return e.error(`Memory check protection failed:`,t),this.errorResponse(t)}}async handleMemoryScanFiltered(t){try{let e=await this.resolvePid(t.pid),n=A(t.pattern,`pattern`),r=this.requireStringArray(t.addresses,`addresses`),i=M(t.patternType),a=await this.memoryManager.checkAvailability();if(!a.available)return this.unavailableResponse(e,a.reason);let o=await this.memoryManager.scanMemoryFiltered(e,n,r,i);return this.jsonResponse(o)}catch(t){return e.error(`Memory scan filtered failed:`,t),this.errorResponse(t)}}async handleMemoryBatchWrite(t){try{let e=await this.resolvePid(t.pid),n=this.requirePatches(t.patches),r=await this.memoryManager.checkAvailability();if(!r.available)return this.unavailableResponse(e,r.reason);let i=await this.memoryManager.batchMemoryWrite(e,n);return this.jsonResponse(i)}catch(t){return e.error(`Memory batch write failed:`,t),this.errorResponse(t)}}async handleMemoryDumpRegion(t){try{let e=await this.resolvePid(t.pid),n=A(t.address,`address`),r=oe(t.size,`size`),i=A(t.outputPath,`outputPath`);this.ensureRelativeOutputPath(i);let a=await this.memoryManager.dumpMemoryRegion(e,n,r,i);return this.jsonResponse(a)}catch(t){return e.error(`Memory dump region failed:`,t),this.errorResponse(t)}}async handleMemoryListRegions(t){try{let e=await this.resolvePid(t.pid),n=await this.memoryManager.enumerateRegions(e);return this.jsonResponse(n)}catch(t){return e.error(`Memory list regions failed:`,t),this.errorResponse(t)}}jsonResponse(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}errorResponse(e){return this.jsonResponse({success:!1,error:this.errorMessage(e)})}errorMessage(e){return e instanceof Error?e.message:String(e)}async resolvePid(e){return await w(e,this.processManager,this.ctx)}async auditedUnavailableResponse(e){let t=e.reason??`Memory operations not available`,n=await this.host.safeBuildMemoryDiagnostics({pid:e.pid,address:e.address??void 0,size:e.size??void 0,operation:e.operation,error:t});return this.host.recordMemoryAudit({operation:e.operation,pid:e.pid,address:e.address,size:e.size,result:`failure`,error:t,durationMs:Date.now()-e.startedAt}),this.jsonResponse({success:!1,message:`Memory operations not available`,reason:e.reason,platform:this.platform,pid:e.pid,...e.extra,diagnostics:n})}async auditedResultResponse(e){let t=e.result.success?void 0:await this.host.safeBuildMemoryDiagnostics({pid:e.pid,address:e.address??void 0,size:e.size??void 0,operation:e.operation,error:e.result.error});return this.host.recordMemoryAudit({operation:e.operation,pid:e.pid,address:e.address,size:e.size,result:e.result.success?`success`:`failure`,error:e.result.error,durationMs:Date.now()-e.startedAt}),e.result.success||(e.payload.diagnostics=t),this.jsonResponse(e.payload)}async auditedExceptionResponse(e){let t=this.errorMessage(e.error),n=await this.host.safeBuildMemoryDiagnostics({pid:e.pid??void 0,address:e.address??void 0,size:e.size??void 0,operation:e.operation,error:t});return this.host.recordMemoryAudit({operation:e.operation,pid:e.pid,address:e.address,size:e.size,result:`failure`,error:t,durationMs:Date.now()-e.startedAt}),this.jsonResponse({success:!1,error:t,diagnostics:n})}unavailableResponse(e,t){return this.jsonResponse({success:!1,message:`Memory operations not available`,reason:t,platform:this.platform,pid:e})}requireStringArray(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array of strings`);return e.map((e,n)=>A(e,`${t}[${n}]`))}requirePatches(e){if(!Array.isArray(e))throw Error(`patches must be an array`);return e.map((e,t)=>{if(typeof e!=`object`||!e)throw Error(`patches[${t}] must be an object`);let n=e,r=F(n.encoding,`patches[${t}].encoding`);return{address:A(n.address,`patches[${t}].address`),data:A(n.data,`patches[${t}].data`),...r?{encoding:r}:{}}})}ensureRelativeOutputPath(e){if(/^[/\\]/.test(e)||/\.\./.test(e)||/^[A-Za-z]:/.test(e))throw Error(`outputPath must be a relative path without parent directory traversal or drive letters`)}};const fe=te(ne);function pe(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}function me(e){let t=`/proc/${pe(e)}/task`,n;try{n=ee(t)}catch(e){throw Error(`Cannot read ${t}: ${e instanceof Error?e.message:String(e)} (process may not exist, or lacks permission — run as root / CAP_SYS_PTRACE)`,{cause:e})}return n.filter(e=>/^\d+$/.test(e)).map(e=>parseInt(e,10)).toSorted((e,t)=>e-t)}async function he(e){let t=pe(e),n;try{n=(await fe(`ps -M -p ${t}`,{maxBuffer:1024*1024})).stdout}catch(e){throw Error(`ps -M -p ${t} failed: ${e instanceof Error?e.message:String(e)} (process may not exist, or ps unavailable)`,{cause:e})}let r=[];for(let e of n.split(`
2
+ `)){let t=e.trim();if(!t)continue;let n=t.match(/^(0x[0-9a-fA-F]+)\b/);if(n?.[1]){let e=parseInt(n[1],16);Number.isFinite(e)&&e>0&&r.push(e)}}return r.toSorted((e,t)=>e-t)}async function ge(e,t){switch(e){case`linux`:return me(t);case`darwin`:return he(t);default:throw Error(`Thread enumeration not supported on platform "${e}"`)}}const _e={R:`Running`,S:`Sleeping`,D:`Disk sleep`,Z:`Zombie`,T:`Stopped`,t:`Tracing stop`,I:`Idle`,P:`Parked`};function ve(e,t){let n={};t&&t.length>0&&(n.name=t);for(let t of e.split(`
3
+ `)){let e=t.match(/^(\w+):\s*(.*)$/);if(!e)continue;let r=e[1],i=(e[2]??``).trim();if(r===`State`){let e=i.match(/^([A-Za-z])\s*(.*)$/);if(e){let t=e[1];n.state=t,n.stateName=_e[t]??e[2]}}else if(r===`voluntary_ctxt_switches`){let e=Number(i);Number.isFinite(e)&&(n.voluntarySwitches=e)}else if(r===`nonvoluntary_ctxt_switches`){let e=Number(i);Number.isFinite(e)&&(n.nonvoluntarySwitches=e)}}return n}async function ye(e,t){try{let n=`/proc/${e}/task/${t}`,r=await D(`${n}/status`,`utf-8`),i;try{i=(await D(`${n}/comm`,`utf-8`)).trim()}catch{}return ve(r,i)}catch{return{}}}const be=5e4,L=new Set([`eval`,`Function`,`require`,`process`,`__dirname`,`__filename`,`global`,`import`,`constructor`,`__proto__`]),xe=[{object:`window`,property:`constructor`},{object:`Object`,property:`constructor`},{object:`Array`,property:`constructor`},{object:`String`,property:`constructor`}],Se=new Set([`AsyncFunction`,`GeneratorFunction`,`AsyncGeneratorFunction`]);function Ce(e){if(!e||e.trim().length===0)return{valid:!1,error:`Empty expression not allowed`};if(e.length>be)return{valid:!1,error:`Expression too long (max ${be} chars)`};try{let t=re.parse(e,{sourceType:`script`,errorRecovery:!1}),n=null;return ie(t,{Identifier(e){let t=e.node.name;if(L.has(t)){let r=e.parent,i=r.type===`MemberExpression`&&r.property===e.node,a=r.type===`ObjectProperty`&&r.key===e.node;!i&&!a&&(n=`Access to '${t}' is blocked for security reasons`,e.stop())}Se.has(t)&&(n=`Access to '${t}' is blocked for security reasons`,e.stop())},MemberExpression(e){let t=e.node.object,r=e.node.property;if(t.type===`Identifier`&&r.type===`Identifier`){for(let i of xe)if(t.name===i.object&&r.name===i.property){n=`Access to '${i.object}.${i.property}' is blocked for security reasons`,e.stop();return}}r.type===`Identifier`&&r.name===`constructor`&&(n=`Access to 'constructor' property is blocked for security reasons`,e.stop()),r.type===`Identifier`&&r.name===`__proto__`&&(n=`Access to '__proto__' is blocked for security reasons`,e.stop())},Import(){n=`Dynamic import() is blocked for security reasons`},NewExpression(e){let t=e.node.callee;t.type===`Identifier`&&L.has(t.name)&&(n=`Instantiation of '${t.name}' is blocked for security reasons`,e.stop())},CallExpression(e){let t=e.node.callee;t.type===`Identifier`&&t.name===`eval`&&(n=`Call to 'eval' is blocked for security reasons`,e.stop())}}),n?{valid:!1,error:n}:{valid:!0}}catch(e){return{valid:!1,error:`Expression parsing failed: ${e instanceof Error?e.message:String(e)}`}}}function we(e){return e.replace(/[A-Za-z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*/g,`[PATH]`).replace(/\/(?:home|Users)\/[^/\s]+/g,`[USER_DIR]`).replace(/\/(?:[^/\s]+\/)+[^/\s]+/g,`[PATH]`).replace(/\b(?:Administrator|admin|root|user)\b/gi,`[USER]`)}function R(e){if(e instanceof Error)return e.message;if(typeof e==`object`&&e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)}const z=Number(process.env.JSHOOK_ELECTRON_ATTACH_CONNECT_TIMEOUT_MS)||5e3;async function Te(e){let{default:t}=await import(`rebrowser-puppeteer-core`);try{return await new Promise((n,r)=>{let i=!1,a=setTimeout(()=>{i=!0,r(Error(`Timed out after ${z}ms while connecting to Electron browser endpoint ${e}.`))},z);t.connect({browserWSEndpoint:e,defaultViewport:null}).then(async e=>{if(i){try{await e.disconnect()}catch{}return}i=!0,clearTimeout(a),n(e)}).catch(e=>{i||(i=!0,clearTimeout(a),r(e))})})}catch(t){try{return await r(e,z)}catch(n){throw Error(`Failed to connect to Electron browser endpoint ${e} via both rebrowser-puppeteer and Playwright compatibility fallback. Primary error: ${R(t)}. Fallback error: ${R(n)}.`,{cause:n})}}}var Ee=class{memoryManager;processMgmt;constructor(e,t){this.memoryManager=e.memoryManager,this.processMgmt=t}async handleInjectDll(t){let n=Date.now();try{let e=k(t.pid),r=A(t.dllPath,`dllPath`),i=typeof t.confirmed==`boolean`?t.confirmed:void 0,a=j(t.payloadHash,`payloadHash`),o=le(t.validationMode,`validationMode`),s=await this.memoryManager.injectDll(e,r,{confirmed:i,payloadHash:a,validationMode:o});return this.processMgmt.recordMemoryAudit({operation:`inject_dll`,pid:e,address:r,size:null,result:s.success?`success`:`failure`,error:s.error,durationMs:Date.now()-n}),{content:[{type:`text`,text:JSON.stringify(s,null,2)}]}}catch(r){e.error(`DLL injection failed:`,r);let i=r instanceof Error?r.message:String(r);return this.processMgmt.recordMemoryAudit({operation:`inject_dll`,pid:N(t.pid)??null,address:P(t.dllPath)??null,size:null,result:`failure`,error:i,durationMs:Date.now()-n}),{content:[{type:`text`,text:JSON.stringify({success:!1,error:i},null,2)}]}}}async handleInjectShellcode(t){let n=Date.now();try{let e=k(t.pid),r=A(t.shellcode,`shellcode`),i=F(t.encoding,`encoding`)??`hex`,a=typeof t.confirmed==`boolean`?t.confirmed:void 0,o=le(t.validationMode,`validationMode`),s=I(r,i),c=await this.memoryManager.injectShellcode(e,r,i,{confirmed:a,validationMode:o});return this.processMgmt.recordMemoryAudit({operation:`inject_shellcode`,pid:e,address:null,size:s,result:c.success?`success`:`failure`,error:c.error,durationMs:Date.now()-n}),{content:[{type:`text`,text:JSON.stringify(c,null,2)}]}}catch(r){e.error(`Shellcode injection failed:`,r);let i=r instanceof Error?r.message:String(r),a=P(t.shellcode),o=se(t.encoding)??`hex`;return this.processMgmt.recordMemoryAudit({operation:`inject_shellcode`,pid:N(t.pid)??null,address:null,size:a?I(a,o):null,result:`failure`,error:i,durationMs:Date.now()-n}),{content:[{type:`text`,text:JSON.stringify({success:!1,error:i},null,2)}]}}}async handleCheckDebugPort(t){try{let e=k(t.pid),n=await this.memoryManager.checkDebugPort(e);return{content:[{type:`text`,text:JSON.stringify({success:n.success,pid:e,isDebugged:n.isDebugged??null,error:n.error},null,2)}]}}catch(t){return e.error(`check_debug_port failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleEnumerateModules(t){try{let e=k(t.pid),n=await this.memoryManager.enumerateModules(e);return{content:[{type:`text`,text:JSON.stringify({success:n.success,pid:e,moduleCount:n.modules?.length??0,modules:n.modules??[],error:n.error},null,2)}]}}catch(t){return e.error(`enumerate_modules failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleProcessEnumThreads(t){try{let e=k(t.pid);if(t.includeDetails!==void 0&&t.includeDetails!==null&&typeof t.includeDetails!=`boolean`)throw Error(`includeDetails must be a boolean when provided`);let n=t.includeDetails===!0,r=this.processMgmt.platformValue,i;if(r===`win32`){let{EnumerateProcessThreads:t}=await import(`./Win32Debug-6yzmtv5b.mjs`);i=t(e)}else i=await ge(r,e);let a=n?await Promise.all(i.map(async(t,n)=>({threadId:t,ordinal:n,isProcessMainThread:t===e,...r===`win32`?{}:await ye(e,t)}))):void 0,o=n?await this.processMgmt.safeBuildMemoryDiagnostics({pid:e,operation:`process_enum_threads`}):void 0;return{content:[{type:`text`,text:JSON.stringify({success:!0,pid:e,platform:r,threadCount:i.length,threadIds:i,...n?{threads:a,diagnostics:o}:{}},null,2)}]}}catch(t){return e.error(`process_enum_threads failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:t instanceof Error?t.message:String(t)},null,2)}]}}}async handleElectronAttach(t){let n=t.port??9229,r=Number(n);if(!Number.isInteger(r)||r<1||r>65535)return{content:[{type:`text`,text:JSON.stringify({success:!1,error:`Invalid port: ${JSON.stringify(n)}. Must be integer 1-65535.`})}]};let i=j(t.wsEndpoint,`wsEndpoint`)??``,a=j(t.evaluate,`evaluate`)??``,o=j(t.pageUrl,`pageUrl`)??``;try{let t=`http://127.0.0.1:${r}`,n=await this.fetchCdpTargets(t);if(!Array.isArray(n))throw Error(`CDP target list is not an array`);let s=o?n.filter(e=>e.url.includes(o)):n;if(!a)return{content:[{type:`text`,text:JSON.stringify({total:n.length,filtered:s.length,pages:s.map(e=>({id:e.id,title:e.title,url:e.url,type:e.type,wsUrl:e.webSocketDebuggerUrl}))},null,2)}]};let c=Ce(a);if(!c.valid)return e.warn(`electron_attach: blocked expression - ${c.error}`),{content:[{type:`text`,text:JSON.stringify({success:!1,error:c.error},null,2)}]};let l=s[0];if(!l?.webSocketDebuggerUrl)return{content:[{type:`text`,text:`No matching page found (pageUrl filter: "${o}"). Available targets:\n`+n.map(e=>` [${e.type}] ${e.title} — ${e.url}`).join(`
4
+ `)}]};let u=await this.resolveBrowserWsEndpoint(t,i,l);if(!u)throw Error(`Could not determine browser WebSocket endpoint`);let d=await Te(u),f,p;try{let e=await d.pages(),t=e.find(e=>e.url().includes(l.url))??e[0];if(!t)throw Error(`Could not get page from connected browser`);let n=await t.evaluate(e=>{try{return{ok:!0,result:(0,eval)(e)}}catch(e){let t=typeof e==`object`&&e?e:{};return{ok:!1,error:{name:t.name||`Error`,message:String(t.message||e),stack:t.stack?String(t.stack):void 0}}}},a);n?.ok?f=n.result:p=we(`Evaluation failed: ${n?.error?.name||`Error`}: ${n?.error?.message||`Unknown error`}`)}finally{await d.disconnect()}return p?{content:[{type:`text`,text:JSON.stringify({success:!1,error:p,target:{title:l.title,url:l.url}},null,2)}]}:(e.info(`electron_attach: evaluated in ${l.title}`),{content:[{type:`text`,text:JSON.stringify({success:!0,target:{title:l.title,url:l.url},result:f},null,2)}]})}catch(t){return e.error(`electron_attach failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:R(t)},null,2)}]}}}async fetchCdpTargets(e){let t=`${e}/json/list`;try{let e=await fetch(t);if(!e.ok)throw Error(`CDP list endpoint returned HTTP ${e.status}`);return await e.json()}catch(t){try{let n=await fetch(`${e}/json`);if(!n.ok)throw Error(`CDP fallback endpoint returned HTTP ${n.status}`,{cause:t});return await n.json()}catch(n){let r=R(n||t);throw Error(`Cannot connect to Electron CDP at ${e}. Ensure the target app is running with a remote debugging port (for example: process_launch_debug with debugPort=${e.split(`:`).pop()}), then retry electron_attach. Original error: ${r}`,{cause:n})}}}async resolveBrowserWsEndpoint(e,t,n){if(t)return t;try{let t=await fetch(`${e}/json/version`);if(t.ok){let e=await t.json();if(e.webSocketDebuggerUrl)return e.webSocketDebuggerUrl}}catch{}if(n.webSocketDebuggerUrl)return n.webSocketDebuggerUrl.replace(/\/devtools\/page\/[^/]+$/,``).replace(`/devtools/page`,`/devtools/browser`)}},De=class{peAnalyzer=new v;processMgmt;constructor(e){this.processMgmt=e}async handleDetectHollowing(e){try{let t=b(e,`pid`);if(!t||t<=0)throw Error(`pid must be a positive integer`);let n=S(e,`autoRestore`,!1),r=S(e,`includeMemoryDump`,!1),i=this.processMgmt?.platformValue??process.platform;return i===`win32`?this.detectHollowingWin32(t,n,r):this.detectHollowingCrossPlatform(t,i)}catch(e){return{success:!1,isHollowed:!1,confidence:0,error:`Unexpected error: ${e instanceof Error?e.message:String(e)}`}}}async detectHollowingWin32(r,i,a){let o=h(r);try{let c=u(o);if(!c.success||c.modules.length===0)return{success:!1,isHollowed:!1,confidence:0,error:`No modules found in target process (process may have exited)`};let l=c.modules[0],p=`0x${l.toString(16)}`,m=s(o,l);if(!m)return{success:!1,isHollowed:!1,confidence:0,error:`Failed to get module path (process may have exited or access denied)`,moduleBase:p};let h=f(o,l);if(!h.success)return{success:!1,isHollowed:!1,confidence:0,error:`Failed to get module information`,moduleBase:p,modulePath:m};let g;try{g=await this.peAnalyzer.compareMemoryWithDisk(r,p,m)}catch(e){return{success:!1,isHollowed:!1,confidence:0,error:`Failed to compare memory with disk: ${e instanceof Error?e.message:String(e)}`,moduleBase:p,modulePath:m}}let _=!g.isMatch,v=!1,y;if(i&&_){e.warn(`[process_detect_hollowing] autoRestore=true for PID ${r} - attempting restoration (HIGH RISK)`);try{v=await this.restoreFromDisk(r,l,m,g.differences)}catch(t){y=`Restoration failed: ${t instanceof Error?t.message:String(t)}`,e.error(`[process_detect_hollowing] Restoration failed for PID ${r}:`,t)}}let b=g.differences.map(e=>({section:e.sectionName,offset:`0x${e.offsetStart.toString(16)}`,size:e.bytesCompared,memoryHash:e.memoryHash.substring(0,16)+`...`,diskHash:e.diskHash.substring(0,16)+`...`})),x;if(a&&_&&g.differences.length>0){let i=t,a=n,s=0,c=!1;try{let{promises:e}=await import(`node:fs`),t=await e.readFile(m),n=this.peAnalyzer.parsePEFromBuffer(t),r=g.differences.slice(0,i);g.differences.length>i&&(c=!0);for(let e=0;e<r.length;e++){let i=r[e],u=b[e],f=Math.min(a,i.bytesCompared);i.bytesCompared>a&&(c=!0),u.memoryBytes=d(o,l+BigInt(i.offsetStart),f).subarray(0,f).toString(`hex`);let p=n.sections.find(e=>e.name===i.sectionName);if(p){let e=p.pointerToRawData+f;u.diskBytes=t.subarray(p.pointerToRawData,e).subarray(0,f).toString(`hex`)}else u.diskBytes=``;s+=f}x={included:!0,truncated:c,totalBytes:s}}catch(t){e.warn(`[process_detect_hollowing] Memory dump collection failed for PID ${r}:`,t),x={included:!0,truncated:!1,totalBytes:0}}}return{success:!0,isHollowed:_,confidence:g.confidence,modulePath:m,moduleBase:p,moduleSizeOfImage:h.info.SizeOfImage,differences:b,memoryDump:x,restored:v,restoreError:y,warning:i?`HIGH RISK: Memory restoration attempted. Target process may crash or behave unexpectedly.`:_?`Process appears to be hollowed. Use autoRestore=true to attempt restoration (HIGH RISK).`:void 0}}finally{p(o)}}async detectHollowingCrossPlatform(e,t){let n;try{n=_()}catch(e){return{success:!1,isHollowed:!1,confidence:0,error:`Cross-platform memory provider unavailable: ${e instanceof Error?e.message:String(e)}`}}let r;try{r=await E(n,e)}catch(e){return{success:!1,isHollowed:!1,confidence:0,error:`Integrity scan failed: ${e instanceof Error?e.message:String(e)}`,platformNote:`Cross-platform fallback (${t}): ELF/Mach-O section hash comparison via IntegrityScanner.`}}let i=r.sections.filter(e=>e.isModified),a=i.length>0;return{success:!0,isHollowed:a,confidence:a?Math.min(95,80+i.length*5):95,platform:t,differences:i.map(e=>({section:e.sectionName,moduleName:e.moduleName,memoryHash:e.memoryHash.substring(0,16)+`...`,diskHash:e.diskHash.substring(0,16)+`...`})),scannedSections:r.stats.scannedSections,skippedSections:r.stats.skippedSections,timedOut:r.stats.timedOut,truncated:r.stats.truncated,restored:!1,platformNote:`Cross-platform fallback (${t}): ELF/Mach-O executable-section SHA-256 comparison via IntegrityScanner. autoRestore is Win32-only.`,warning:a?`${i.length} executable section(s) differ from disk — consistent with process hollowing (or runtime patching / packing). Inspect differences[].moduleName to identify the affected module.`:void 0}}async restoreFromDisk(t,n,r,i){let{promises:a}=await import(`node:fs`),o=await import(`./Win32API-G7QPyckq.mjs`).then(e=>e.v),s=o.openProcessForMemory(t,!0);try{let t=await a.readFile(r),c=this.peAnalyzer.parsePEFromBuffer(t);for(let r of i){let i=c.sections.find(e=>e.name===r.sectionName);if(!i){e.warn(`[restoreFromDisk] Section ${r.sectionName} not found in disk PE, skipping`);continue}let a=t.subarray(i.pointerToRawData,i.pointerToRawData+Math.min(i.sizeOfRawData,r.bytesCompared)),l=n+BigInt(r.offsetStart),{oldProtect:u}=o.VirtualProtectEx(s,l,a.length,o.PAGE.READWRITE);o.WriteProcessMemory(s,l,a),o.VirtualProtectEx(s,l,a.length,u),e.info(`[restoreFromDisk] Restored section ${r.sectionName} (${a.length} bytes) at 0x${l.toString(16)}`)}return!0}catch(t){throw e.error(`[restoreFromDisk] Restoration failed:`,t),t}finally{o.CloseHandle(s)}}};const B=3221225476,Oe=BigInt(`0xffffffffffffffff`),ke=new Set([`File`,`EtwRegistration`,`IoCompletionReserve`,`WaitCompletionPacket`,`IoCompletion`]);let V=null,H=null;function Ae(){return V||=O.load(`kernel32.dll`),V}function U(){return H||=O.load(`ntdll.dll`),H}let W=null;function je(){return W||=U().func(`int32 NtQuerySystemInformation(uint32, _Out_ void *, uint32, _Out_ uint32 *)`),W}let G=null;function K(){return G||=U().func(`int32 NtQueryObject(void *, uint32, _Out_ void *, uint32, _Out_ uint32 *)`),G}let q=null;function Me(){return q||=Ae().func(`int DuplicateHandle(void *, void *, void *, _Out_ void **, uint32, int, uint32)`),q}function Ne(){let e=1048576,t,n;do{t=Buffer.alloc(e);let r=Buffer.alloc(8);n=je()(64,O.address(t),e,O.address(r));let i=n>>>0;if(i===B){let t=r.readUInt32LE(0);if(e=t>0?t*2:e*2,e>536870912)throw Error(`Handle enumeration buffer exceeded 512 MB`)}else if(i===3221225506)throw new Re(`NtQuerySystemInformation(SystemExtendedHandleInformation) requires elevated privileges (SeDebugPrivilege). Run as Administrator.`);else if(n<0)throw Error(`NtQuerySystemInformation failed with NTSTATUS 0x${i.toString(16)}`)}while(n>>>0==B);let r=Number(t.readBigUInt64LE(0));return{buffer:t,totalHandles:r}}function Pe(e,t){let n=Number(e.readBigUInt64LE(0)),r=[];for(let i=0;i<n;i++){let n=16+i*40;if(n+40>e.length)break;let a=Number(e.readBigUInt64LE(n+8)),o=Number(e.readBigUInt64LE(n+16)),s=e.readUInt16LE(n+30);t!==void 0&&a!==t||o!==0&&r.push({object:e.readBigUInt64LE(n+0),processId:a,handleValue:o,grantedAccess:e.readUInt32LE(n+24),objectTypeIndex:s,handleAttributes:e.readUInt32LE(n+32)})}return r}function Fe(e){let t=1024,n=Buffer.alloc(t),r=Buffer.alloc(8);if(K()(e,2,O.address(n),t,O.address(r))<0)return`Unknown`;let i=n.readUInt16LE(0);if(i===0)return`Unknown`;try{return n.toString(`utf16le`,16,16+i)}catch{return`Unknown`}}function Ie(e){let t=4096,n,r;do{n=Buffer.alloc(t);let i=Buffer.alloc(8);if(r=K()(e,1,O.address(n),t,O.address(i)),r>>>0==B){let e=i.readUInt32LE(0);if(t=e>0?e+256:t*2,t>1048576)break}else if(r<0)return``}while(r>>>0==B);if(r<0)return``;let i=n.readUInt16LE(0);if(i===0)return``;try{return n.toString(`utf16le`,16,16+i)}catch{return``}}function J(e,t){let n=Buffer.alloc(8);return Me()(e,BigInt(t),Oe,O.address(n),0,0,2)===0?0n:n.readBigUInt64LE(0)}function Le(e,t){let n=new Map,r=new Set;for(let i of e){if(r.has(i.objectTypeIndex))continue;r.add(i.objectTypeIndex);let e=J(t,i.handleValue);if(e!==0n)try{let t=Fe(e);n.set(i.objectTypeIndex,t)}finally{p(e)}}return n}var Re=class extends Error{constructor(e){super(e),this.name=`HandleElevationError`}};function ze(e,t={}){if(!o())return{success:!1,entries:[],totalSystemHandles:0,typeIndexCache:new Map,error:`process_enum_handles is only available on Windows`};let n=t.includeNames!==!1,r=t.filterType?.toLowerCase();try{let{buffer:t,totalHandles:i}=Ne(),a=Pe(t,e),o;try{o=m(l.DUP_HANDLE,!1,e)}catch{try{o=m(l.QUERY_LIMITED_INFORMATION,!1,e)}catch{return{success:!1,entries:[],totalSystemHandles:i,typeIndexCache:new Map,error:`Cannot open process ${e}. Run as Administrator.`,requiresElevation:!0}}}try{let e=Le(a,o),t=[];for(let i of a){let a=e.get(i.objectTypeIndex)??`Unknown`;if(r&&a.toLowerCase()!==r)continue;let s=``;if(n&&!ke.has(a)){let e=J(o,i.handleValue);if(e!==0n)try{s=Ie(e)}finally{p(e)}}t.push({...i,typeName:a,objectName:s})}return{success:!0,entries:t,totalSystemHandles:i,typeIndexCache:e}}finally{p(o)}}catch(e){return e instanceof Re?{success:!1,entries:[],totalSystemHandles:0,typeIndexCache:new Map,error:e.message,requiresElevation:!0}:{success:!1,entries:[],totalSystemHandles:0,typeIndexCache:new Map,error:`Handle enumeration failed: ${e instanceof Error?e.message:String(e)}`}}}const Y={PROCESS_TERMINATE:1,PROCESS_CREATE_THREAD:2,PROCESS_SET_SESSIONID:4,PROCESS_VM_OPERATION:8,PROCESS_VM_READ:16,PROCESS_VM_WRITE:32,PROCESS_DUP_HANDLE:64,PROCESS_CREATE_PROCESS:128,PROCESS_SET_QUOTA:256,PROCESS_SET_INFORMATION:512,PROCESS_QUERY_INFORMATION:1024,PROCESS_SUSPEND_RESUME:2048,PROCESS_QUERY_LIMITED_INFORMATION:4096,SYNCHRONIZE:1048576,PROCESS_ALL_ACCESS:2097151},Be={THREAD_TERMINATE:1,THREAD_SUSPEND_RESUME:2,THREAD_GET_CONTEXT:8,THREAD_SET_CONTEXT:16,THREAD_SET_INFORMATION:32,THREAD_QUERY_INFORMATION:64,THREAD_SET_THREAD_TOKEN:128,THREAD_IMPERSONATE:256,THREAD_DIRECT_IMPERSONATION:512,SYNCHRONIZE:1048576,THREAD_ALL_ACCESS:2032639},X={TOKEN_ASSIGN_PRIMARY:1,TOKEN_DUPLICATE:2,TOKEN_IMPERSONATE:4,TOKEN_QUERY:8,TOKEN_QUERY_SOURCE:16,TOKEN_ADJUST_PRIVILEGES:32,TOKEN_ADJUST_GROUPS:64,TOKEN_ADJUST_DEFAULT:128,TOKEN_ADJUST_SESSIONID:256,TOKEN_ALL_ACCESS:8447},Ve={FILE_READ_DATA:1,FILE_WRITE_DATA:2,FILE_APPEND_DATA:4,FILE_READ_EA:8,FILE_WRITE_EA:16,FILE_EXECUTE:32,FILE_READ_ATTRIBUTES:128,FILE_WRITE_ATTRIBUTES:256,DELETE:65536,READ_CONTROL:131072,WRITE_DAC:262144,WRITE_OWNER:524288,SYNCHRONIZE:1048576,FILE_ALL_ACCESS:2032127},He=[`\\SAM`,`\\SECURITY`,`\\SYSTEM`,`\\Device\\Condrv`,`lsass.exe`,`winlogon.exe`,`wininit.exe`,`csrss.exe`,`services.exe`];function Ue(e,t){let n=`0x${(e>>>0).toString(16).padStart(8,`0`)}`,r=[],i;switch(t){case`Process`:i=Y;break;case`Thread`:i=Be;break;case`Token`:i=X;break;case`File`:i=Ve;break;default:i={DELETE:65536,READ_CONTROL:131072,WRITE_DAC:262144,WRITE_OWNER:524288,SYNCHRONIZE:1048576,ACCESS_SYSTEM_SECURITY:16777216}}let a=Object.keys(i).find(e=>e.endsWith(`_ALL_ACCESS`));if(a){let t=i[a];if((e&t)===t)return r.push(a),r}for(let[t,n]of Object.entries(i))t.endsWith(`_ALL_ACCESS`)||(e&n)===n&&r.push(t);return r.length===0&&r.push(n),r}function We(e,t,n){let r=e.grantedAccess,i=!!(e.handleAttributes&2);if(t===`Process`){let t=He.some(e=>n.toLowerCase().includes(e.toLowerCase())),i=(r&Y.PROCESS_ALL_ACCESS)===Y.PROCESS_ALL_ACCESS,a=(r&(Y.PROCESS_VM_WRITE|Y.PROCESS_DUP_HANDLE))!==0;if(t&&i)return{severity:`critical`,handleValue:e.handleValue,riskType:`HIGH_ACCESS_TO_SENSITIVE_PROCESS`,description:`Full access to sensitive process: ${n}`};if(t&&a)return{severity:`high`,handleValue:e.handleValue,riskType:`DANGEROUS_ACCESS_TO_SENSITIVE_PROCESS`,description:`VM_WRITE/DUP_HANDLE access to sensitive process: ${n}`}}if(t===`Token`){let t=(r&X.TOKEN_DUPLICATE)!==0,n=(r&X.TOKEN_IMPERSONATE)!==0,i=(r&X.TOKEN_ADJUST_PRIVILEGES)!==0;if(t&&n)return{severity:`critical`,handleValue:e.handleValue,riskType:`TOKEN_DUPLICATE_IMPERSONATE`,description:`Token with TOKEN_DUPLICATE + TOKEN_IMPERSONATE: potential privilege escalation via token impersonation`};if(i)return{severity:`high`,handleValue:e.handleValue,riskType:`TOKEN_ADJUST_PRIVILEGES`,description:`Token with TOKEN_ADJUST_PRIVILEGES: can enable SeDebugPrivilege or equivalent`}}if(i&&(t===`Process`||t===`Token`||t===`Key`))return{severity:`medium`,handleValue:e.handleValue,riskType:`INHERITABLE_SENSITIVE_HANDLE`,description:`Inheritable ${t} handle: will be inherited by child processes. Name: ${n||`(unnamed)`}`};if(t===`Section`&&n){let t=n.toLowerCase().endsWith(`.exe`)||n.toLowerCase().endsWith(`.dll`),i=(r&2)!=0||(r&4)!=0;if(t&&i)return{severity:`high`,handleValue:e.handleValue,riskType:`SECTION_TO_EXECUTABLE`,description:`Section handle to executable file with write/execute access: ${n}`}}}var Ge=class{processMgmt;constructor(e){this.processMgmt=e}async handleProcessEnumHandles(t){try{let e=b(t,`pid`);if(!e||e<=0)return{success:!1,pid:e??0,totalHandles:0,filteredHandles:0,typeSummary:{},handles:[],securityFindings:[],error:`pid must be a positive integer`};if(this.processMgmt.platformValue!==`win32`)return{success:!1,pid:e,totalHandles:0,filteredHandles:0,typeSummary:{},handles:[],securityFindings:[],error:`process_enum_handles is only available on Windows`};let n=y(t,`filterType`,``),r=S(t,`includeNames`,!0),i=S(t,`securityOnly`,!1),a=ze(e,{includeNames:r,filterType:n||void 0});if(!a.success)return{success:!1,pid:e,totalHandles:0,filteredHandles:0,typeSummary:{},handles:[],securityFindings:[],error:a.error,requiresElevation:a.requiresElevation};let o={};for(let e of a.entries){let t=e.typeName;o[t]=(o[t]??0)+1}let s=[],c=[];for(let e of a.entries){let t=We(e,e.typeName,e.objectName);if(i&&!t)continue;let n=Ue(e.grantedAccess,e.typeName);c.push({handleValue:e.handleValue,typeName:e.typeName,objectName:e.objectName,grantedAccess:`0x${(e.grantedAccess>>>0).toString(16).padStart(8,`0`)}`,grantedAccessDecoded:n,handleAttributes:e.handleAttributes,inheritable:!!(e.handleAttributes&2),securityRisk:t?.riskType}),t&&s.push(t)}let l;a.entries.length>500&&(l=`Process has ${a.entries.length} handles. Showing first 500. Use filterType or securityOnly to narrow results.`);let u=!i&&!n?c.slice(0,500):c;return{success:!0,pid:e,totalSystemHandles:a.totalSystemHandles,totalHandles:a.entries.length,filteredHandles:u.length,typeSummary:o,handles:u,securityFindings:s,warning:l}}catch(n){return e.error(`[handleProcessEnumHandles] failed:`,n),{success:!1,pid:b(t,`pid`)??0,totalHandles:0,filteredHandles:0,typeSummary:{},handles:[],securityFindings:[],error:`Unexpected error: ${n instanceof Error?n.message:String(n)}`}}}};const Ke=3221225476;let qe=null;function Je(){return qe||=g().func(`int32 NtQueryInformationThread(void *, uint32, _Out_ void *, uint32, _Out_ uint32 *)`),qe}let Ye=null;function Xe(){return Ye||=c().func(`void * OpenThread(uint32, int32, uint32)`),Ye}let Ze=null;function Qe(){return Ze||=c().func(`void * CreateToolhelp32Snapshot(uint32, uint32)`),Ze}let $e=null;function et(){return $e||=c().func(`int32 Thread32First(void *, _Out_ void *)`),$e}let tt=null;function nt(){return tt||=c().func(`int32 Thread32Next(void *, _Out_ void *)`),tt}let Z=null;function rt(){return Z||=c().func(`int32 CloseHandle(void *)`),Z}function it(e){return typeof e==`bigint`?e:typeof e==`number`?BigInt(e):0n}function at(e){let t=it(Qe()(4,0));if(t===0n||t===BigInt(`0xFFFFFFFFFFFFFFFF`))return[];let n=Buffer.alloc(28);n.writeUInt32LE(28,0);let r=[],i=et()(t,O.address(n));for(;i;){let a=n.readUInt32LE(12);a===e&&r.push({threadId:n.readUInt32LE(8),ownerPid:a,tpBasePri:n.readUInt32LE(16)}),i=nt()(t,O.address(n))}return rt()(t),r}function ot(e){let t=it(Xe()(2112,0,e));if(t===0n||t===BigInt(`0xFFFFFFFFFFFFFFFF`))return null;try{let n={threadId:e,hasPendingApc:!1,kernelApcCount:0,userApcCount:null,isAlertable:!1,startAddress:`0x0`},r=Buffer.alloc(256),i=Buffer.alloc(4),a=Je()(t,0,O.address(r),r.length,O.address(i));(a===0||a===Ke)&&(n.hasPendingApc=a===Ke,n.kernelApcCount=r.readUInt32LE(0)&3,n.userApcCount=+!!n.hasPendingApc);let o=Buffer.alloc(8),s=Buffer.alloc(4);return Je()(t,9,O.address(o),o.length,O.address(s))===0&&(n.startAddress=`0x${o.readBigUInt64LE(0).toString(16)}`),n.isAlertable=n.hasPendingApc&&(n.userApcCount??0)>0,n}finally{rt()(t)}}function st(e){try{let t=at(e);if(t.length===0)return{success:!1,pid:e,error:`No threads found for PID ${e} (process may have exited or access denied)`,threadCount:0,suspiciousThreads:0,apcThreads:[],verdict:`clean`,confidence:0,riskReasons:[],requiresElevation:!0};let n=[],r=[];for(let e of t){let t=ot(e.threadId);t&&t.hasPendingApc&&(n.push(t),t.isAlertable?r.push(`Thread ${e.threadId}: pending user-mode APC(s) + alertable wait — likely injection target`):t.kernelApcCount>0&&r.push(`Thread ${e.threadId}: pending kernel-mode APC(s) — possible injection or system event`))}let i=n.length,a=`clean`,o=0;return i===0?(a=`clean`,o=95):i<=2&&r.every(e=>e.includes(`kernel-mode`))?(a=`clean`,o=70):i<=2?(a=`suspicious`,o=60):(a=`infected`,o=Math.min(85,50+i*5)),{success:!0,pid:e,threadCount:t.length,suspiciousThreads:i,apcThreads:n,verdict:a,confidence:o,riskReasons:r,requiresElevation:i===0&&t.length>0?!1:void 0}}catch(t){return{success:!1,pid:e,error:t instanceof Error?t.message:String(t),threadCount:0,suspiciousThreads:0,apcThreads:[],verdict:`clean`,confidence:0,riskReasons:[],requiresElevation:!0}}}var ct=class{deps;constructor(e){this.deps=e}async handleProcessDetectApc(e){try{let t=b(e,`pid`);if(!t||t<=0||!Number.isInteger(t))return{success:!1,error:`pid must be a positive integer`};if(process.platform!==`win32`)return{success:!1,error:`APC injection detection is Windows-only (requires NtQueryInformationThread)`,platform:process.platform};let n=st(t);if(this.deps?.auditTrail)try{this.deps.auditTrail.record({operation:`process_detect_apc`,pid:t,address:BigInt(0),size:0,result:n.success?`success`:`failure`,error:n.error})}catch{}return n}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}},lt=class{processMgmt;constructor(e){this.processMgmt=e}async handleProcessSuspend(e){let t=b(e,`pid`);if(!t||t<=0)return{success:!1,error:`pid must be a positive integer`};let n=this.processMgmt?.platformValue??process.platform;try{let{suspendProcess:e}=await import(`./native-D9ouskXO.mjs`).then(e=>e.r),r=await e(n,t);return{success:!0,pid:t,suspended:r,platform:n,message:r?`Suspended process ${t}`:`Failed to suspend process ${t} (already exited? permissions?)`}}catch(e){return{success:!1,pid:t,error:String(e)}}}async handleProcessResume(e){let t=b(e,`pid`);if(!t||t<=0)return{success:!1,error:`pid must be a positive integer`};let n=this.processMgmt?.platformValue??process.platform;try{let{resumeProcess:e}=await import(`./native-D9ouskXO.mjs`).then(e=>e.r);return await e(n,t),{success:!0,pid:t,resumed:!0,platform:n}}catch(e){return{success:!1,pid:t,error:String(e)}}}};const ut=/^([0-9a-f]+)-([0-9a-f]+)\s+([r-][w-][x][sp-]?)\s+([0-9a-f]+)\s+([0-9a-f]+:[0-9a-f]+)\s+(\d+)\s*(.*)$/;function dt(e){let t=e.trim().match(ut);return t?{start:t[1],end:t[2],perms:t[3],offset:t[4],dev:t[5],inode:t[6],pathname:(t[7]??``).trim()}:null}function ft(e){return e.split(`
5
+ `).map(dt).filter(e=>e!==null)}function pt(e){let t=[];for(let n of e)(n.perms===`rwx`||n.perms===`rwxp`)&&t.push({type:`rwx_memory_region`,severity:`high`,description:`RWX memory region at 0x${n.start}-0x${n.end}${n.pathname?` (${n.pathname})`:``}`,detail:{start:`0x${n.start}`,end:`0x${n.end}`,perms:n.perms,pathname:n.pathname||null,inode:n.inode}});return t}function mt(e){let t=[];return e.includes(`(deleted)`)&&t.push({type:`deleted_backing_file`,severity:`critical`,description:`Process executable has been deleted from disk: ${e}`,detail:{exeLink:e}}),t}function Q(e,t){return e[t]|e[t+1]<<8}function $(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function ht(e,t){let n=[];for(let r=0;r<8;r++){let i=e[t+r];if(i===0)break;n.push(i)}return String.fromCharCode(...n)}function gt(e){if(e.length<64)return null;let t=Q(e,0);if(t!==23117)return null;let n=$(e,60);if(n<64||n>e.length-4||$(e,n)!==17744)return null;let r=n+4,i=Q(e,r),a=Q(e,r+2),o=$(e,r+4),s=$(e,r+8),c=$(e,r+12),l=Q(e,r+16),u=Q(e,r+18),d=r+20,f=Q(e,d),p=f===523,m,h,g,_,v,y,b,x,S,C;if(p){m=$(e,d+16),h=$(e,d+24),g=$(e,d+32),_=$(e,d+36),v=$(e,d+56),y=$(e,d+60),b=$(e,d+64),x=Q(e,d+68),S=Q(e,d+70);let t=$(e,d+72),n=$(e,d+76);C=BigInt(t)|BigInt(n)<<32n}else m=$(e,d+16),h=$(e,d+28),g=$(e,d+32),_=$(e,d+36),v=$(e,d+56),y=$(e,d+60),b=$(e,d+64),x=Q(e,d+68),S=Q(e,d+70),C=$(e,d+72);let w={magic:f,entryPointAddress:m,imageBase:h,sectionAlignment:g,fileAlignment:_,sizeOfImage:v,sizeOfHeaders:y,checksum:b,subsystem:x,dllCharacteristics:S,sizeOfStackReserve:C},T=d+l,E=[];for(let t=0;t<a;t++){let n=T+t*40;if(n+40>e.length)break;E.push({name:ht(e,n),virtualSize:$(e,n+8),virtualAddress:$(e,n+12),sizeOfRawData:$(e,n+16),pointerToRawData:$(e,n+20),characteristics:$(e,n+36)})}return{dosHeader:{e_magic:t,e_lfanew:n},coffHeader:{machine:i,numberOfSections:a,timeDateStamp:o,pointerToSymbolTable:s,numberOfSymbols:c,sizeOfOptionalHeader:l,characteristics:u},optionalHeader:w,sections:E,is64bit:p}}const _t=new Set([`.text`,`.rdata`,`.data`,`.pdata`,`.rsrc`,`.reloc`,`.edata`,`.idata`,`.bss`,`.tls`,`.xdata`,`.00cfg`,`.didat`,`.gehcont`,`.gfids`,`.giats`,`.gljmp`,`.glhsh`,`.mrdata`,`INIT`,`PAGE`,`.CRT`]);function vt(e){let t=[];for(let n of e.sections){let e=n.name;if(e.length===0||/[^\x20-\x7e]/.test(e)){t.push({type:`suspicious_section_name`,severity:`medium`,description:`PE section with non-printable or empty name at VA 0x${n.virtualAddress.toString(16)}`,detail:{sectionName:e||`(empty)`,virtualAddress:`0x${n.virtualAddress.toString(16)}`,characteristics:`0x${n.characteristics.toString(16)}`}});continue}[..._t].some(t=>e.startsWith(t))||t.push({type:`suspicious_section_name`,severity:`low`,description:`Non-standard PE section "${e}" at VA 0x${n.virtualAddress.toString(16)}`,detail:{sectionName:e,virtualAddress:`0x${n.virtualAddress.toString(16)}`,characteristics:`0x${n.characteristics.toString(16)}`,note:`May be compiler-specific. Review if unexpected.`}});let r=(n.characteristics&536870912)!=0;n.characteristics&2147483648&&r&&t.push({type:`rwx_memory_region`,severity:`high`,description:`PE section "${e}" has Writable+Executable characteristics (RWX) at VA 0x${n.virtualAddress.toString(16)}`,detail:{sectionName:e,virtualAddress:`0x${n.virtualAddress.toString(16)}`,characteristics:`0x${n.characteristics.toString(16)}`}})}return t}function yt(e){let t=[];if(!e.expectedImagePath||!e.peInfo)return t;let n=e.expectedImagePath.toLowerCase();for(let r of[`svchost.exe`,`explorer.exe`,`lsass.exe`,`csrss.exe`,`winlogon.exe`,`services.exe`,`spoolsv.exe`,`rundll32.exe`])if(n.includes(r)&&n.includes(`\\windows\\`)){t.push({type:`mismatched_binary_path`,severity:`medium`,description:`Process claims to be ${r} in Windows system directory — common hollowing target. Verify PE section hashes in memory.`,detail:{imagePath:e.expectedImagePath,peMachine:e.peInfo.coffHeader.machine,peTimestamp:new Date(e.peInfo.coffHeader.timeDateStamp*1e3).toISOString(),note:`Static check only. Use process_detect_hollowing for live section comparison.`}});break}return t}function bt(e){let t=[],n=e.optionalHeader.entryPointAddress;n===0&&t.push({type:`entry_point_mismatch`,severity:`critical`,description:`PE entry point is 0 — binary cannot execute normally`,detail:{entryPoint:0}});let r=!1;for(let t of e.sections)if(n>=t.virtualAddress&&n<t.virtualAddress+t.virtualSize){r=!0;break}return!r&&n!==0&&t.push({type:`entry_point_mismatch`,severity:`medium`,description:`PE entry point 0x${n.toString(16)} falls outside all section boundaries`,detail:{entryPoint:`0x${n.toString(16)}`,sections:e.sections.map(e=>({name:e.name,va:`0x${e.virtualAddress.toString(16)}`,size:e.virtualSize}))}}),t}function xt(e,t){let n=[],r=[];e.optionalHeader.sizeOfImage!==t.optionalHeader.sizeOfImage&&r.push(`SizeOfImage: disk=0x${e.optionalHeader.sizeOfImage.toString(16)} memory=0x${t.optionalHeader.sizeOfImage.toString(16)}`),e.coffHeader.numberOfSections!==t.coffHeader.numberOfSections&&r.push(`Section count: disk=${e.coffHeader.numberOfSections} memory=${t.coffHeader.numberOfSections}`),e.optionalHeader.entryPointAddress!==t.optionalHeader.entryPointAddress&&r.push(`EntryPoint: disk=0x${e.optionalHeader.entryPointAddress.toString(16)} memory=0x${t.optionalHeader.entryPointAddress.toString(16)}`),e.coffHeader.machine!==t.coffHeader.machine&&r.push(`Machine: disk=0x${e.coffHeader.machine.toString(16)} memory=0x${t.coffHeader.machine.toString(16)}`),e.optionalHeader.subsystem!==t.optionalHeader.subsystem&&r.push(`Subsystem: disk=${e.optionalHeader.subsystem} memory=${t.optionalHeader.subsystem}`),e.optionalHeader.imageBase!==t.optionalHeader.imageBase&&r.push(`ImageBase: disk=0x${e.optionalHeader.imageBase.toString(16)} memory=0x${t.optionalHeader.imageBase.toString(16)}`);let i=new Map(e.sections.map(e=>[e.name,e])),a=new Map(t.sections.map(e=>[e.name,e]));for(let[e,t]of i){let n=a.get(e);if(!n){r.push(`Section "${e}" exists on disk but missing in memory`);continue}t.virtualSize!==n.virtualSize&&r.push(`Section "${e}" virtualSize: disk=0x${t.virtualSize.toString(16)} memory=0x${n.virtualSize.toString(16)}`),t.characteristics!==n.characteristics&&r.push(`Section "${e}" characteristics: disk=0x${t.characteristics.toString(16)} memory=0x${n.characteristics.toString(16)}`)}return r.length>0&&n.push({type:`pe_memory_mismatch`,severity:`high`,description:`PE header mismatch between disk and memory: ${r.join(`; `)}`,detail:{mismatches:r,diskSizeOfImage:`0x${e.optionalHeader.sizeOfImage.toString(16)}`,memorySizeOfImage:`0x${t.optionalHeader.sizeOfImage.toString(16)}`,diskSections:e.coffHeader.numberOfSections,memorySections:t.coffHeader.numberOfSections}}),n}function St(e){let t=[];if(!e.exeLink||!e.cmdlineContent)return t;let n=e.cmdlineContent.split(`\0`).filter(Boolean);if(n.length===0)return t;let r=n[0],i=e.exeLink.replace(`(deleted)`,``).trim(),a=r.trim();return i!==a&&!a.endsWith(i.split(`/`).pop()??``)&&t.push({type:`peb_path_mismatch`,severity:`high`,description:`/proc/pid/exe symlink target ("${e.exeLink}") differs from cmdline argv[0] ("${r}") — possible argv[0] spoofing`,detail:{exeLink:e.exeLink,cmdlineArgv0:r,cmdlineFull:n.join(` `),note:`argv[0] spoofing is commonly used by hollowed processes to disguise their identity.`}}),t}function Ct(e){let t=[];if(!e.iatEntries||e.iatEntries.length===0)return t;let n=e.loadedModules??[],r=e.mapsEntries??[],i=n.map(e=>({name:e.name,start:e.base,end:e.base+e.size}));for(let a of e.iatEntries){let e=a.address;if(e!==0&&!i.some(t=>e>=t.start&&e<t.end)&&n.length>0){let n=r.some(t=>{let n=parseInt(t.start,16),r=parseInt(t.end,16);return e>=n&&e<r&&(t.perms===`rwx`||t.perms===`rwxp`)});t.push({type:`iat_hook_detected`,severity:n?`critical`:`high`,description:`IAT entry "${a.moduleName}!${a.functionName}" points to 0x${e.toString(16)} — outside all known module ranges${n?` (RWX region — possible shellcode)`:``}`,detail:{functionName:a.functionName,moduleName:a.moduleName,address:`0x${e.toString(16)}`,inRwxRegion:n,knownModuleRanges:i.map(e=>({name:e.name,range:`0x${e.start.toString(16)}-0x${e.end.toString(16)}`}))}})}}return t}const wt=[{engine:`V8 (Chrome/Node.js)`,pathPattern:/v8|chrome|node/i},{engine:`.NET CLR`,pathPattern:/clr\.dll|mscorlib|coreclr\.dll|\.net/i},{engine:`Java JVM`,pathPattern:/jvm\.dll|java|libjvm/i},{engine:`JavaScriptCore (WebKit)`,pathPattern:/javascriptcore|webkit/i},{engine:`SpiderMonkey (Firefox)`,pathPattern:/mozjs|spidermonkey|firefox/i},{engine:`LuaJIT`,pathPattern:/luajit/i},{engine:`Electron`,pathPattern:/electron/i}];function Tt(e){let t=[],n=e.knownJitRanges??[];for(let r of e.mapsEntries){if(r.perms!==`rwx`&&r.perms!==`rwxp`)continue;let e=parseInt(r.start,16),i=parseInt(r.end,16),a=r.pathname.toLowerCase();if(n.some(t=>e>=t.start&&i<=t.end)||wt.some(e=>e.pathPattern.test(a)))continue;let o=a===``||r.inode===`0`,s=r.perms.includes(`r`);t.push({type:`vad_protection_anomaly`,severity:o?`critical`:`high`,description:`RWX memory region at 0x${r.start}-0x${r.end} does NOT match any known JIT engine${o?` (anonymous mapping — likely injected code)`:``}${s?``:` (no read permission — unusual)`}${a?` (${a})`:``}`,detail:{start:`0x${r.start}`,end:`0x${r.end}`,perms:r.perms,pathname:a||`(anonymous)`,isAnonymous:o,hasRead:s,knownJitRanges:n.map(e=>({engine:e.engine,range:`0x${e.start.toString(16)}-0x${e.end.toString(16)}`})),note:`RWX regions outside known JIT address ranges are strong hollowing indicators. JIT engines like V8, .NET CLR, and Java HotSpot use known, identifiable code-cache regions.`,knownJitPatterns:wt.map(e=>e.engine)}})}return t}function Et(e){let t=[],n=null,r=null,i=[];if(e.peHex)try{let r=e.peHex.replace(/\s/g,``),i=new Uint8Array(r.length/2);for(let e=0;e<r.length;e+=2)i[e/2]=parseInt(r.substring(e,e+2),16);n=gt(i),n||t.push({type:`mismatched_binary_path`,severity:`info`,description:`Invalid PE hex provided — not a valid PE file (missing MZ/PE signature).`,detail:{}})}catch{t.push({type:`mismatched_binary_path`,severity:`info`,description:`Failed to parse PE hex input.`,detail:{}})}if(e.peMemoryHex)try{let t=e.peMemoryHex.replace(/\s/g,``),n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=parseInt(t.substring(e,e+2),16);r=gt(n)}catch{}e.mapsContent&&(i=ft(e.mapsContent),t.push(...pt(i))),e.exeLink&&t.push(...mt(e.exeLink)),n&&(t.push(...vt(n)),t.push(...bt(n)),t.push(...yt({expectedImagePath:e.expectedImagePath,peInfo:n}))),n&&r&&t.push(...xt(n,r)),(e.exeLink||e.cmdlineContent)&&t.push(...St({exeLink:e.exeLink,cmdlineContent:e.cmdlineContent})),e.loadedModules&&t.push(...Ct({iatEntries:void 0,loadedModules:e.loadedModules,mapsEntries:i})),i.length>0&&t.push(...Tt({mapsEntries:i,knownJitRanges:e.knownJitRanges}));let a=t.filter(e=>e.severity===`critical`).length,o=t.filter(e=>e.severity===`high`).length,s=t.filter(e=>e.severity===`medium`).length,c=t.filter(e=>e.severity===`low`).length,l=a*100+o*60+s*30+c*10,u=0;l>=200?u=95:l>=100?u=80:l>=50?u=50:t.length>0&&(u=20);let d=t.some(e=>e.severity===`critical`||e.severity===`high`||e.severity===`medium`),f;return f=t.length===0?`No hollowing indicators found in the provided data.`:d?[`Found ${t.length} hollowing indicator(s):`,...t.map(e=>` [${e.severity.toUpperCase()}] ${e.type}: ${e.description}`)].join(`
6
+ `):`Found ${t.length} low-severity indicator(s) — not conclusive.`,{isSuspicious:d,confidence:u,findings:t,summary:f,note:`This is a static/passive scan from provided data covering 7 heuristics: RWX regions, deleted backing file, suspicious sections, PE header-vs-memory mismatch, PEB path mismatch, IAT hook scan, VAD protection anomaly. Live memory comparison (process_detect_hollowing) is the gold standard for process hollowing detection and requires native OS APIs on Win32 (process_detect_hollowing provides that live native-API comparison — see hollowing-detection.ts). IAT hook detection via import table parsing requires IAT dump data not available in static scan mode — use process_detect_hollowing for live IAT analysis. VAD anomaly detection is static-only: RWX-vs-JIT classification is based on pattern matching against known JIT engine names, not live process introspection.`}}function Dt(e){let t=new a,n=new i,r=t.getPlatform();return{processManager:t,memoryManager:n,auditTrail:new T,platform:r,ctx:e}}var Ot=class{processMgmt;memoryOps;deps;buildMemoryDiagnostics;safeBuildMemoryDiagnostics;recordMemoryAudit;constructor(t){this.deps=Dt(t),e.info(`ProcessToolHandlers initialized for platform: ${this.deps.platform}`),this.processMgmt=new ue(this.deps),this.memoryOps=new de(this.deps,this.processMgmt),this.buildMemoryDiagnostics=this.processMgmt.buildMemoryDiagnostics.bind(this.processMgmt),this.safeBuildMemoryDiagnostics=this.processMgmt.safeBuildMemoryDiagnostics.bind(this.processMgmt),this.recordMemoryAudit=this.processMgmt.recordMemoryAudit.bind(this.processMgmt)}async handleProcessFindTool(e){return C(async()=>await this.handleProcessFind(e))}async handleProcessFind(e){return this.processMgmt.handleProcessFind(e)}async handleProcessGetTool(e){return C(async()=>await this.handleProcessGet(e))}async handleProcessGet(e){return this.processMgmt.handleProcessGet(e)}async handleProcessKillTool(e){return C(async()=>await this.handleProcessKill(e))}async handleProcessKill(e){return this.processMgmt.handleProcessKill(e)}async handleProcessWindowsTool(e){return C(async()=>await this.handleProcessWindows(e))}async handleProcessWindows(e){return this.processMgmt.handleProcessWindows(e)}async handleProcessCheckDebugPortTool(e){return C(async()=>await this.handleProcessCheckDebugPort(e))}async handleProcessCheckDebugPort(e){return this.processMgmt.handleProcessCheckDebugPort(e)}async handleProcessLaunchDebugTool(e){return C(async()=>await this.handleProcessLaunchDebug(e))}async handleProcessLaunchDebug(e){return this.processMgmt.handleProcessLaunchDebug(e)}async handleMemoryReadTool(e){return C(async()=>await this.handleMemoryRead(e))}async handleMemoryRead(e){return this.memoryOps.handleMemoryRead(e)}async handleMemoryWriteTool(e){return C(async()=>await this.handleMemoryWrite(e))}async handleMemoryWrite(e){return this.memoryOps.handleMemoryWrite(e)}async handleMemoryScanTool(e){return C(async()=>await this.handleMemoryScan(e))}async handleMemoryScan(e){return this.memoryOps.handleMemoryScan(e)}async handleMemoryAuditExportTool(e){return C(async()=>await this.handleMemoryAuditExport(e))}async handleMemoryAuditExport(e){return this.memoryOps.handleMemoryAuditExport(e)}async handleMemoryCheckProtectionTool(e){return C(async()=>await this.handleMemoryCheckProtection(e))}async handleMemoryCheckProtection(e){return this.memoryOps.handleMemoryCheckProtection(e)}async handleMemoryScanFilteredTool(e){return C(async()=>await this.handleMemoryScanFiltered(e))}async handleMemoryScanFiltered(e){return this.memoryOps.handleMemoryScanFiltered(e)}async handleMemoryBatchWriteTool(e){return C(async()=>await this.handleMemoryBatchWrite(e))}async handleMemoryBatchWrite(e){return this.memoryOps.handleMemoryBatchWrite(e)}async handleMemoryDumpRegionTool(e){return C(async()=>await this.handleMemoryDumpRegion(e))}async handleMemoryDumpRegion(e){return this.memoryOps.handleMemoryDumpRegion(e)}async handleMemoryListRegionsTool(e){return C(async()=>await this.handleMemoryListRegions(e))}async handleMemoryListRegions(e){return this.memoryOps.handleMemoryListRegions(e)}},kt=class extends Ot{injection;hollowing;handleEnum;apcDetection;processSuspend;constructor(e){super(e),this.injection=new Ee(this.deps,this.processMgmt),this.hollowing=new De(this.processMgmt),this.handleEnum=new Ge(this.processMgmt),this.apcDetection=new ct(this.deps),this.processSuspend=new lt(this.processMgmt)}async handleInjectDllTool(e){return C(async()=>await this.handleInjectDll(e))}async handleInjectDll(e){return this.injection.handleInjectDll(e)}async handleInjectShellcodeTool(e){return C(async()=>await this.handleInjectShellcode(e))}async handleInjectShellcode(e){return this.injection.handleInjectShellcode(e)}async handleCheckDebugPortTool(e){return C(async()=>await this.handleCheckDebugPort(e))}async handleCheckDebugPort(e){return this.injection.handleCheckDebugPort(e)}async handleEnumerateModulesTool(e){return C(async()=>await this.handleEnumerateModules(e))}async handleEnumerateModules(e){return this.injection.handleEnumerateModules(e)}async handleProcessEnumThreadsTool(e){return C(async()=>await this.handleProcessEnumThreads(e))}async handleProcessEnumThreads(e){return this.injection.handleProcessEnumThreads(e)}async handleElectronAttachTool(e){return C(async()=>await this.handleElectronAttach(e))}async handleElectronAttach(e){return this.injection.handleElectronAttach(e)}async handleDetectHollowingTool(e){return C(async()=>await this.handleDetectHollowing(e))}async handleDetectHollowing(e){return this.hollowing.handleDetectHollowing(e)}async handleHollowingScanTool(e){return C(async()=>this.handleHollowingScan(e))}async handleHollowingScan(e){return Et({pid:typeof e.pid==`number`?e.pid:void 0,mapsContent:typeof e.mapsContent==`string`?e.mapsContent:void 0,exeLink:typeof e.exeLink==`string`?e.exeLink:void 0,peHex:typeof e.peHex==`string`?e.peHex:void 0,expectedImagePath:typeof e.expectedImagePath==`string`?e.expectedImagePath:void 0})}async handleProcessEnumHandlesTool(e){return C(async()=>await this.handleProcessEnumHandles(e))}async handleProcessEnumHandles(e){return this.handleEnum.handleProcessEnumHandles(e)}async handleProcessDetectApcTool(e){return C(async()=>await this.handleProcessDetectApc(e))}async handleProcessDetectApc(e){return this.apcDetection.handleProcessDetectApc(e)}async handleProcessSuspendTool(e){return C(async()=>await this.handleProcessSuspend(e))}async handleProcessSuspend(e){return this.processSuspend.handleProcessSuspend(e)}async handleProcessResumeTool(e){return C(async()=>await this.handleProcessResume(e))}async handleProcessResume(e){return this.processSuspend.handleProcessResume(e)}};export{kt as ProcessToolHandlers};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./logger-BGCcd-jJ.mjs";import{d as t,f as n,h as r,m as i,p as a}from"./constants-nvsLpSri.mjs";import{c as o,i as s,n as c,s as l}from"./parse-args-B6dwWc9k.mjs";import{r as u,t as d}from"./ResponseBuilder-BLicSCjn.mjs";import"./definitions-BpIQN2nm.mjs";import{createRequire as f}from"node:module";import p from"node:path";import{access as m,mkdir as h,readFile as g,writeFile as _}from"node:fs/promises";import{createPrivateKey as v,randomUUID as y,webcrypto as b}from"node:crypto";const x={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`,publicExponent:new Uint8Array([1,0,1])},S={commonName:`CN`,organizationName:`O`,organizationalUnitName:`OU`,countryName:`C`,localityName:`L`,stateOrProvinceName:`ST`,domainComponent:`DC`,serialNumber:`2.5.4.5`},C=Symbol.for(`jshookmcp.mockttpCaCompatPatched`);let w=null;function T(e,t){return`-----BEGIN ${t}-----\n${(Buffer.from(e).toString(`base64`).match(/.{1,64}/g)||[]).join(`
2
+ `)}\n-----END ${t}-----\n`}function E(e,t,n){let r=[];for(let e of n){let n=t[e];if(!n)continue;let i=S[e]||e;r.push({[i]:[n]})}for(let[e,i]of Object.entries(t)){if(!i||n.includes(e))continue;let t=S[e]||e;r.push({[t]:[i]})}return new e.x509.Name(r).toString()}function D(e){if(!e.includes(`_`))return e;let[,...t]=e.split(`.`);if(t.length<=1||t.some(e=>e.includes(`_`)))throw Error(`Cannot generate certificate for domain due to underscores: ${e}`);return`*.${t.join(`.`)}`}function O(e){return e instanceof Error?e.message.includes(`Cannot get schema for 'PrivateKeyInfo' target`)||e.message.includes(`Unsupported or malformed key format`):!1}async function k(e){if(`key`in e&&`cert`in e)return{keyPem:e.key.toString(),certPem:e.cert.toString()};let[t,n]=await Promise.all([g(e.keyPath,`utf8`),g(e.certPath,`utf8`)]);return{keyPem:t,certPem:n}}async function A(e){let t=v(e).export({type:`pkcs8`,format:`der`});return await b.subtle.importKey(`pkcs8`,t,{name:x.name,hash:x.hash},!0,[`sign`])}function j(){let e=new Map;return t=>{let n=e.get(t);return n||(n=b.subtle.generateKey({...x,modulusLength:t},!0,[`sign`,`verify`]),e.set(t,n)),n}}async function M(e,t){let{keyPem:n,certPem:r}=await k(e),i=await A(n),a=new t.x509.X509Certificate(r),o=j(),s=Math.max(1024,e.keyLength??2048);return{generateCertificate:async n=>{let r=D(n),c=await o(s),l=E(t,{countryName:e.countryName??`XX`,localityName:e.localityName,organizationName:e.organizationName,commonName:r.startsWith(`*.`)?void 0:r},[`countryName`,`organizationName`,`localityName`,`commonName`]),u=new Date;u.setDate(u.getDate()-1);let d=new Date(u.getTime()+1080*60*60*1e3),f=[new t.x509.BasicConstraintsExtension(!1,void 0,!0),new t.x509.KeyUsagesExtension(t.x509.KeyUsageFlags.digitalSignature|t.x509.KeyUsageFlags.keyEncipherment,!0),new t.x509.ExtendedKeyUsageExtension([t.asn1X509.id_kp_serverAuth,t.asn1X509.id_kp_clientAuth],!1),new t.x509.SubjectAlternativeNameExtension([{type:`dns`,value:r}],!1),await t.x509.AuthorityKeyIdentifierExtension.create(a,!1)],p=await t.x509.X509CertificateGenerator.create({serialNumber:`A${y().replaceAll(`-`,``)}`,subject:l,issuer:a.subject,notBefore:u,notAfter:d,signingAlgorithm:{name:x.name,hash:x.hash},publicKey:c.publicKey,signingKey:i,extensions:f});return{key:T(await b.subtle.exportKey(`pkcs8`,c.privateKey),`PRIVATE KEY`),cert:p.toString(`pem`),ca:a.toString(`pem`),expiresAt:d}}}}async function N(){return w||=(async()=>{let e=f(f(import.meta.url).resolve(`mockttp`)),t=e(`./util/certificates`);if(t[C])return;let n=t.getCA.bind(t),r={x509:e(`@peculiar/x509`),asn1X509:e(`@peculiar/asn1-x509`),asn1Schema:e(`@peculiar/asn1-schema`)};t.getCA=async e=>{try{return await n(e)}catch(t){if(!O(t))throw t;return await M(e,r)}},t[C]=!0})(),await w}const P={success:e=>d.ok().merge(e).json(),error:e=>d.fail(e).mcpError().json()},F=new Set([`forward`,`mock_response`,`redirect`,`block`]),I=/^[A-Z][A-Z0-9_-]*$|^\*$/;async function L(e){try{return await m(e),!0}catch{return!1}}function R(e){let t=e.trim(),n=/^\/(.+)\/([a-z]*)$/.exec(t);if(n&&n[1]!==void 0){let e=n[1],t=n[2]??``;return new RegExp(e,t)}return new RegExp(t)}function z(e){return typeof e!=`string`||!F.has(e)?{ok:!1,error:`action must be one of: forward, mock_response, redirect, block`}:{ok:!0,value:e}}function B(e,t,n){let r=e[t];return r==null?{ok:!0,value:n}:typeof r==`string`?{ok:!0,value:r}:{ok:!1,error:`${t} must be a string when provided`}}function V(e){let t=B(e,`method`,`GET`);if(!t.ok)return t;let n=t.value.trim().toUpperCase();return I.test(n)?{ok:!0,value:n}:{ok:!1,error:`method must be a valid HTTP method token, ANY, ALL, or *`}}function H(e){let t=e.mockStatus;return t==null?{ok:!0,value:200}:typeof t!=`number`||!Number.isFinite(t)||!Number.isInteger(t)||t<100||t>599?{ok:!1,error:`mockStatus must be an integer between 100 and 599 when provided`}:{ok:!0,value:t}}function U(e,t){if(e==null)return;if(typeof e!=`object`||Array.isArray(e))throw Error(`forwardOptions.${t} must be an object of header name to string|null`);let n={};for(let[r,i]of Object.entries(e))if(i===null)n[r]=void 0;else if(typeof i==`string`)n[r]=i;else throw Error(`forwardOptions.${t}["${r}"] must be a string or null`);return n}function W(e,t){let n=/^\/(.+)\/([a-z]*)$/.exec(e);if(n&&n[1]!==void 0){let e=n[1],r=n[2]??``;try{return new RegExp(e,r)}catch(e){throw Error(`forwardOptions.${t} is not a valid regex literal: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}return e}function G(e,t){if(e==null)return;if(!Array.isArray(e))throw Error(`forwardOptions.${t} must be an array of [match, replacement] pairs`);let n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(!Array.isArray(i)||i.length!==2)throw Error(`forwardOptions.${t}[${r}] must be a [match, replacement] pair`);let[a,o]=i;if(typeof a!=`string`)throw Error(`forwardOptions.${t}[${r}][0] must be a string (plain or /pattern/flags)`);if(typeof o!=`string`)throw Error(`forwardOptions.${t}[${r}][1] must be a string`);n.push([W(a,`${t}[${r}][0]`),o])}return n}function K(e){let t={},n=e.replaceMethod;if(n!=null){if(typeof n!=`string`||n.trim()===``)throw Error(`forwardOptions.transformRequest.replaceMethod must be a non-empty string`);t.replaceMethod=n.toUpperCase()}let r=U(e.updateHeaders,`transformRequest.updateHeaders`);r&&(t.updateHeaders=r);let i=U(e.replaceHeaders,`transformRequest.replaceHeaders`);i&&(t.replaceHeaders=i);let a=e.replaceBody;if(a!=null){if(typeof a!=`string`)throw Error(`forwardOptions.transformRequest.replaceBody must be a string`);t.replaceBody=a}let o=G(e.matchReplaceBody,`transformRequest.matchReplaceBody`);o&&(t.matchReplaceBody=o);let s=e.updateJsonBody;if(s!=null){if(typeof s!=`object`||Array.isArray(s))throw Error(`forwardOptions.transformRequest.updateJsonBody must be an object`);t.updateJsonBody=s}return t}function q(e){let t={},n=e.replaceStatus;if(n!=null){if(typeof n!=`number`||!Number.isInteger(n)||n<100||n>599)throw Error(`forwardOptions.transformResponse.replaceStatus must be an integer between 100 and 599`);t.replaceStatus=n}let r=U(e.updateHeaders,`transformResponse.updateHeaders`);r&&(t.updateHeaders=r);let i=U(e.replaceHeaders,`transformResponse.replaceHeaders`);i&&(t.replaceHeaders=i);let a=e.replaceBody;if(a!=null){if(typeof a!=`string`)throw Error(`forwardOptions.transformResponse.replaceBody must be a string`);t.replaceBody=a}let o=G(e.matchReplaceBody,`transformResponse.matchReplaceBody`);o&&(t.matchReplaceBody=o);let s=e.updateJsonBody;if(s!=null){if(typeof s!=`object`||Array.isArray(s))throw Error(`forwardOptions.transformResponse.updateJsonBody must be an object`);t.updateJsonBody=s}return t}function J(e){let t=l(e,`forwardOptions`);if(t===void 0)return;let n={},r=t.transformRequest;if(r!=null){if(typeof r!=`object`||Array.isArray(r))throw Error(`forwardOptions.transformRequest must be an object`);n.transformRequest=K(r)}let i=t.transformResponse;if(i!=null){if(typeof i!=`object`||Array.isArray(i))throw Error(`forwardOptions.transformResponse must be an object`);n.transformResponse=q(i)}let a=t.chainUpstream;if(a!=null){if(typeof a!=`object`||Array.isArray(a))throw Error(`forwardOptions.chainUpstream must be an object`);let e=a,t={};if(e.proxyUrl!==void 0&&e.proxyUrl!==null){if(typeof e.proxyUrl!=`string`)throw Error(`forwardOptions.chainUpstream.proxyUrl must be a string`);t.proxyUrl=e.proxyUrl}else throw Error(`forwardOptions.chainUpstream.proxyUrl is required`);let r=e.noProxy;if(r!=null){if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw Error(`forwardOptions.chainUpstream.noProxy must be an array of strings`);t.noProxy=r}let i=e.trustedCAs;if(i!=null){if(!Array.isArray(i))throw Error(`forwardOptions.chainUpstream.trustedCAs must be an array`);t.trustedCAs=i}n.chainUpstream=t}let o=t.callbackScript;if(o!=null){if(typeof o!=`object`||Array.isArray(o))throw Error(`forwardOptions.callbackScript must be an object with a path field`);let e=o;if(typeof e.path!=`string`||e.path.trim()===``)throw Error(`forwardOptions.callbackScript.path must be a non-empty string`);if(n.transformRequest||n.transformResponse)throw Error(`forwardOptions.callbackScript is mutually exclusive with transformRequest/transformResponse`);n.callbackScript={path:e.path}}else if(!n.transformRequest&&!n.transformResponse&&!n.chainUpstream)return;return n}function Y(e){let t={};for(let[n,r]of Object.entries(e??{}))Array.isArray(r)?t[n]=r.map(e=>String(e)).join(`, `):r!==void 0&&(t[n]=String(r));return t}function X(e,t){if(!(typeof e!=`number`||typeof t!=`number`))return Math.max(0,Math.round((t-e)*1e3)/1e3)}function Z(e){if(!e)return;let t=e.startTimestamp,n=X(t,e.bodyReceivedTimestamp),r=X(t,e.headersSentTimestamp),i=X(t,e.responseSentTimestamp),a=X(t,e.abortedTimestamp),o=i??r??a??n;return{...typeof e.startTime==`number`?{startedAt:new Date(e.startTime).toISOString(),startTime:e.startTime}:{},...n===void 0?{}:{bodyReceivedMs:n},...r===void 0?{}:{headersSentMs:r},...i===void 0?{}:{responseSentMs:i},...o===void 0?{}:{durationMs:o}}}function Q(e){let t=Buffer.from(e,`utf8`),n=t.subarray(0,a);return{bodyTextPreview:n.toString(`utf8`),bodyBytes:t.length,bodyPreviewBytes:n.length,bodyTruncated:t.length>n.length,bodyEncoding:`utf8`}}async function $(e){if(!e)return{};try{let t;return typeof e.getText==`function`?t=await e.getText():typeof e.asText==`function`?t=await e.asText():Buffer.isBuffer(e.buffer)&&(t=e.buffer.toString(`utf8`)),t===void 0?{bodyUnavailable:`body could not be decoded as text`}:Q(t)}catch(e){return{bodyUnavailable:e instanceof Error?e.message:String(e)}}}var ee=class{server=null;caPathDir;currentPort=null;captureBuffer=[];ruleRecords=[];ruleEndpoints=new Map;mockttpModule=null;caReady=!1;constructor(){let e=process.env.HOME||process.env.USERPROFILE||`/tmp`;this.caPathDir=p.join(e,`.jshookmcp`,`ca`)}async handleProxyStartTool(e){return u(async()=>await this.handleProxyStart(e))}async handleProxyStopTool(e){return u(async()=>await this.handleProxyStop(e))}async handleProxyStatusTool(e){return u(async()=>await this.handleProxyStatus(e))}async handleProxyExportCaTool(e){return u(async()=>await this.handleProxyExportCa(e))}async handleProxyAddRuleTool(e){return u(async()=>await this.handleProxyAddRule(e))}async handleProxyListRulesTool(e){return u(async()=>await this.handleProxyListRules(e))}async handleProxyRemoveRuleTool(e){return u(async()=>await this.handleProxyRemoveRule(e))}async handleProxyClearRulesTool(e){return u(async()=>await this.handleProxyClearRules(e))}async handleProxyGetRequestsTool(e){return u(async()=>await this.handleProxyGetRequests(e))}async handleProxyClearLogsTool(e){return u(async()=>await this.handleProxyClearLogs(e))}async handleProxySetupAdbDeviceTool(e){return u(async()=>await this.handleProxySetupAdbDevice(e))}appendCapture(e){this.captureBuffer.push(e),this.captureBuffer.length>i&&this.captureBuffer.shift()}updateCapture(e,t,n){let r=this.captureBuffer.find(n=>n.type===e&&n.id===t);r&&Object.assign(r,n)}async ensureCa(t){let n=p.join(this.caPathDir,`ca.key`),r=p.join(this.caPathDir,`ca.pem`);this.caReady||=(await h(this.caPathDir,{recursive:!0}),!0);let i=await L(n),a=await L(r);if(!i||!a){e.info(`[proxy] generating new CA certificates`);let i=await t.generateCACertificate();try{i.key=v(i.key).export({type:`pkcs8`,format:`pem`}).toString()}catch{}await _(n,i.key,{mode:384}),await _(r,i.cert)}return{key:await g(n,`utf8`),cert:await g(r,`utf8`),certPath:r}}async handleProxyStart(e){let t=s(e,`port`)||8080,n=c(e,`useHttps`)??!0;if(this.server)return P.error(`Proxy is already running on port ${this.currentPort}`);try{let e=this.mockttpModule??await import(`mockttp`);this.mockttpModule=e;let r=null,i;if(n){await N();let{key:t,cert:n,certPath:a}=await this.ensureCa(e);r=a,i=e.getLocal({https:{key:t,cert:n},cors:!0})}else i=e.getLocal();let a=i;return a.on(`request`,e=>{let t=e;this.appendCapture({type:`request`,id:t.id,method:t.method,url:t.url,headers:Y(t.headers),remoteIpAddress:t.remoteIpAddress,remotePort:t.remotePort,timing:Z(t.timingEvents),timestamp:Date.now()}),$(t.body).then(e=>this.updateCapture(`request`,t.id,e))}),a.on(`response`,e=>{let t=e,n=this.captureBuffer.find(e=>e.type===`request`&&e.id===t.id);this.appendCapture({type:`response`,id:t.id,method:n?.method,url:n?.url,status:t.statusCode,headers:Y(t.headers),remoteIpAddress:t.remoteIpAddress,remotePort:t.remotePort,timing:Z(t.timingEvents),timestamp:Date.now()}),$(t.body).then(e=>this.updateCapture(`response`,t.id,e))}),await i.start(t),this.server=i,this.currentPort=t,P.success({message:`Proxy started.`,port:this.currentPort,caCertPath:r})}catch(e){this.server=null;let t=e instanceof Error?e.message:String(e);return P.error(`Failed to start proxy: ${t}`)}}async handleProxyStop(e){return this.server?(await this.server.stop(),this.server=null,this.currentPort=null,this.ruleRecords=[],this.ruleEndpoints.clear(),P.success({message:`Proxy stopped successfully`})):P.error(`Proxy is not running.`)}async handleProxyStatus(e){return P.success({running:!!this.server,port:this.currentPort,caDir:this.caPathDir,caCertPath:p.join(this.caPathDir,`ca.pem`),ruleCount:this.ruleRecords.length})}async handleProxyExportCa(e){let t=p.join(this.caPathDir,`ca.pem`);if(!await L(t))return P.error(`CA certificate not found. Start the proxy with HTTPS enabled first.`);let n=await g(t,`utf8`);return P.success({path:t,content:n})}async handleProxyAddRule(e){if(!this.server)return P.error(`Proxy must be running to add rules.`);let t=z(e.action);if(!t.ok)return P.error(t.error);let n=t.value,r=V(e);if(!r.ok)return P.error(r.error);let i=r.value,a=B(e,`urlPattern`,`.*`);if(!a.ok)return P.error(a.error);let o=a.value,c,l;if(n===`mock_response`){let t=H(e);if(!t.ok)return P.error(t.error);c=t.value;let n=B(e,`mockBody`,``);if(!n.ok)return P.error(n.error);l=n.value}let u;if(n===`redirect`){let t=B(e,`targetUrl`,``);if(!t.ok)return P.error(t.error);let n=t.value.trim();if(n===``)return P.error(`targetUrl is required when action=redirect`);let r=n.replace(/^[a-z][a-z0-9+.-]*:\/\//i,``);if(/[/?#]/.test(r))return P.error(`targetUrl must be a root URL with no path, query, or fragment (e.g. http://host:port); the original request path is preserved`);u=n}let d=s(e,`delayMs`)??0;if(!Number.isFinite(d)||!Number.isInteger(d)||d<0)return P.error(`delayMs must be a non-negative integer when provided`);let f=d;try{let t=R(o),r=this.server,a;if(i===`GET`)a=r.forGet(t);else if(i===`POST`)a=r.forPost(t);else if(i===`PUT`)a=r.forPut(t);else if(i===`DELETE`)a=r.forDelete(t);else if(i===`ANY`||i===`*`||i===`ALL`)a=r.forAnyRequest();else if(typeof r.forMethod==`function`)a=r.forMethod(i,t);else return P.error(`Proxy server does not support method-specific rules for ${i}`);f>0&&(a=a.delay(f));let s,d;switch(n){case`forward`:d=J(e),s=await a.thenPassThrough(await this.resolveMockttpOptions(d??{}));break;case`redirect`:d=J(e),s=await a.thenForwardTo(u??``,await this.resolveMockttpOptions(d??{}));break;case`block`:s=await a.thenCloseConnection();break;case`mock_response`:s=await a.thenReply(c??200,l??``);break}return this.ruleEndpoints.set(s.id,s),P.success({message:`Rule added successfully`,endpointId:s.id,rule:this.recordRule({endpointId:s.id,action:n,method:i,urlPattern:o,...n===`mock_response`?{mockStatus:c??200}:{},...n===`mock_response`?{mockBody:l??``}:{},...u?{targetUrl:u}:{},...f>0?{delayMs:f}:{},...d?{forwardOptions:d}:{}})})}catch(e){let t=e instanceof Error?e.message:String(e);return P.error(`Failed to add rule: ${t}`)}}async handleProxyRemoveRule(e){if(!this.server)return P.error(`Proxy must be running to remove rules.`);let t=o(e,`endpointId`);if(!t)return P.error(`endpointId is required`);let n=this.ruleRecords.findIndex(e=>e.endpointId===t);if(n===-1)return P.error(`Rule not found: ${t}. Use proxy_list_rules to see active rules.`);let r=this.ruleRecords[n],i=this.ruleEndpoints.get(t);if(!i?.dispose)return P.error(`Rule endpoint cannot be disposed: ${t}`);try{return await i.dispose(),this.ruleEndpoints.delete(t),this.ruleRecords.splice(n,1),P.success({message:`Rule removed successfully.`,endpointId:t,removedRule:{action:r.action,method:r.method,urlPattern:r.urlPattern,createdAt:r.createdAt}})}catch(e){let t=e instanceof Error?e.message:String(e);return P.error(`Failed to remove rule: ${t}`)}}async handleProxyListRules(e){return P.success({count:this.ruleRecords.length,rules:this.ruleRecords.map(e=>({...e}))})}async handleProxyClearRules(e){if(!this.server)return P.error(`Proxy must be running to clear rules.`);let t=this.server;if(typeof t.setRequestRules!=`function`)return P.error(`Proxy server does not support clearing rules at runtime.`);await t.setRequestRules();let n=this.ruleRecords.length;return this.ruleRecords=[],this.ruleEndpoints.clear(),P.success({message:`Proxy rules cleared.`,cleared:n})}async handleProxyGetRequests(e){let t=o(e,`urlFilter`),n=this.captureBuffer;return t&&(n=n.filter(e=>e.url!==void 0&&e.url.includes(t))),P.success({count:n.length,logs:n.slice(-r)})}async handleProxyClearLogs(e){return this.captureBuffer=[],P.success({message:`Captured proxy logs cleared.`})}async handleProxySetupAdbDevice(e){let r=this.currentPort;if(!r)return P.error(`Proxy must be running locally to setup ADB device reverse tethering.`);let i=p.join(this.caPathDir,`ca.pem`);if(!await L(i))return P.error(`CA certificate not found. Start the proxy with HTTPS enabled first.`);let{execFile:a}=await import(`node:child_process`),{promisify:s}=await import(`node:util`),c=s(a),l=o(e,`deviceSerial`),u=l?[`-s`,l]:[],f=async e=>c(`adb`,[...u,...e],{encoding:`utf8`,windowsHide:!0,timeout:n,maxBuffer:t});try{try{await c(`adb`,[`version`],{encoding:`utf8`,windowsHide:!0,timeout:n,maxBuffer:t})}catch(e){let t=e instanceof Error?e.message:String(e);return d.fail(`ADB binary not available: ${t}`).merge({available:!1,capability:`adb_binary`,status:`unavailable`,fix:"Install Android Platform Tools and ensure `adb` is available on PATH."}).json()}await f([`get-state`]),await f([`push`,i,`/data/local/tmp/ca.pem`]),await f([`reverse`,`tcp:${r}`,`tcp:${r}`]),await f([`shell`,`settings`,`put`,`global`,`http_proxy`,`127.0.0.1:${r}`]);let e=`ADB Configuration Applied Automatically:\n- Verified device connection.\n- Pushed CA to /data/local/tmp/ca.pem\n- Reversed forwarded tcp:${r} -> tcp:${r}\n- Set global http_proxy to 127.0.0.1:${r}\n\nNote: For HTTPS decryption, manually install the CA cert from /data/local/tmp/ca.pem in Android Settings. Android does not allow system CA installation through normal ADB permissions.`;return P.success({message:`ADB device successfully configured.`,deviceId:l||`default`,instructions:e})}catch(e){let t=e instanceof Error?e.message:String(e);return P.error(`Failed to configure ADB device: ${t}`)}}async resolveMockttpOptions(e){let t={};if(e.transformRequest&&(t.transformRequest=e.transformRequest),e.transformResponse&&(t.transformResponse=e.transformResponse),e.chainUpstream){let n=e.chainUpstream,r={};n.proxyUrl&&(r.proxyUrl=n.proxyUrl),n.noProxy&&(r.noProxy=n.noProxy),n.trustedCAs&&(r.trustedCAs=n.trustedCAs.map(e=>e.cert?{cert:e.cert}:e.certPath?{certPath:e.certPath}:{})),t.proxyConfig=r}if(e.callbackScript)try{let n=e.callbackScript.path,r=await import(n);if(typeof r.beforeRequest==`function`&&(t.beforeRequest=r.beforeRequest),typeof r.beforeResponse==`function`&&(t.beforeResponse=r.beforeResponse),!r.beforeRequest&&!r.beforeResponse)throw Error(`Callback script ${n} must export beforeRequest and/or beforeResponse`)}catch(e){if(e instanceof Error&&e.message.includes(`must export`))throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load callback script: ${t}`,{cause:e})}return t}recordRule(e){let t={...e,createdAt:new Date().toISOString()};return this.ruleRecords.push(t),{...t}}};export{ee as ProxyHandlers};
@@ -0,0 +1 @@
1
+ import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{t}from"./logger-BGCcd-jJ.mjs";const n=[{domain:`adb-bridge`,depKey:`adbBridgeHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CaeFjdhj.mjs`)},{domain:`core`,depKey:`coreAnalysisHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-qXqrO6KC.mjs`)},{domain:`binary-instrument`,depKey:`binaryInstrumentHandlers`,profiles:[`full`],secondaryDepKeys:[`apkPackerHandlers`,`binarySecretsHandlers`],load:()=>import(`./manifest-D82z-5og.mjs`)},{domain:`boringssl-inspector`,depKey:`boringsslInspectorHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-7EOTUc0D.mjs`)},{domain:`browser`,depKey:`browserHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Dw5yYEac.mjs`)},{domain:`canvas`,depKey:`canvasHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`skiaCaptureHandlers`],load:()=>import(`./manifest-f0lUeXwq.mjs`)},{domain:`coordination`,depKey:`coordinationHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`sharedStateBoardHandlers`],load:()=>import(`./manifest-DjHkjddT.mjs`)},{domain:`cross-domain`,depKey:`crossDomainHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BKA-mD3J.mjs`)},{domain:`dart-inspector`,depKey:`dartInspectorHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-h-Ebisf8.mjs`)},{domain:`debugger`,depKey:`debuggerHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`antidebugHandlers`],load:()=>import(`./manifest-QdkIzmYM.mjs`)},{domain:`encoding`,depKey:`encodingHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-JHaG6GMN.mjs`)},{domain:`exploit-dev`,depKey:`exploitDevHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DEY0s1O72.mjs`)},{domain:`extension-registry`,depKey:`extensionRegistryHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DucPMG_a.mjs`)},{domain:`graphql`,depKey:`graphqlHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-B5ujuQmf.mjs`)},{domain:`instrumentation`,depKey:`instrumentationHandlers`,profiles:[`full`],secondaryDepKeys:[`aiHookHandlers`,`hookPresetHandlers`,`evidenceHandlers`],load:()=>import(`./manifest-C0owVAdq.mjs`)},{domain:`maintenance`,depKey:`coreMaintenanceHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`extensionManagementHandlers`,`sandboxHandlers`],load:()=>import(`./manifest-oOfTymBS.mjs`)},{domain:`memory`,depKey:`memoryScanHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DTOqNqiA.mjs`)},{domain:`mojo-ipc`,depKey:`mojoIpcHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-YZqaCe25.mjs`)},{domain:`native-bridge`,depKey:`nativeBridgeHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-C5XqYc9o.mjs`)},{domain:`native-emulator`,depKey:`nativeEmulatorHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CVKzLjsA.mjs`)},{domain:`network`,depKey:`advancedHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D0dbtDqd.mjs`)},{domain:`platform`,depKey:`platformHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Bx-tpURK.mjs`)},{domain:`process`,depKey:`processHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DA2afIwh.mjs`)},{domain:`protocol-analysis`,depKey:`protocolAnalysisHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CegBgip0.mjs`)},{domain:`proxy`,depKey:`proxyHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Dpnhvfq0.mjs`)},{domain:`sourcemap`,depKey:`sourcemapHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BUXj23bX.mjs`)},{domain:`streaming`,depKey:`streamingHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CoJHqlgS.mjs`)},{domain:`syscall-hook`,depKey:`syscallHookHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DZ6ELNgX.mjs`)},{domain:`trace`,depKey:`traceHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DocA_itf2.mjs`)},{domain:`transform`,depKey:`transformHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BfXt9cau.mjs`)},{domain:`v8-inspector`,depKey:`v8InspectorHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D5Gr8ujd.mjs`)},{domain:`wasm`,depKey:`wasmHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BErXl3zn.mjs`)},{domain:`webgpu`,depKey:`webgpuHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Ic_Cg66S.mjs`)},{domain:`workflow`,depKey:`workflowHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`macroHandlers`],load:()=>import(`./manifest-DAbiFP5o.mjs`)}],r={"adb-bridge":[`full`],core:[`workflow`,`full`],"binary-instrument":[`full`],"boringssl-inspector":[`full`],browser:[`workflow`,`full`],canvas:[`workflow`,`full`],coordination:[`workflow`,`full`],"cross-domain":[`full`],"dart-inspector":[`full`],debugger:[`workflow`,`full`],encoding:[`workflow`,`full`],"exploit-dev":[`full`],"extension-registry":[`full`],graphql:[`workflow`,`full`],instrumentation:[`full`],maintenance:[`workflow`,`full`],memory:[`full`],"mojo-ipc":[`full`],"native-bridge":[`full`],"native-emulator":[`full`],network:[`workflow`,`full`],platform:[`full`],process:[`full`],"protocol-analysis":[`full`],proxy:[`full`],sourcemap:[`full`],streaming:[`workflow`,`full`],"syscall-hook":[`full`],trace:[`full`],transform:[`full`],"v8-inspector":[`workflow`,`full`],wasm:[`full`],webgpu:[`workflow`,`full`],workflow:[`workflow`,`full`]};function i(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.kind===`domain-manifest`&&t.version===1&&typeof t.domain==`string`&&typeof t.depKey==`string`&&Array.isArray(t.profiles)&&Array.isArray(t.registrations)&&typeof t.ensure==`function`}function a(e){if(!e||typeof e!=`object`)return null;let t=e;for(let e of[`default`,`manifest`,`domainManifest`]){let n=t[e];if(i(n))return n}return null}function o(e){let t=new Set;for(let[n,i]of Object.entries(r))i.includes(e)&&t.add(n);return t}function s(){return new Set(Object.keys(r))}function c(){return n}async function l(e){let r=[],i=new Set,o=new Set;for(let{domain:s,load:c}of n)if(!(e&&!e.has(s)))try{let e=a(await c());if(!e){t.warn(`[discovery] Skipping domain "${s}": no valid DomainManifest export`);continue}if(i.has(e.domain)){t.warn(`[discovery] Duplicate domain "`+e.domain+`" in generated manifests - skipping`);continue}if(o.has(e.depKey)){t.warn(`[discovery] Duplicate depKey "`+e.depKey+`" in generated manifests - skipping`);continue}i.add(e.domain),o.add(e.depKey),r.push(e),t.info(`[discovery] Loaded domain "`+e.domain+`" (`+String(e.registrations.length)+` tools)`)}catch(e){if(t.error(`[discovery] Failed to load domain "${s}"`,e),process.env.DISCOVERY_STRICT===`true`)throw e}let s=r.reduce((e,t)=>e+t.registrations.length,0);return e&&r.length===0?t.info(`[discovery] No manifests loaded for the requested startup profile. Domains remain available for lazy activation.`):t.info(`[discovery] Discovered `+String(r.length)+` domains, `+String(s)+` tools total`),r}async function u(e){let r=n.find(t=>t.domain===e);if(!r)return null;try{let n=a(await r.load());return n?(t.info(`[discovery] On-demand loaded domain "`+n.domain+`" (`+String(n.registrations.length)+` tools)`),n):(t.warn(`[discovery] Domain "${e}": no valid DomainManifest export`),null)}catch(n){return t.error(`[discovery] Failed to load domain "${e}"`,n),null}}var d=e({allTools:()=>b,clearToolGroupsCache:()=>_,getProfileDomains:()=>E,getToolDomain:()=>T,getToolsByDomains:()=>C,getToolsForProfile:()=>w,parseToolDomains:()=>S});let f=null,p=null,m=null,h=null;function g(){return f||=G(),f}function _(){f=null}function v(){return p||=K(),p}function y(){return m||=Y(),m}const b=new Proxy([],{get(e,t){h||=q();let n=h,r=n[t];return typeof r==`function`?r.bind(n):r}});function x(e){let t=new Map;for(let n of e)t.set(n.name,n);return Array.from(t.values())}function S(e){if(!e?.trim())return null;let t=U(),n=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean).filter(e=>t.has(e));return n.length>0?Array.from(new Set(n)):null}function C(e){return x(e.flatMap(e=>g()[e]??[]))}function w(e){let t=y()[e];if(!t)return[];let n=new Set(t);return x([...H()].filter(t=>!(!n.has(t.domain)||t.profiles&&!t.profiles.includes(e))).map(e=>e.tool))}function T(e){return v().get(e)??null}function E(e){return y()[e]??[]}var D=e({buildAllTools:()=>q,buildHandlerMapFromRegistry:()=>J,buildProfileDomains:()=>Y,buildToolDomainMap:()=>K,buildToolGroups:()=>G,ensureAllDomainsLoaded:()=>R,ensureDomainLoaded:()=>L,getAllDomains:()=>U,getAllKnownDomains:()=>W,getAllManifests:()=>V,getAllRegistrations:()=>H,initRegistry:()=>I});function O(e,t){let n=new Set(t);return e.every(e=>n.has(e))}let k=null,A=null,j=null,M=null,N=null,P=null;async function F(e){if(k===null){if(j){await j;return}j=(async()=>{let n=await l(e?o(e):void 0);k=n,P=new Map;for(let e of n)for(let n of e.registrations){let r=n.domain?n:{...n,domain:e.domain},i=P.get(r.tool.name);i?t.warn(`[registry] Duplicate tool name "${r.tool.name}": domain "${r.domain}" conflicts with "${i.domain}" — keeping first`):P.set(r.tool.name,r)}A=[...P.values()],M=new Set(k.map(e=>e.domain)),N=new Set(A.map(e=>e.tool.name))})(),await j}}async function I(e){await F(e)}async function L(e){if(!k)throw Error(`[registry] Not initialised - call initRegistry() first.`);if(k.some(t=>t.domain===e))return k.find(t=>t.domain===e);let t=await u(e);if(!t)return null;k.push(t),M.add(t.domain);for(let e of t.registrations){let n=e.domain?e:{...e,domain:t.domain};P.has(n.tool.name)||P.set(n.tool.name,n)}A=[...P.values()],_();for(let e of t.registrations)N.add(e.tool.name);return t}async function R(){if(!k)throw Error(`[registry] Not initialised - call initRegistry() first.`);let e=s(),n=new Set(k.map(e=>e.domain)),r=[...e].filter(e=>!n.has(e));r.length!==0&&(t.info(`[registry] Loading ${r.length} remaining domains for full discovery`),await Promise.all(r.map(e=>L(e))))}function z(){if(!k)throw Error(`[registry] Not initialised - call initRegistry() first.`);return k}function B(){if(!A)throw Error(`[registry] Not initialised - call initRegistry() first.`);return A}function V(){return z()}function H(){return B()}function U(){if(!M)throw Error(`[registry] Not initialised - call initRegistry() first.`);return M}function W(){return s()}function G(){let e={};for(let t of B())(e[t.domain]??=[]).push(t.tool);return e}function K(){let e=new Map;for(let t of B())e.has(t.tool.name)||e.set(t.tool.name,t.domain);return e}function q(){return B().map(e=>e.tool)}function J(e,t){let n=t?B().filter(e=>t.has(e.tool.name)):[...B()],r=[];for(let t of n)try{r.push([t.tool.name,t.bind(e)])}catch{}return Object.fromEntries(r)}function Y(){let e={search:new Set,workflow:new Set,full:new Set};for(let[t,n]of Object.entries(r))for(let r of n)e[r]?.add(t);let n={};for(let[t,r]of Object.entries(e))n[t]=[...r];return O(n.search,n.workflow)||t.warn(`[registry] Profile hierarchy: search not subset of workflow`),O(n.workflow,n.full)||t.warn(`[registry] Profile hierarchy: workflow not subset of full`),n}export{c as _,W as a,I as c,b as d,E as f,S as g,w as h,U as i,D as l,C as m,R as n,V as o,T as p,L as r,H as s,J as t,d as u};
@@ -1 +1 @@
1
- import"./ensure-browser-core-JHwDo5ql.mjs";function e(e){let t=new Map(e.map(e=>[e.name,e]));return e=>{let n=t.get(e);if(!n)throw Error(`[registry] Tool definition not found: "${e}"`);return n}}export{e as t};
1
+ import"./ensure-browser-core-BP70x0TB.mjs";function e(e){let t=new Map(e.map(e=>[e.name,e]));return e=>{let n=t.get(e);if(!n)throw Error(`[registry] Tool definition not found: "${e}"`);return n}}export{e as t};
@@ -0,0 +1 @@
1
+ function e(e){return e instanceof Error?e.message:String(e)}function t(e,t=!1){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function n(e){return t(JSON.stringify(e,null,2))}function r(n){return t(`Error: ${e(n)}`,!0)}function i(t){return{success:!1,error:e(t)}}export{i,n,t as r,r as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{t}from"./logger-BGCcd-jJ.mjs";import{l as n,o as r}from"./ToolRouter.policy-Bgb3S8jc.mjs";import{randomUUID as i}from"node:crypto";var a=class{store=new Map;set(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}getValueAtPath(e,t){let n=this.store.get(e);if(!n||typeof n!=`object`)return n;let r=o(n)||n;return t.split(`.`).reduce((e,t)=>{if(e&&typeof e==`object`){let n=t.match(/^(\d+)$/);return n&&Array.isArray(e)?e[Number(n[1])]:e[t]}},r)}resolve(e){let t=e.match(/^\$\{(.+)\}$/);if(!t||!t[1])return e;let n=t[1],r=n.indexOf(`.`);return r===-1?this.store.get(n):this.getValueAtPath(n.slice(0,r),n.slice(r+1))}};function o(e){if(!e||typeof e!=`object`)return;let t=e.content?.find(e=>e.type===`text`)?.text;if(typeof t==`string`)try{let e=JSON.parse(t);return e&&typeof e==`object`?e:void 0}catch{return}}function s(e){if(!e||typeof e!=`object`)return;if(e.isError)return`Tool returned MCP error response`;let t=o(e);if(t?.success===!1)return typeof t.error==`string`?t.error:`Tool reported success=false`}function c(e){if(Array.isArray(e))return e.reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0});if(!e||typeof e!=`object`)return{success:0,failure:0};let t=e;if(Array.isArray(t.__order))return t.__order.reduce((e,n)=>{let r=c(t[n]);return e.success+=r.success,e.failure+=r.failure,e},{success:0,failure:0});let n=o(e);return n?.success===!0?{success:1,failure:0}:n?.success===!1||`error`in t?{success:0,failure:1}:{success:0,failure:0}}function l(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=i.startsWith("${")?i:`\${${i}}`;n[r]=t.resolve(e)}return n}function u(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}function d(e,t){if(typeof e==`string`)return t.resolve(e);if(Array.isArray(e))return e.map(e=>d(e,t));if(e&&typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}return e}function f(e,t){if(e.has(t))return e.get(t);let[n,...r]=t.split(`.`);if(!n||!e.has(n))return;let i=e.get(n);if(i&&typeof i==`object`){let e=o(i);e&&(i=e)}for(let e of r){if(i&&typeof i==`object`){let t=e.match(/^(\d+)$/);if(t&&Array.isArray(i)){i=i[Number(t[1])];continue}i=i[e];continue}return}return i}function p(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){let n=e,r=t;return n.length===r.length&&n.every((e,t)=>p(e,r[t]))}let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>p(e[n],t[n])):!1}return!1}async function m(e,t){if(e.predicateFn)return await e.predicateFn(t);if(e.predicateId===`always_true`)return!0;if(e.predicateId===`always_false`)return!1;if(e.predicateId===`any_step_failed`)return[...t.stepResults.values()].some(e=>c(e).failure>0);let n=e.predicateId.match(/success_rate_gte_(\d+)/i);if(n?.[1]){let e=Number(n[1]),r=[...t.stepResults.values()].reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0}),i=r.success+r.failure;return i>0&&r.success/i>=e/100}let r=e.predicateId.match(/^variable_equals_(.+?)_(.+)$/);if(r?.[1]&&r[2])return p(f(t.stepResults,r[1]),r[2]);let i=e.predicateId.match(/^variable_contains_(.+?)_(.+)$/);if(i?.[1]&&i[2]){let e=f(t.stepResults,i[1]);return typeof e!=`string`&&!Array.isArray(e)?!1:String(e).includes(i[2])}let a=e.predicateId.match(/^variable_matches_(.+?)_(.+)$/);if(a?.[1]&&a[2]){let e=f(t.stepResults,a[1]);if(typeof e!=`string`)return!1;try{return new RegExp(a[2]).test(e)}catch{return!1}}throw Error(`Unknown workflow predicateId "${e.predicateId}"`)}function h(e){switch(e.kind){case`tool`:return[e];case`sequence`:case`parallel`:return e.steps.flatMap(e=>h(e));case`branch`:return[...h(e.whenTrue),...e.whenFalse?h(e.whenFalse):[]];case`fallback`:return[...h(e.primary),...h(e.fallback)];default:return[]}}function g(e){try{let t=e.getDomainInstance(`evidenceGraph`);return t?{hasGraph:!0,nodeCount:t.nodeCount,edgeCount:t.edgeCount}:{hasGraph:!1,nodeCount:0,edgeCount:0}}catch{return{hasGraph:!1,nodeCount:0,edgeCount:0}}}function _(e,t){let n=r(),i=[];for(let r of h(e)){let e=n[r.toolName]??[];for(let n of e)n.check(t)||i.push({nodeId:r.id,toolName:r.toolName,condition:n.condition,fix:n.fix})}return i}var v=class{runs=new Map;lastSuccess=new Map;recordSuccess(e){let n={workflowId:e.workflowId,runId:e.runId,startedAt:e.startedAt,finishedAt:e.finishedAt,durationMs:e.durationMs,status:`success`,stepResultKeys:Object.keys(e.stepResults)};this.runs.set(e.runId,n),this.lastSuccess.set(e.workflowId,e),t.debug(`workflow run recorded: ${e.runId} (${e.workflowId})`)}recordError(e,n,r,i){let a={workflowId:e,runId:n,startedAt:r,finishedAt:new Date().toISOString(),durationMs:Date.now()-new Date(r).getTime(),status:`error`,stepResultKeys:[]};this.runs.set(n,a),t.debug(`workflow run error: ${n} (${e}): ${i}`)}getRun(e){return this.runs.get(e)}getLastSuccess(e){return this.lastSuccess.get(e)}listRuns(e){let t=[...this.runs.values()];return e?t.filter(t=>t.workflowId===e):t}clear(){this.runs.clear(),this.lastSuccess.clear()}},y=class extends Error{warnings;constructor(e){super(`Workflow preflight failed with ${e.length} unsatisfied prerequisite(s)`),this.warnings=e,this.name=`PreflightError`}},b=e({executeExtensionWorkflow:()=>k,getWorkflowRunStore:()=>S});const x=new v;function S(){return x}function C(e,t,n){let r=t.split(`.`).filter(Boolean),i=e;for(let e of r){if(!i||typeof i!=`object`)return n;i=i[e]}return i??n}function w(e){return new Promise(t=>setTimeout(t,e))}async function T(e,t,n){return!Number.isFinite(t)||t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}async function E(e,t,n,r,i){let a=t.inputFrom?l(t.inputFrom,r.dataBus):{},o={...t.input?u(t.input,r.dataBus):{},...a,...n?.[t.id]},c=async()=>{let n=await T(e.executeToolWithTracking(t.toolName,o),t.timeoutMs??0,`Workflow tool node "${t.id}"`),i=s(n);if(i)throw Error(i);return r.dataBus.set(t.id,n),n},d=t.retry??i;if(!d)return c();let f=0;for(;f<d.maxAttempts;)try{return await c()}catch(e){if(f+=1,f>=d.maxAttempts)throw e;await w(Math.floor(d.backoffMs*(d.multiplier??1)**(f-1)*(.5+Math.random())))}throw Error(`Workflow tool node "${t.id}" exhausted retries`)}async function D(e,t,n,r){let i=Math.max(1,t.maxConcurrency??4),a={__order:[]},o=0,s=!1,c=async()=>{for(;;){if(s)return;let i=o;if(o+=1,i>=t.steps.length)return;let c=t.steps[i];if(!c)return;try{let t=await O(e,c,n,r);a[c.id]=t,a.__order.push(c.id)}catch(e){if(t.failFast)throw s=!0,e;a[c.id]={success:!1,error:e instanceof Error?e.message:String(e)},a.__order.push(c.id)}}};return await Promise.all(Array.from({length:Math.min(i,t.steps.length)},()=>c())),a}async function O(e,t,n,r){n.emitSpan(`workflow.node.start`,{nodeId:t.id,kind:t.kind});let i;switch(t.kind){case`tool`:i=await E(e,t,r.nodeInputOverrides,n,r.retryPolicy);break;case`sequence`:{let a=t,o=[];for(let t of a.steps)o.push(await O(e,t,n,r));i=o;break}case`parallel`:i=await D(e,t,n,r);break;case`branch`:{let a=t,o=await m(a,n)?a.whenTrue:a.whenFalse;i=o?await O(e,o,n,r):void 0;break}case`fallback`:{let a=t;try{i=await O(e,a.primary,n,r)}catch(t){n.emitSpan(`workflow.node.fallback`,{nodeId:a.id,primaryNodeId:a.primary.id,fallbackNodeId:a.fallback.id,error:t instanceof Error?t.message:String(t)}),i=await O(e,a.fallback,n,r)}break}default:throw Error(`Unsupported workflow node kind: ${t.kind}`)}return n.stepResults.set(t.id,i),n.emitSpan(`workflow.node.finish`,{nodeId:t.id,kind:t.kind}),i}async function k(e,t,r={}){let o=i(),s=r.profile??String(e.baseTier??`workflow`),c=new Date().toISOString(),l=Date.now(),u=[],d=[],f=new Map,p=new a,m=r.config?{...e.config,...r.config}:e.config,h={workflowRunId:o,profile:s,stepResults:f,dataBus:p,invokeTool(t,n){return e.executeToolWithTracking(t,n)},emitSpan(e,t){d.push({name:e,attrs:t,at:new Date().toISOString()})},emitMetric(e,t,n,r){u.push({name:e,value:t,type:n,attrs:r,at:new Date().toISOString()})},getConfig(e,t){return C(m,e,t)}};try{await t.onStart?.(h);let i=t.build(h),a=r.preflightMode??`warn`,p=[];if(a===`skip`)h.emitSpan(`workflow.preflight`,{mode:a,skipped:!0,evidenceState:g(e),warningCount:0});else try{let t=await n(e),r=g(e);if(p=_(i,t),h.emitSpan(`workflow.preflight`,{mode:a,routingState:t,evidenceState:r,warningCount:p.length,warnings:p}),a===`strict`&&p.length>0)throw new y(p)}catch(t){if(t instanceof y)throw t;h.emitSpan(`workflow.preflight`,{mode:a,warningCount:0,skipped:!0,error:t instanceof Error?t.message:String(t),evidenceState:g(e)})}let m=await T(O(e,i,h,r),r.timeoutMs??t.timeoutMs??0,`Workflow "${t.id}"`);await t.onFinish?.(h,m);try{let t=typeof e.getDomainInstance==`function`?e.getDomainInstance(`evidenceGraph`):void 0;t&&t.nodeCount>0&&(f.set(`__evidenceSnapshot`,t.exportJson()),h.emitSpan(`workflow.evidence.auto-export`,{nodeCount:t.nodeCount,edgeCount:t.edgeCount}))}catch(e){h.emitSpan(`workflow.evidence.auto-export`,{skipped:!0,error:e instanceof Error?e.message:String(e)})}let v={workflowId:t.id,displayName:t.displayName,runId:o,profile:s,startedAt:c,finishedAt:new Date().toISOString(),durationMs:Date.now()-l,result:m,stepResults:Object.fromEntries(f.entries()),metrics:u,spans:d};return x.recordSuccess(v),v}catch(e){let n=e instanceof Error?e:Error(String(e));throw x.recordError(t.id,o,c,n),await t.onError?.(h,n),n}}let A;function j(){return A?{...A}:void 0}function M(e){A={...e}}export{S as a,k as i,M as n,m as o,b as r,j as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./config-5ODJ3Aj0.mjs";function t(){return e().reverseEngineering}export{t};
@@ -0,0 +1 @@
1
+ import{basename as e,dirname as t,isAbsolute as n,normalize as r,relative as i,resolve as a,sep as o}from"node:path";import{lstat as s,mkdir as c,open as l,realpath as u,rename as d,rm as f}from"node:fs/promises";function p(e){return r(a(e))}function m(e,t){let r=i(e,t);return r===``||!n(r)&&!r.startsWith(`..${o}`)&&r!==`..`}function h(e,t,n=`path`){let r=p(e);if(t.split(/[\\/]+/).filter(e=>e.length>0).includes(`..`))throw Error(`${n} must not contain parent-directory segments`);let i=p(a(r,t));if(!m(r,i))throw Error(`${n} must stay within ${r}`);return i}async function g(e,t){let n=e.trim();if(!n)throw Error(`outputPath must be a non-empty string`);let r=p(n),i=t.allowedRoots.map(e=>e.trim()).filter(e=>e.length>0).map(e=>p(e));if(i.length===0||!i.some(e=>m(e,r)))throw Error(`outputPath must be within the ${t.allowedRootsDescription}.`);return r}function _(e){let t=e?.code;return t===`EEXIST`||t===`EPERM`||t===`EACCES`}async function v(e){try{return p(await u(e))}catch(e){if(e?.code===`ENOENT`)return null;throw e}}async function y(e){let n=p(e);for(;;){let r=await v(n);if(r)return r;let i=t(n);if(i===n)throw Error(`Unable to resolve an existing parent directory for ${e}`);n=i}}async function b(e){if(e)try{await e.close()}catch{}}async function x(e,t,n){await C(e,t,n)}async function S(e,t,n){await C(e,t,n)}async function C(n,r,i){let o=t(n);if(await c(o,{recursive:!0}),i?.allowedRoots?.length){let e=await Promise.all(i.allowedRoots.map(async e=>await v(e)??p(e))),t=await y(o);if(!e.some(e=>m(e,t)))throw Error(`outputPath parent directory escapes the allowed roots.`)}if(i?.rejectSymbolicLink!==!1)try{let e=await s(n);if(e.isSymbolicLink())throw Error(`outputPath must not be a symbolic link.`);if(e.isDirectory())throw Error(`outputPath must be a file path, not a directory.`)}catch(e){if(e?.code!==`ENOENT`&&!(e instanceof Error&&e.message.includes(`symbolic link`))||e instanceof Error&&e.message.includes(`symbolic link`))throw e}let u=a(o,`.${e(n)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`),h=null;try{h=await l(u,`wx`),typeof r==`string`?await h.writeFile(r,`utf8`):await h.writeFile(r),await h.sync(),await b(h),h=null;try{await d(u,n);return}catch(e){if(!_(e))throw e}await f(n,{force:!0}),await d(u,n)}catch(e){throw await b(h),await f(u,{force:!0}).catch(()=>void 0),e}}export{x as i,g as n,S as r,h as t};
@@ -1 +1 @@
1
- import{Ci as e,Ti as t,ki as n,wi as r}from"./constants-DMv3svps.mjs";const i={queryCategoryProfiles:[{pattern:`(?:security|vuln|xss|injection|csrf|exploit|attack|prototype\\s*pollution|漏洞|安全|注入|攻击)`,flags:`i`,domainBoosts:[{domain:`instrumentation`,weight:1.35},{domain:`debugger`,weight:1.2},{domain:`core`,weight:1.1}]},{pattern:`(?:debug|breakpoint|pause|step\\s*over|step\\s*into|stack\\s*trace|断点|调试|单步)`,flags:`i`,domainBoosts:[{domain:`debugger`,weight:1.6},{domain:`v8-inspector`,weight:1.2}]},{pattern:`(?:network|request|response|header|cookie|fetch|xhr|网络|请求|抓包)`,flags:`i`,domainBoosts:[{domain:`network`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:transform|deobfuscate|beautify|minify|decode|encode|解密|混淆|反混淆|转换)`,flags:`i`,domainBoosts:[{domain:`transform`,weight:1.6},{domain:`core`,weight:1.2}]},{pattern:`(?:memory|heap|dump|scan|inject|内存|堆|扫描)`,flags:`i`,domainBoosts:[{domain:`memory`,weight:1.6},{domain:`process`,weight:1.15},{domain:`binary-instrument`,weight:1.1}]},{pattern:`(?:wasm|webassembly)`,flags:`i`,domainBoosts:[{domain:`wasm`,weight:1.6}]},{pattern:`(?:browser|page|tab|navigate|click|screenshot|浏览器|页面|标签)`,flags:`i`,domainBoosts:[{domain:`browser`,weight:1.4}]},{pattern:`(?:captcha|人机验证|验证码|图形验证)`,flags:`i`,domainBoosts:[{domain:`browser`,weight:1.65}]},{pattern:`(?:reverse|mission|signature|hook|crypto|encrypt|websocket|\\bws\\b|protocol|bundle|webpack|deobfusc|stealthfingerprint|evidence|\\bhar\\b|逆向|签名|加签|协议|反混淆|反检测|指纹|证据|报告)`,flags:`i`,domainBoosts:[{domain:`workflow`,weight:1.8},{domain:`core`,weight:1.1}]},{pattern:`(?:v8|heap\\s?(?:snapshot|dump|profile)|bytecode|jit|turbofan|ignition|hidden\\s?class)`,flags:`i`,domainBoosts:[{domain:`v8-inspector`,weight:1.6},{domain:`memory`,weight:1.2}]},{pattern:`(?:tls|ssl|boringssl|cert(?:ificate)?|pinning|handshake|keylog|nss)`,flags:`i`,domainBoosts:[{domain:`boringssl-inspector`,weight:1.6},{domain:`network`,weight:1.1}]},{pattern:`(?:skia|gpu|render|scenegraph|scene\\s?tree|raster|draw\\s?call|layer)`,flags:`i`,domainBoosts:[{domain:`canvas`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:frida|ghidra|ida|unidbg|jadx|disassemble|instrument)`,flags:`i`,domainBoosts:[{domain:`binary-instrument`,weight:1.6},{domain:`memory`,weight:1.2}]},{pattern:`(?:adb|android|webview|apk|dalvik|art\\s?(?:runtime)?)`,flags:`i`,domainBoosts:[{domain:`adb-bridge`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:mojo|ipc|chromium.*ipc|broker|chromium.*interface)`,flags:`i`,domainBoosts:[{domain:`mojo-ipc`,weight:1.6},{domain:`debugger`,weight:1.1}]},{pattern:`(?:syscall|etw|strace|dtrace|kernel.*call|system\\s?call|tracefs)`,flags:`i`,domainBoosts:[{domain:`syscall-hook`,weight:1.6},{domain:`process`,weight:1.1}]},{pattern:`(?:protocol.*analy|state\\s?machine|packet.*decode|field.*extract)`,flags:`i`,domainBoosts:[{domain:`protocol-analysis`,weight:1.6},{domain:`network`,weight:1.1}]},{pattern:`(?:extension.*(?:install|registry|list)|plugin.*(?:install|manage)|addon|webhook.*(?:create|manage))`,flags:`i`,domainBoosts:[{domain:`extension-registry`,weight:1.6},{domain:`workflow`,weight:1.1}]}],cjkQueryAliases:[{pattern:`工作流|流程编排|流程自动化|编排`,tokens:[`workflow`,`flow`,`orchestration`]},{pattern:`抓包|抓取|采集|捕获`,tokens:[`capture`,`sniff`,`collect`]},{pattern:`接口|端点`,tokens:[`api`,`endpoint`,`request`]},{pattern:`探测|探针|扫描`,tokens:[`probe`,`scan`]},{pattern:`账号|账户|用户`,tokens:[`account`,`user`]},{pattern:`注册|开户|报名`,tokens:[`register`,`signup`]},{pattern:`验证|校验|激活`,tokens:[`verify`,`verification`,`activation`]},{pattern:`验证码|图形验证码|人机验证`,tokens:[`captcha`,`verify`,`verification`]},{pattern:`邮箱|邮件`,tokens:[`email`,`mail`]},{pattern:`keygen|密钥|注册码|激活码`,tokens:[`keygen`,`key`,`activation`]},{pattern:`轮询|监听`,tokens:[`poll`,`watch`]},{pattern:`批量|并发`,tokens:[`batch`,`parallel`]},{pattern:`令牌|凭证|鉴权|认证`,tokens:[`token`,`auth`,`credential`]},{pattern:`提取|抽取|解析`,tokens:[`extract`,`parse`]},{pattern:`签名|加签|加密|hook`,tokens:[`signature`,`crypto`,`hook`,`sign`]},{pattern:`协议|消息|帧|handler`,tokens:[`websocket`,`protocol`,`ws`,`handler`]},{pattern:`打包|webpack|混淆|反混淆`,tokens:[`bundle`,`webpack`,`deobfuscate`,`unpack`]},{pattern:`反爬|反检测|指纹|stealth`,tokens:[`antibot`,`stealth`,`fingerprint`,`detection`]},{pattern:`证据|取证|导出|报告|快照`,tokens:[`evidence`,`export`,`report`,`forensic`]},{pattern:`多标签页|多标签|标签页`,tokens:[`tab`,`multi`]},{pattern:`脚本库|脚本仓库`,tokens:[`script`,`library`]},{pattern:`脚本`,tokens:[`script`]},{pattern:`执行|运行`,tokens:[`run`,`execute`]},{pattern:`导出`,tokens:[`export`]},{pattern:`回放|重放`,tokens:[`replay`]},{pattern:`请求`,tokens:[`request`]},{pattern:`鉴权面|认证面|授权面|凭证枚举`,tokens:[`auth`,`surface`,`token`,`credential`]},{pattern:`通道|通信|协议注册|协议枚举`,tokens:[`protocol`,`channel`,`registry`]},{pattern:`人机|挑战|风控|拦截页`,tokens:[`challenge`,`captcha`,`cloudflare`,`turnstile`]},{pattern:`签名谱系|签名链路|加签链路|签名追踪`,tokens:[`signing`,`lineage`,`signature`,`trace`]},{pattern:`复现|重发|篡改|参数篡改`,tokens:[`replay`,`tamper`,`request`]},{pattern:`反混淆链|反混淆管道|清洗|还原`,tokens:[`deobfuscate`,`pipeline`,`transform`,`ast`]},{pattern:`桌面应用|electron|nwjs|预加载`,tokens:[`electron`,`bridge`,`preload`,`ipc`]}],intentToolBoostRules:[{pattern:`(?:端到端闭环|全链路闭环|一键闭环|api(?:[_\\s-]*)capture(?:[_\\s-]*)session|抓取接口|抓包流程)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:18},{tool:`list_extension_workflows`,bonus:12},{tool:`api_probe_batch`,bonus:18},{tool:`network_extract_auth`,bonus:10},{tool:`network_export_har`,bonus:8}]},{pattern:`(?:register|signup|sign\\s*up|账号注册|账户注册|邮箱验证|验证账号|激活账号|注册验证|验证码|邮箱激活|激活链接|mail\\s*verify|email\\s*verifyaccount\\s*pending|keygen)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:12},{tool:`list_extension_workflows`,bonus:8},{tool:`tab_workflow`,bonus:8}]},{pattern:`(?:script\\s*library|script\\s*preset|run\\s*script|脚本库执行|脚本库|执行脚本)`,flags:`i`,boosts:[{tool:`page_script_run`,bonus:22},{tool:`page_script_register`,bonus:16},{tool:`run_extension_workflow`,bonus:10}]},{pattern:`(?:bundle|webpack|js\\s*bundle|脚本包|静态包|源码包)`,flags:`i`,boosts:[{tool:`js_bundle_search`,bonus:20},{tool:`sourcemap_fetch_and_parse`,bonus:10},{tool:`webpack_enumerate`,bonus:8}]},{pattern:`(?:workflow|orchestration|工作流|流程编排|流程自动化)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:26},{tool:`list_extension_workflows`,bonus:16}]},{pattern:`(?=.*(?:抓包|抓取|捕获|capture|sniff|collect))(?=.*(?:鉴权|认证|令牌|凭证|jwt|token|auth|credential))`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:18},{tool:`list_extension_workflows`,bonus:12},{tool:`network_extract_auth`,bonus:18}]},{pattern:`(?:signature|crypto|encrypt|hash|hook|签名|加签|加密)`,flags:`i`,boosts:[{tool:`search_in_scripts`,bonus:14},{tool:`detect_crypto`,bonus:12},{tool:`manage_hooks`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:websocket|\\bws\\b|protocol|socket|handler|协议|消息|帧)`,flags:`i`,boosts:[{tool:`ws_monitor`,bonus:14},{tool:`ws_get_frames`,bonus:12},{tool:`ws_get_connections`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:bundle|webpack|chunk|source.*map|deobfusc|源码|打包|混淆|反混淆)`,flags:`i`,boosts:[{tool:`js_bundle_search`,bonus:18},{tool:`collect_code`,bonus:12},{tool:`sourcemap_fetch_and_parse`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:stealth|fingerprint|webdriver|antibot|bot.*detect|反爬|反检测|指纹)`,flags:`i`,boosts:[{tool:`stealth_inject`,bonus:14},{tool:`stealth_generate_fingerprint`,bonus:12},{tool:`stealth_verify`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:evidence|export.*(?:har|markdown|json)|har|report|证据|导出|报告|取证)`,flags:`i`,boosts:[{tool:`evidence_query`,bonus:16},{tool:`evidence_export`,bonus:14},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:auth.*surface|token.*enum|credential.*map|鉴权面|认证面|凭证枚举|jwt|csrf|api.?key|授权)`,flags:`i`,boosts:[{tool:`network_extract_auth`,bonus:16},{tool:`run_extension_workflow`,bonus:6},{tool:`list_extension_workflows`,bonus:4}]},{pattern:`(?:protocol.*registry|channel.*enum|通道枚举|协议注册|协议归类|SSE|EventSource|beacon|postMessage)`,flags:`i`,boosts:[{tool:`ws_monitor`,bonus:12},{tool:`network_get_requests`,bonus:10},{tool:`sse_monitor_enable`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:challenge|turnstile|cloudflare|hcaptcha|datadome|akamai|perimeterx|kasada|人机|挑战|风控|拦截页)`,flags:`i`,boosts:[{tool:`captcha_detect`,bonus:16},{tool:`stealth_verify`,bonus:12},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:signing.*lineage|签名谱系|签名链路|加签链路|签名追踪|plaintext.*cipher|明文.*密文)`,flags:`i`,boosts:[{tool:`detect_crypto`,bonus:14},{tool:`extract_function_tree`,bonus:12},{tool:`manage_hooks`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:replay.*lab|request.*replay|复现|重发|篡改|参数篡改|request.*tamper)`,flags:`i`,boosts:[{tool:`network_replay_request`,bonus:16},{tool:`instrumentation_network_replay`,bonus:14},{tool:`network_export_har`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:deobfusc.*pipeline|反混淆链|反混淆管道|清洗|还原|ast.*transform|packer|unpack)`,flags:`i`,boosts:[{tool:`webcrack_unpack`,bonus:16},{tool:`ast_transform_apply`,bonus:14},{tool:`deobfuscate`,bonus:12},{tool:`detect_obfuscation`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:electron|nwjs|preload|ipc|asar|桌面应用|预加载|桥接|electron.*bridge)`,flags:`i`,boosts:[{tool:`electron_inspect_app`,bonus:16},{tool:`electron_ipc_sniff`,bonus:14},{tool:`asar_search`,bonus:12},{tool:`electron_check_fuses`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]}],vectorEnabled:t,vectorModelId:n,vectorCosineWeight:e,vectorDynamicWeight:r};export{i as t};
1
+ import{Ji as e,Ki as t,Qi as n,qi as r}from"./constants-nvsLpSri.mjs";const i={queryCategoryProfiles:[{pattern:`(?:security|vuln|xss|injection|csrf|exploit|attack|prototype\\s*pollution|漏洞|安全|注入|攻击)`,flags:`i`,domainBoosts:[{domain:`instrumentation`,weight:1.35},{domain:`debugger`,weight:1.2},{domain:`core`,weight:1.1}]},{pattern:`(?:debug|breakpoint|pause|step\\s*over|step\\s*into|stack\\s*trace|断点|调试|单步)`,flags:`i`,domainBoosts:[{domain:`debugger`,weight:1.6},{domain:`v8-inspector`,weight:1.2}]},{pattern:`(?:network|request|response|header|cookie|fetch|xhr|网络|请求|抓包)`,flags:`i`,domainBoosts:[{domain:`network`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:transform|deobfuscate|beautify|minify|decode|encode|解密|混淆|反混淆|转换)`,flags:`i`,domainBoosts:[{domain:`transform`,weight:1.6},{domain:`core`,weight:1.2}]},{pattern:`(?:memory|heap|dump|scan|inject|内存|堆|扫描)`,flags:`i`,domainBoosts:[{domain:`memory`,weight:1.6},{domain:`process`,weight:1.15},{domain:`binary-instrument`,weight:1.1}]},{pattern:`(?:wasm|webassembly)`,flags:`i`,domainBoosts:[{domain:`wasm`,weight:1.6}]},{pattern:`(?:browser|page|tab|navigate|click|screenshot|浏览器|页面|标签)`,flags:`i`,domainBoosts:[{domain:`browser`,weight:1.4}]},{pattern:`(?:captcha|人机验证|验证码|图形验证)`,flags:`i`,domainBoosts:[{domain:`browser`,weight:1.65}]},{pattern:`(?:reverse|mission|signature|hook|crypto|encrypt|websocket|\\bws\\b|protocol|bundle|webpack|deobfusc|stealthfingerprint|evidence|\\bhar\\b|逆向|签名|加签|协议|反混淆|反检测|指纹|证据|报告)`,flags:`i`,domainBoosts:[{domain:`workflow`,weight:1.8},{domain:`core`,weight:1.1}]},{pattern:`(?:v8|heap\\s?(?:snapshot|dump|profile)|bytecode|jit|turbofan|ignition|hidden\\s?class)`,flags:`i`,domainBoosts:[{domain:`v8-inspector`,weight:1.6},{domain:`memory`,weight:1.2}]},{pattern:`(?:tls|ssl|boringssl|cert(?:ificate)?|pinning|handshake|keylog|nss)`,flags:`i`,domainBoosts:[{domain:`boringssl-inspector`,weight:1.6},{domain:`network`,weight:1.1}]},{pattern:`(?:skia|gpu|render|scenegraph|scene\\s?tree|raster|draw\\s?call|layer)`,flags:`i`,domainBoosts:[{domain:`canvas`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:frida|ghidra|ida|unidbg|jadx|disassemble|instrument)`,flags:`i`,domainBoosts:[{domain:`binary-instrument`,weight:1.6},{domain:`memory`,weight:1.2}]},{pattern:`(?:adb|android|webview|apk|dalvik|art\\s?(?:runtime)?)`,flags:`i`,domainBoosts:[{domain:`adb-bridge`,weight:1.6},{domain:`browser`,weight:1.1}]},{pattern:`(?:mojo|ipc|chromium.*ipc|broker|chromium.*interface)`,flags:`i`,domainBoosts:[{domain:`mojo-ipc`,weight:1.6},{domain:`debugger`,weight:1.1}]},{pattern:`(?:syscall|etw|strace|dtrace|kernel.*call|system\\s?call|tracefs)`,flags:`i`,domainBoosts:[{domain:`syscall-hook`,weight:1.6},{domain:`process`,weight:1.1}]},{pattern:`(?:protocol.*analy|state\\s?machine|packet.*decode|field.*extract)`,flags:`i`,domainBoosts:[{domain:`protocol-analysis`,weight:1.6},{domain:`network`,weight:1.1}]},{pattern:`(?:extension.*(?:install|registry|list)|plugin.*(?:install|manage)|addon|webhook.*(?:create|manage))`,flags:`i`,domainBoosts:[{domain:`extension-registry`,weight:1.6},{domain:`workflow`,weight:1.1}]}],cjkQueryAliases:[{pattern:`工作流|流程编排|流程自动化|编排`,tokens:[`workflow`,`flow`,`orchestration`]},{pattern:`抓包|抓取|采集|捕获`,tokens:[`capture`,`sniff`,`collect`]},{pattern:`接口|端点`,tokens:[`api`,`endpoint`,`request`]},{pattern:`探测|探针|扫描`,tokens:[`probe`,`scan`]},{pattern:`账号|账户|用户`,tokens:[`account`,`user`]},{pattern:`注册|开户|报名`,tokens:[`register`,`signup`]},{pattern:`验证|校验|激活`,tokens:[`verify`,`verification`,`activation`]},{pattern:`验证码|图形验证码|人机验证`,tokens:[`captcha`,`verify`,`verification`]},{pattern:`邮箱|邮件`,tokens:[`email`,`mail`]},{pattern:`keygen|密钥|注册码|激活码`,tokens:[`keygen`,`key`,`activation`]},{pattern:`轮询|监听`,tokens:[`poll`,`watch`]},{pattern:`批量|并发`,tokens:[`batch`,`parallel`]},{pattern:`令牌|凭证|鉴权|认证`,tokens:[`token`,`auth`,`credential`]},{pattern:`提取|抽取|解析`,tokens:[`extract`,`parse`]},{pattern:`签名|加签|加密|hook`,tokens:[`signature`,`crypto`,`hook`,`sign`]},{pattern:`协议|消息|帧|handler`,tokens:[`websocket`,`protocol`,`ws`,`handler`]},{pattern:`打包|webpack|混淆|反混淆`,tokens:[`bundle`,`webpack`,`deobfuscate`,`unpack`]},{pattern:`反爬|反检测|指纹|stealth`,tokens:[`antibot`,`stealth`,`fingerprint`,`detection`]},{pattern:`证据|取证|导出|报告|快照`,tokens:[`evidence`,`export`,`report`,`forensic`]},{pattern:`多标签页|多标签|标签页`,tokens:[`tab`,`multi`]},{pattern:`脚本库|脚本仓库`,tokens:[`script`,`library`]},{pattern:`脚本`,tokens:[`script`]},{pattern:`执行|运行`,tokens:[`run`,`execute`]},{pattern:`导出`,tokens:[`export`]},{pattern:`回放|重放`,tokens:[`replay`]},{pattern:`请求`,tokens:[`request`]},{pattern:`鉴权面|认证面|授权面|凭证枚举`,tokens:[`auth`,`surface`,`token`,`credential`]},{pattern:`通道|通信|协议注册|协议枚举`,tokens:[`protocol`,`channel`,`registry`]},{pattern:`人机|挑战|风控|拦截页`,tokens:[`challenge`,`captcha`,`cloudflare`,`turnstile`]},{pattern:`签名谱系|签名链路|加签链路|签名追踪`,tokens:[`signing`,`lineage`,`signature`,`trace`]},{pattern:`复现|重发|篡改|参数篡改`,tokens:[`replay`,`tamper`,`request`]},{pattern:`反混淆链|反混淆管道|清洗|还原`,tokens:[`deobfuscate`,`pipeline`,`transform`,`ast`]},{pattern:`桌面应用|electron|nwjs|预加载`,tokens:[`electron`,`bridge`,`preload`,`ipc`]}],intentToolBoostRules:[{pattern:`(?:端到端闭环|全链路闭环|一键闭环|api(?:[_\\s-]*)capture(?:[_\\s-]*)session|抓取接口|抓包流程)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:18},{tool:`list_extension_workflows`,bonus:12},{tool:`api_probe_batch`,bonus:18},{tool:`network_extract_auth`,bonus:10},{tool:`network_export_har`,bonus:8}]},{pattern:`(?:register|signup|sign\\s*up|账号注册|账户注册|邮箱验证|验证账号|激活账号|注册验证|验证码|邮箱激活|激活链接|mail\\s*verify|email\\s*verifyaccount\\s*pending|keygen)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:12},{tool:`list_extension_workflows`,bonus:8},{tool:`tab_workflow`,bonus:8}]},{pattern:`(?:script\\s*library|script\\s*preset|run\\s*script|脚本库执行|脚本库|执行脚本)`,flags:`i`,boosts:[{tool:`page_script_run`,bonus:22},{tool:`page_script_register`,bonus:16},{tool:`run_extension_workflow`,bonus:10}]},{pattern:`(?:bundle|webpack|js\\s*bundle|脚本包|静态包|源码包)`,flags:`i`,boosts:[{tool:`js_bundle_search`,bonus:20},{tool:`sourcemap_fetch_and_parse`,bonus:10},{tool:`webpack_enumerate`,bonus:8}]},{pattern:`(?:workflow|orchestration|工作流|流程编排|流程自动化)`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:26},{tool:`list_extension_workflows`,bonus:16}]},{pattern:`(?=.*(?:抓包|抓取|捕获|capture|sniff|collect))(?=.*(?:鉴权|认证|令牌|凭证|jwt|token|auth|credential))`,flags:`i`,boosts:[{tool:`run_extension_workflow`,bonus:18},{tool:`list_extension_workflows`,bonus:12},{tool:`network_extract_auth`,bonus:18}]},{pattern:`(?:signature|crypto|encrypt|hash|hook|签名|加签|加密)`,flags:`i`,boosts:[{tool:`search_in_scripts`,bonus:14},{tool:`detect_crypto`,bonus:12},{tool:`manage_hooks`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:websocket|\\bws\\b|protocol|socket|handler|协议|消息|帧)`,flags:`i`,boosts:[{tool:`ws_monitor`,bonus:14},{tool:`ws_get_frames`,bonus:12},{tool:`ws_get_connections`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:bundle|webpack|chunk|source.*map|deobfusc|源码|打包|混淆|反混淆)`,flags:`i`,boosts:[{tool:`js_bundle_search`,bonus:18},{tool:`collect_code`,bonus:12},{tool:`sourcemap_fetch_and_parse`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:stealth|fingerprint|webdriver|antibot|bot.*detect|反爬|反检测|指纹)`,flags:`i`,boosts:[{tool:`stealth_inject`,bonus:14},{tool:`stealth_generate_fingerprint`,bonus:12},{tool:`stealth_verify`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:evidence|export.*(?:har|markdown|json)|har|report|证据|导出|报告|取证)`,flags:`i`,boosts:[{tool:`evidence_query`,bonus:16},{tool:`evidence_export`,bonus:14},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:auth.*surface|token.*enum|credential.*map|鉴权面|认证面|凭证枚举|jwt|csrf|api.?key|授权)`,flags:`i`,boosts:[{tool:`network_extract_auth`,bonus:16},{tool:`run_extension_workflow`,bonus:6},{tool:`list_extension_workflows`,bonus:4}]},{pattern:`(?:protocol.*registry|channel.*enum|通道枚举|协议注册|协议归类|SSE|EventSource|beacon|postMessage)`,flags:`i`,boosts:[{tool:`ws_monitor`,bonus:12},{tool:`network_get_requests`,bonus:10},{tool:`sse_monitor_enable`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:challenge|turnstile|cloudflare|hcaptcha|datadome|akamai|perimeterx|kasada|人机|挑战|风控|拦截页)`,flags:`i`,boosts:[{tool:`captcha_detect`,bonus:16},{tool:`stealth_verify`,bonus:12},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:signing.*lineage|签名谱系|签名链路|加签链路|签名追踪|plaintext.*cipher|明文.*密文)`,flags:`i`,boosts:[{tool:`detect_crypto`,bonus:14},{tool:`extract_function_tree`,bonus:12},{tool:`manage_hooks`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:replay.*lab|request.*replay|复现|重发|篡改|参数篡改|request.*tamper)`,flags:`i`,boosts:[{tool:`network_replay_request`,bonus:16},{tool:`instrumentation_network_replay`,bonus:14},{tool:`network_export_har`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:deobfusc.*pipeline|反混淆链|反混淆管道|清洗|还原|ast.*transform|packer|unpack)`,flags:`i`,boosts:[{tool:`webcrack_unpack`,bonus:16},{tool:`ast_transform_apply`,bonus:14},{tool:`deobfuscate`,bonus:12},{tool:`detect_obfuscation`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]},{pattern:`(?:electron|nwjs|preload|ipc|asar|桌面应用|预加载|桥接|electron.*bridge)`,flags:`i`,boosts:[{tool:`electron_inspect_app`,bonus:16},{tool:`electron_ipc_sniff`,bonus:14},{tool:`asar_search`,bonus:12},{tool:`electron_check_fuses`,bonus:10},{tool:`run_extension_workflow`,bonus:6}]}],vectorEnabled:e,vectorModelId:n,vectorCosineWeight:t,vectorDynamicWeight:r};export{i as t};
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1 @@
1
+ import{parentPort as e}from"worker_threads";let t=null,n=null;async function r(e){if(t&&n!==e)throw Error(`Embedding worker already loaded model ${n}; cannot switch to ${e}`);if(!t){let{pipeline:r}=await import(`@huggingface/transformers`);t=await r(`feature-extraction`,e,{quantized:!0}),n=e}return t}function i(e,t,n){let r=n&&n.length>0?n[n.length-1]:void 0,i=e.length/t,a=r&&Number.isInteger(r)&&r>0?r:Number.isInteger(i)&&i>0?i:384;if(e.length<t*a)throw Error(`Unexpected embedding tensor size: ${e.length} for ${t}x${a}`);let o=[];for(let n=0;n<t;n++){let t=new Float32Array(a);t.set(e.subarray(n*a,(n+1)*a)),o.push(t)}return o}e?.on(`message`,async t=>{try{let n=t.modelId?.trim()||`Xenova/bge-micro-v2`;if(t.type===`embed`){let i=(await(await r(n))(t.text,{pooling:`mean`,normalize:!0})).data,a=new Float32Array(i);e.postMessage({type:`result`,id:t.id,embedding:a},[a.buffer])}else if(t.type===`embed_batch`){let a=await r(n),o=t.texts,s=[];for(let e=0;e<o.length;e+=32){let t=o.slice(e,e+32);if(t.length!==0)try{let e=await a(t,{pooling:`mean`,normalize:!0}),n=e.data,r=i(n,t.length,e.dims);s.push(...r)}catch{for(let e of t){let t=await a(e,{pooling:`mean`,normalize:!0});s.push(new Float32Array(t.data))}}}e.postMessage({type:`result`,id:t.id,embedding:s})}}catch(n){let r=n instanceof Error?n.message:String(n);e.postMessage({type:`error`,id:t.id,message:r})}});export{};
@@ -0,0 +1 @@
1
+ import{o as e}from"./handlers-BxQv-wtf.mjs";export{e as invokeLegacyPlugin};
@@ -0,0 +1,3 @@
1
+ import{O as e,k as t}from"./constants-nvsLpSri.mjs";import{i as n}from"./artifacts-Bx9GLx4J.mjs";import{d as r,h as i,m as a}from"./ensure-browser-core-BP70x0TB.mjs";import{r as o}from"./ResponseBuilder-BLicSCjn.mjs";import{s}from"./ssrf-policy-B72vdy23.mjs";import{t as c}from"./safeOutput-Dt4mfjXA.mjs";import"./definitions-C-AdFfFu.mjs";import{dirname as l}from"node:path";import{mkdir as u,writeFile as d}from"node:fs/promises";function f(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.version===3&&Array.isArray(t.sections)}const p=new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e,t]));function m(e){let t=(e&1)==1,n=e>>1;return t?-n:n}function h(e){let t=[],n=0;for(;n<e.length;){let r=0,i=0,a=!0;for(;a;){let t=e.charAt(n);if(!t)throw Error(`Unexpected end of VLQ segment: "${e}"`);n+=1;let o=p.get(t);if(o===void 0)throw Error(`Invalid VLQ base64 char "${t}" in segment "${e}"`);a=(o&32)!=0;let s=o&31;r+=s<<i,i+=5}t.push(m(r))}return t}function g(e){let t=[],n=0;for(;n<e.length;){let r=0,i=0,a=!0;for(;a;){let t=e.charAt(n);if(!t)throw Error(`Unexpected end of VLQ segment: "${e}"`);n+=1;let o=p.get(t);if(o===void 0)throw Error(`Invalid VLQ base64 char "${t}" in segment "${e}"`);a=(o&32)!=0;let s=o&31;r+=s<<i,i+=5}t.push(r)}return t}function _(e){if(!e)return[];let t=[],n=0,r=0,i=0,a=0,o=e.split(`;`);for(let e=0;e<o.length;e+=1){let s=o[e]??``,c=0;if(!s)continue;let l=s.split(`,`);for(let o of l){if(!o)continue;let s=h(o),l=s[0];if(l===void 0)continue;c+=l;let u={generatedLine:e+1,generatedColumn:c};s.length>=4&&(n+=s[1]??0,r+=s[2]??0,i+=s[3]??0,u.sourceIndex=n,u.originalLine=r+1,u.originalColumn=i,s.length>=5&&(a+=s[4]??0,u.nameIndex=a)),t.push(u)}}return t}function v(e){if(!e)return{mappingsCount:0,segmentCount:0};let t=0,n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`;`?(r&&t++,r=!1):a===`,`?n++:r||(r=!0,n++)}return r&&t++,{mappingsCount:t,segmentCount:n}}function y(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function b(e,t){return y({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}function x(e){return typeof e==`object`&&e?e:{}}function S(e){return typeof e==`string`?e:void 0}function C(e){return/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)}function w(e,t){return typeof e==`boolean`?e:t}function T(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} is required`);return e.trim()}function E(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}async function D(e){if(e.detach)try{await e.detach()}catch{}}async function O(e,t,n){try{await e.send(t,n)}catch{}}async function k(e){await new Promise(t=>setTimeout(()=>t(),e))}var A=class{state;constructor(e){this.state=e}async handleExtensionListInstalled(e){let t=await(await this.state.collector.getActivePage()).createCDPSession();try{return y((await this.getExtensionTargets(t)).map(e=>({extensionId:e.extensionId,name:e.name,type:e.type,url:e.url})))}catch(e){return b(`extension_list_installed`,e)}finally{await D(t)}}async handleExtensionExecuteInContext(e){let t=T(e.extensionId,`extensionId`),n=T(e.code,`code`),r=w(e.returnByValue,!0),o=await(await this.state.collector.getActivePage()).createCDPSession(),s=null;try{let e=await this.getExtensionTargets(o,t);if(e.length===0)throw Error(`No background target found for extension: ${t}`);let i=this.pickPreferredExtensionTarget(e);s=await a(o,i.targetId);let c=await this.evaluateInAttachedTarget(s,n,r);return y({extensionId:t,target:{type:i.type,url:i.url,name:i.name},result:c.result,exceptionDetails:c.exceptionDetails})}catch(e){return b(`extension_execute_in_context`,e)}finally{s&&await i(o,s).catch(()=>void 0),await D(o)}}async getExtensionTargets(e,t){let n=x(await e.send(`Target.getTargets`)),r=Array.isArray(n.targetInfos)?n.targetInfos:[],i=new Set([`service_worker`,`background_page`]),a=[];for(let e of r){let n=x(e),r=S(n.targetId),o=S(n.type),s=S(n.url);if(!r||!o||!s||!i.has(o))continue;let c=this.extractExtensionId(s);if(!c||t&&c!==t)continue;let l=S(n.title)??``;a.push({targetId:r,extensionId:c,name:l||c,type:o,url:s})}return a.sort((e,t)=>{let n=e.type===`service_worker`?0:1,r=t.type===`service_worker`?0:1;return n===r?e.extensionId.localeCompare(t.extensionId):n-r}),a}pickPreferredExtensionTarget(e){return e.find(e=>e.type===`service_worker`)??e[0]}extractExtensionId(e){return e.match(/^chrome-extension:\/\/([a-p]{32})(?:\/|$)/i)?.[1]??null}async evaluateInAttachedTarget(e,t,n){let r=x(await e.send(`Runtime.evaluate`,{expression:t,returnByValue:n,awaitPromise:!0})),i=x(r.result);return{result:n&&i.value!==void 0?i.value:Object.keys(i).length>0?i:null,exceptionDetails:r.exceptionDetails===void 0?null:r.exceptionDetails}}};function j(e){return{...e.name===void 0?{}:{name:e.name},...e.kind===void 0?{}:{kind:e.kind},isStackFrame:e.isStackFrame,start:{line:e.start.line,column:e.start.column},end:{line:e.end.line,column:e.end.column},variables:[...e.variables],children:e.children.map(j)}}function M(e){return 1+e.children.reduce((e,t)=>e+M(t),0)}function N(e,t){return t?{format:`sourcemap-v4-scopes`,sourcePath:e,scopeCount:M(t),scopes:[j(t)]}:null}function P(e,t,n){return L(e,t,n).then(e=>{let t=_(e.map.mappings),n=new Set(t.map(e=>e.generatedLine));return{resolvedUrl:e.resolvedUrl,map:e.map,mappings:t,mappingsCount:n.size,segmentCount:t.length}})}function F(e,t,n){let r=n.filter(t=>t.sourceIndex===e).toSorted((e,t)=>{let n=(e.originalLine??-1)-(t.originalLine??-1);return n===0?(e.originalColumn??-1)-(t.originalColumn??-1):n}),i=[`/* Inferred source skeleton — sourcesContent was stripped by the vendor.`,` Reconstructed from ${r.length} mapping segment(s): original line:col + bound name.`,` This is NOT real source; variable names and positions only. */`];for(let e of r){let n=`L${e.originalLine??`?`}:${e.originalColumn??`?`}`,r=typeof e.nameIndex==`number`&&e.nameIndex>=0&&e.nameIndex<t.names.length?t.names[e.nameIndex]??null:null;i.push(r?`${n} ${r}`:n)}return i.join(`
2
+ `)+`
3
+ `}function I(e,t,n){return L(e,t,n).then(e=>{let{mappingsCount:t,segmentCount:n}=v(e.map.mappings);return{resolvedUrl:e.resolvedUrl,map:e.map,mappingsCount:t,segmentCount:n}})}async function L(e,t,n){let r=J(e,t??``),i=``;i=r.startsWith(`data:`)?q(r):await G(r,n);let a;try{a=JSON.parse(i)}catch{throw Error(`Invalid SourceMap JSON: ${r}`)}return{resolvedUrl:r,map:R(a)}}function R(e){if(f(e))return z(e);let t=x(e);if(t.version!==3)throw Error(`Only SourceMap version 3 is supported`);let n=S(t.mappings);if(n===void 0)throw Error(`SourceMap.mappings is required`);let r=(Array.isArray(t.sources)?t.sources:[]).map(e=>S(e)).filter(e=>typeof e==`string`),i=(Array.isArray(t.names)?t.names:[]).map(e=>S(e)).filter(e=>typeof e==`string`),a=S(t.sourceRoot),o;return Array.isArray(t.sourcesContent)&&(o=t.sourcesContent.map(e=>typeof e==`string`?e:null)),{version:3,sources:r,sourcesContent:o,mappings:n,names:i,sourceRoot:a}}function z(e){if(e.sections.length===0)throw Error(`Indexed SourceMap has no sections`);let t=[],n=[],r=[],i=[];for(let a of e.sections){if(!a)continue;let e=a.map,o=e.sources.length>0?e.sources:[],s=e.names.length>0?e.names:[],c=e.sourcesContent??[],l=Array.from({length:o.length},()=>0);for(let e=0;e<o.length;e+=1){let n=o[e]??``,i=t.indexOf(n);i>=0?l[e]=i:(l[e]=t.length,t.push(n),r.push(typeof c[e]==`string`?c[e]:null))}let u=Array.from({length:s.length},()=>0);for(let e=0;e<s.length;e+=1){let t=s[e]??``,r=n.indexOf(t);r>=0?u[e]=r:(u[e]=n.length,n.push(t))}let d=_(e.mappings),f=Math.max(0,a.offset.line),p=Math.max(0,a.offset.column);for(let e of d)V(i,e.generatedLine+f,e.generatedLine===1?e.generatedColumn+p:e.generatedColumn,e.sourceIndex===void 0?void 0:l[e.sourceIndex]??e.sourceIndex,e.nameIndex===void 0?void 0:u[e.nameIndex]??e.nameIndex)}return{version:3,sources:t,sourcesContent:r,mappings:i.map(e=>e.segments.join(`,`)).join(`;`),names:n}}function B(e,t){for(;e.length<t;)e.push({segments:[],prev:{column:0,source:0,name:0}});return e[t-1]}function V(e,t,n,r,i){let a=B(e,t),o=a.prev,s=n-o.column;if(o.column=n,r===void 0){a.segments.push(U([s]));return}let c=r-o.source;if(o.source=r,i===void 0){a.segments.push(U([s,c,0,0]));return}let l=i-o.name;o.name=i,a.segments.push(U([s,c,0,0,l]))}const H=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`;function U(e){let t=``;for(let n of e){let e=W(n),r=!0;for(;r;){let n=e&31;e>>=5,e>0?(r=!0,t+=H[n|32]):(r=!1,t+=H[n])}}return t}function W(e){return e<0?-e<<1|1:e<<1}async function G(e,t){K(e);{let t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{let n=await fetch(e,{signal:t.signal});if(!n.ok)throw Error(`HTTP ${n.status} ${n.statusText}`);return await n.text()}catch(t){if(t.name===`AbortError`)throw Error(`SourceMap fetch timed out after 10s: ${e}`,{cause:t})}finally{clearTimeout(n)}}let n=await r(await t.getActivePage(),async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{let n=await fetch(e,{signal:t.signal});return n.ok?await n.text():`__FETCH_ERROR__HTTP ${n.status} ${n.statusText}`}catch(e){return`__FETCH_ERROR__${e instanceof Error?e.message:String(e)}`}finally{clearTimeout(n)}},e);if(typeof n!=`string`)throw Error(`Failed to fetch SourceMap content`);if(n.startsWith(`__FETCH_ERROR__`))throw Error(n.slice(15)||`Failed to fetch SourceMap content`);return n}function K(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Blocked: unsupported protocol "${t.protocol}"`);let n=t.hostname.toLowerCase();if([`localhost`,`metadata.google.internal`,`metadata`].includes(n))throw Error(`SSRF blocked: hostname "${n}" is not allowed`);if(s(n))throw Error(`SSRF blocked: protected/reserved IP "${n}" is not allowed`)}function q(e){let t=e.indexOf(`,`);if(t===-1)throw Error(`Invalid data URI source map`);let n=e.slice(0,t),r=e.slice(t+1);return/;base64/i.test(n)?Buffer.from(r,`base64`).toString(`utf-8`):decodeURIComponent(r)}function J(e,t){let n=e.trim();if(!n)return``;if(n.startsWith(`data:`)||C(n)||!t)return n;try{return new URL(n,t).toString()}catch{return n}}function Y(e){let t=e.slice(-8192),n=/(?:\/\/[@#]\s*sourceMappingURL=([^\s]+)|\/\*[@#]\s*sourceMappingURL=([^*]+)\*\/)/g,r,i=null;for(;r=n.exec(t),r;){let e=(r[1]??r[2]??``).trim();e&&(i=e)}return i}function X(e,t){if(!e)return t;if(!t)return e;if(C(t)||t.startsWith(`/`))return t;if(C(e))try{let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t,n).toString()}catch{return`${e.replace(/\/+$/g,``)}/${t.replace(/^\/+/g,``)}`}return`${e.replace(/\/+$/g,``)}/${t.replace(/^\/+/g,``)}`}function Z(e,t){let n=e.trim();if(!n)return`source_${t+1}.js`;if(n.startsWith(`webpack://`)&&(n=n.slice(10)),n.startsWith(`data:`))return`inline/source_${t+1}.txt`;if(C(n))try{let e=new URL(n);n=`${e.hostname}${e.pathname}`}catch{n=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,``)}n=n.replace(/[?#].*$/g,``),n=n.replace(/^[A-Za-z]:[\\/]/,``),n=n.replace(/^\/+/,``);let r=n.split(/[\\/]+/).map(e=>ee(e)).filter(e=>e!==``&&e!==`.`&&e!==`..`);return r.length===0?`source_${t+1}.js`:r.join(`/`)}function ee(e){let t=Array.from(e,e=>{let t=e.codePointAt(0);return t!==void 0&&(t<=31||`<>:"|?*`.includes(e))?`_`:e}).join(``).replace(/\s+/g,` `).trim();return!t||t===`.`||t===`..`?`_`:t}function te(e){return e.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,``).replace(/[^a-zA-Z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_|_$/g,``).slice(0,48)}function ne(e,t,n=1){let r=new Set(e.map.sources),i=new Set(t.map.sources),a=[...i].filter(e=>!r.has(e)).toSorted(),o=[...r].filter(e=>!i.has(e)).toSorted(),s=[...r].filter(e=>i.has(e)).toSorted(),c=new Set(e.map.names),l=new Set(t.map.names),u=[...l].filter(e=>!c.has(e)).toSorted(),d=[...c].filter(e=>!l.has(e)).toSorted(),f=e.segmentCount,p=t.segmentCount,m=new Map,h=new Map,g=new Map,_=new Map;for(let t of e.mappings){if(t.sourceIndex===void 0)continue;let n=e.map.sources[t.sourceIndex];if(n===void 0||(m.set(n,(m.get(n)??0)+1),t.originalLine===void 0))continue;let r=`${t.sourceIndex}:${t.originalLine}:${t.originalColumn??0}`,i=g.get(n);i||(i=new Map,g.set(n,i)),i.set(r,{line:t.generatedLine,col:t.generatedColumn})}for(let e of t.mappings){if(e.sourceIndex===void 0)continue;let n=t.map.sources[e.sourceIndex];if(n===void 0||(h.set(n,(h.get(n)??0)+1),e.originalLine===void 0))continue;let r=`${e.sourceIndex}:${e.originalLine}:${e.originalColumn??0}`,i=_.get(n);i||(i=new Map,_.set(n,i)),i.set(r,{line:e.generatedLine,col:e.generatedColumn})}let v={},y=new Set([...r,...i]);for(let e of y){let t=m.get(e)??0,r=h.get(e)??0,i=g.get(e),a=_.get(e),o=0;if(i&&a)for(let[e,t]of i){let r=a.get(e);r&&Math.abs(r.line-t.line)>=n&&o++}v[e]={segmentsBefore:t,segmentsAfter:r,delta:r-t,positionsShifted:o}}return{sourcesAdded:a,sourcesRemoved:o,sourcesUnmodified:s,namesAdded:u,namesRemoved:d,segmentsBefore:f,segmentsAfter:p,segmentDelta:p-f,perSourceDeltas:v}}function Q(e){let t=0;for(let n of e)n&&(t+=1+Q(n.children));return t}var re=class{state;constructor(e){this.state=e}async handleSourcemapDiscover(e){let n=w(e.includeInline,!0),r=await(await this.state.collector.getActivePage()).createCDPSession(),i=new Map,a=e=>{let t=x(e),n=S(t.scriptId);if(!n)return;let r=S(t.url)??``,a=S(t.sourceMapURL)??``,o=i.get(n),s=a?J(a,r):o?.sourceMapUrl??``;i.set(n,{scriptId:n,scriptUrl:r||o?.scriptUrl||``,sourceMapUrl:s,isInline:s.startsWith(`data:`)})};try{r.on?.(`Debugger.scriptParsed`,a),await r.send(`Debugger.enable`),await k(t);for(let e of i.values())if(!e.sourceMapUrl&&!(!e.scriptId||!e.scriptUrl))try{let t=S(x(await r.send(`Debugger.getScriptSource`,{scriptId:e.scriptId})).scriptSource);if(!t)continue;let n=Y(t);if(!n)continue;let i=J(n,e.scriptUrl);e.sourceMapUrl=i,e.isInline=i.startsWith(`data:`)}catch{continue}return y(Array.from(i.values()).filter(e=>e.sourceMapUrl.length>0).filter(e=>n||!e.isInline).toSorted((e,t)=>{let n=`${e.scriptUrl}|${e.scriptId}`,r=`${t.scriptUrl}|${t.scriptId}`;return n.localeCompare(r)}).map(e=>({scriptUrl:e.scriptUrl,sourceMapUrl:e.sourceMapUrl,isInline:e.isInline,scriptId:e.scriptId})))}catch(e){return b(`sourcemap_discover`,e)}finally{r.off?.(`Debugger.scriptParsed`,a),await O(r,`Debugger.disable`),await D(r)}}async handleSourcemapFetchAndParse(e){try{let t=await P(T(e.sourceMapUrl,`sourceMapUrl`),E(e.scriptUrl),this.state.collector),n={sources:t.map.sources,mappingsCount:t.mappingsCount,segmentCount:t.segmentCount};return Array.isArray(t.map.sourcesContent)&&(n.sourcesContent=t.map.sourcesContent),y(n)}catch(e){return b(`sourcemap_fetch_and_parse`,e)}}async handleSourcemapCoverage(e){try{let t=T(e.sourceMapUrl,`sourceMapUrl`),n=await P(t,E(e.scriptUrl),this.state.collector),r=new Map,i=new Map,a=0;for(let e=0;e<n.mappings.length;e+=1){let t=n.mappings[e];if(!t)continue;let o=n.mappings[e+1],s=1;if(o&&o.generatedLine===t.generatedLine&&(s=Math.max(o.generatedColumn-t.generatedColumn,1)),t?.sourceIndex===void 0){a+=s;continue}r.set(t.sourceIndex,(r.get(t.sourceIndex)??0)+s),i.set(t.sourceIndex,(i.get(t.sourceIndex)??0)+1)}let o=n.map.sources.map((e,t)=>{let a=r.get(t)??0,o=i.get(t)??0,s=n.map.sourcesContent?.[t],c=typeof s==`string`?Buffer.byteLength(s,`utf-8`):null,l=c===null?null:Math.max(c-a,0),u=c&&c>0?Number((a/c*100).toFixed(2)):null;return{source:e,generatedSegments:o,mappedBytes:a,coveredBytes:a,unmappedBytes:l,coveragePercent:u,coveredPercent:u,sourceContentBytes:c}}),s=o.reduce((e,t)=>e+(typeof t.coveredBytes==`number`?t.coveredBytes:0),0);return y({sourceMapUrl:t,resolvedUrl:n.resolvedUrl,totalMappings:n.segmentCount,mappedSourceCount:o.filter(e=>e.generatedSegments>0).length,coveredBytes:s,uncoveredGeneratedBytes:a,buckets:[{source:`[unmapped]`,generatedSegments:n.mappings.filter(e=>e.sourceIndex===void 0).length,coveredBytes:a}],sources:o})}catch(e){return b(`sourcemap_coverage`,e)}}async handleSourcemapLookup(e){try{let t=T(e.sourceMapUrl,`sourceMapUrl`),n=await P(t,E(e.scriptUrl),this.state.collector),r=E(e.originalSource)??e.original;if(typeof r==`string`){let i=Number(e.originalLine),a=Number(e.originalColumn);if(!Number.isInteger(i)||i<1)throw Error(`originalLine must be a positive integer`);if(!Number.isFinite(a)||a<0)throw Error(`originalColumn must be a non-negative number`);let o=n.map.sources.indexOf(r);if(o===-1)return y({success:!1,sourceMapUrl:t,resolvedUrl:n.resolvedUrl,original:{source:r,line:i,column:a},error:`Original source not present in this source map`});let s=n.mappings.filter(e=>e.sourceIndex===o&&(e.originalLine??1/0)<=i).toSorted((e,t)=>{let n=(t.originalLine??0)-(e.originalLine??0);return n===0?(t.originalColumn??0)-(e.originalColumn??0):n})[0];return y(s?{success:!0,sourceMapUrl:t,resolvedUrl:n.resolvedUrl,original:{source:r,line:i,column:a},generated:{line:s.generatedLine,column:s.generatedColumn,name:typeof s.nameIndex==`number`?n.map.names[s.nameIndex]??null:null},matchType:s.originalLine===i&&s.originalColumn===a?`exact`:`closest-preceding`}:{success:!1,sourceMapUrl:t,resolvedUrl:n.resolvedUrl,original:{source:r,line:i,column:a},error:`No generated position maps to this original source`})}let i=Number(e.line),a=Number(e.column);if(!Number.isInteger(i)||i<1)throw Error(`line must be a positive integer`);if(!Number.isFinite(a)||a<0)throw Error(`column must be a non-negative number`);let o=n.mappings.find(e=>e.generatedLine===i&&e.generatedColumn===a);if(!o){let e=n.mappings.filter(e=>e.generatedLine===i&&e.generatedColumn<=a);o=e.length>0?e[e.length-1]:void 0}if(!o||o.sourceIndex===void 0)return y({success:!1,sourceMapUrl:t,resolvedUrl:n.resolvedUrl,generated:{line:i,column:a},error:`No original source mapping found for generated position`});let s=o.sourceIndex;return y({success:!0,sourceMapUrl:t,resolvedUrl:n.resolvedUrl,generated:{line:i,column:a},original:{source:n.map.sources[s]??null,line:o.originalLine??null,column:o.originalColumn??null,name:typeof o.nameIndex==`number`?n.map.names[o.nameIndex]??null:null,sourceIndex:s},matchType:o.generatedLine===i&&o.generatedColumn===a?`exact`:`closest-preceding`})}catch(e){return b(`sourcemap_lookup`,e)}}async handleSourcemapReconstructTree(e){try{let t=T(e.sourceMapUrl,`sourceMapUrl`),r=E(e.outputDir),i=w(e.inferMissing,!1),a=w(e.emitScopes,!1),o=await I(t,void 0,this.state.collector),s=i?_(o.map.mappings):void 0,f=null;if(a)try{let e=await G(o.resolvedUrl,this.state.collector),t=JSON.parse(e),n=typeof t.scopes==`string`?t.scopes:typeof t.x_scopes==`string`?t.x_scopes:void 0;n&&(f=$(n,o.map.names,o.map.sources).originalScopes)}catch{}let p=await n({category:`reports`,toolName:`sourcemap-tree`,target:te(o.resolvedUrl),ext:`tmp`,...r?{customDir:r}:{}}),m=p.absolutePath.replace(/\.tmp$/i,``),h=p.displayPath.replace(/\.tmp$/i,``);await u(m,{recursive:!0});let g=[],v=[],b=0;for(let e=0;e<o.map.sources.length;e+=1){let t=o.map.sources[e]??``,n=X(o.map.sourceRoot,t),r=Z(n,e),a;try{a=c(m,r,`reconstructed source path`)}catch{b+=1;continue}let p=o.map.sourcesContent&&e<o.map.sourcesContent.length?o.map.sourcesContent[e]:null,h=typeof p==`string`?p:i&&s?F(e,o.map,s):`/* source content missing in source map: ${n} */\n`;try{if(await u(l(a),{recursive:!0}),await d(a,h,`utf-8`),g.push(r),f){let t=N(n,f[e]??null);t&&(await d(`${a}.scopes.json`,JSON.stringify(t,null,2),`utf-8`),v.push(`${r}.scopes.json`))}}catch{b+=1}}return y({outputDir:h,totalSources:o.map.sources.length,writtenFiles:g.length,skippedFiles:b,scopeSidecars:v.length,files:g,...v.length>0?{scopeSidecarFiles:v}:{}})}catch(e){return b(`sourcemap_reconstruct_tree`,e)}}async handleSourcemapDiff(e){try{let t=T(e.sourceMapUrl,`sourceMapUrl`),n=T(e.sourceMapUrlB,`sourceMapUrlB`),r=E(e.scriptUrl),i=E(e.scriptUrlB),a=typeof e.positionThreshold==`number`&&e.positionThreshold>=1?e.positionThreshold:1,[o,s]=await Promise.all([P(t,r,this.state.collector),P(n,i,this.state.collector)]),c=ne(o,s,a);return y({mapA:{resolvedUrl:o.resolvedUrl,sources:o.map.sources.length,names:o.map.names.length,segments:o.segmentCount},mapB:{resolvedUrl:s.resolvedUrl,sources:s.map.sources.length,names:s.map.names.length,segments:s.segmentCount},diff:c})}catch(e){return b(`sourcemap_diff`,e)}}async handleSourcemapParseV4(t){let n=T(t.sourceMapUrl,`sourceMapUrl`),r=w(t.extractScopes,!0),i=w(t.extractDebugIds,!0);try{let a=await G(n,this.state.collector),o=JSON.parse(a),s=Array.isArray(o.names)?o.names.filter(e=>typeof e==`string`):[],c=Array.isArray(o.sources)?o.sources.filter(e=>typeof e==`string`):[],l={version:o.version,sources:c.length,names:s.length,mappings:typeof o.mappings==`string`?o.mappings.length:0,hasFile:typeof o.file==`string`,hasSourceRoot:typeof o.sourceRoot==`string`},u={success:!0,sourceMapUrl:n,version:o.version,v3Baseline:l};if(i&&typeof o.debugId==`string`){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o.debugId);u.debugId=o.debugId,u.debugIdValid=e}let d=typeof o.scopes==`string`?o.scopes:typeof o.x_scopes==`string`?o.x_scopes:void 0;if(r&&d)try{let e=$(d,s,c);u.isV4=!0,u.scopes=e,u.scopeCount=Q(e.originalScopes),u.generatedRangeCount=e.generatedRanges.length}catch(t){u.success=!1,u.scopeDecodeError=t instanceof Error?t.message:String(t),u.rawScopesField=d.substring(0,e)+(d.length>e?`...`:``),u.isV4=!0}let f={};return o.x_scopeLines&&(f.x_scopeLines=o.x_scopeLines),o.x_namesIdx&&(f.x_namesIdx=o.x_namesIdx),o.x_computedBases&&(f.x_computedBases=o.x_computedBases),Object.keys(f).length>0&&(u.extensions=f),!d&&!o.debugId&&Object.keys(f).length===0&&(u.isV4=!1,u.note=`No v4 fields (scopes/debugId) found. This source map is v3 only.`),t.compareV3===!0&&(u.comparison={v3Only:[`version`,`sources`,`names`,`mappings`,`file`,`sourceRoot`],v4Only:Object.keys(u).filter(e=>![`success`,`sourceMapUrl`,`version`,`v3Baseline`,`comparison`].includes(e))}),y(u)}catch(e){return b(`sourcemap_parse_v4`,e)}}};function $(e,t,n){let r=e.split(`,`),i={value:0},a=[],o=0,s=0,c=0,l=0,u=0,d=0,f=e=>e>0&&e<=t.length?t[e-1]:void 0;function p(e){return e>=0&&e<r.length?r[e]:void 0}function m(e,n){let l=p(i.value++);if(!l?.startsWith(`B`))throw Error(`expected original scope start 'B', got "${l}"`);let u=g(l.slice(1)),d=h(l.slice(1)),f=0,_=u[f++]??0,v=n.line+(u[f++]??0),y=u[f++]??0,b=v===n.line?n.column+y:y,x;_&1&&(o+=d[f++]??0,x=t[o]);let S;_&2&&(s+=d[f++]??0,S=t[s]);let C={index:a.length,sourceIndex:e,start:{line:v,column:b},end:{line:v,column:b},name:x,kind:S,isStackFrame:(_&4)!=0,variables:[],children:[]};a.push(C);let w={line:v,column:b};for(;i.value<r.length;){let n=r[i.value]??``;if(n.startsWith(`D`)){i.value++;let e=h(n.slice(1));for(let n of e)c+=n,C.variables.push(t[c]??`<name:${c}>`);continue}if(n.startsWith(`B`)){let t=m(e,w);w={...t.end},C.children.push(t);continue}break}let T=p(i.value++);if(!T?.startsWith(`C`))throw Error(`expected original scope end 'C', got "${T}"`);let E=g(T.slice(1)),D=w.line+(E[0]??0),O=E[1]??0;return C.end={line:D,column:D===w.line?w.column+O:O},C}function _(e){let t=p(i.value++);if(!t?.startsWith(`E`))throw Error(`expected generated range start 'E', got "${t}"`);let n=g(t.slice(1)),a=h(t.slice(1)),o=0,s=n[o++]??0,c=(s&1)!=0,m=e.line+(c?n[o++]??0:0),v=n[o++]??0,y=m===e.line?e.column+v:v,b;s&2&&(d+=a[o++]??0,b=d);let x={start:{line:m,column:y},end:{line:m,column:y},isStackFrame:(s&4)!=0,isHidden:(s&8)!=0,definitionIndex:b,children:[]},S=new Map,C=0,w={line:m,column:y};for(;i.value<r.length;){let e=r[i.value]??``;if(e.startsWith(`G`)){i.value++,x.bindings=g(e.slice(1)).map(e=>f(e));continue}if(e.startsWith(`H`)){i.value++;let t=g(e.slice(1));x.bindings||=[];let n=0;C+=t[n++]??0;let r=C,a=[],o=S.get(r)??{line:x.start.line,column:x.start.column};for(;n<t.length;){let e=f(t[n++]??0),r=t[n++]??0,i=o.line+r,s=t[n++]??0,c=i===o.line?o.column+s:s;a.push({from:{line:i,column:c},expression:e}),o={line:i,column:c}}for(S.set(r,o);x.bindings.length<=r;)x.bindings.push(void 0);x.bindings[r]=a;continue}if(e.startsWith(`I`)){i.value++;let t=g(e.slice(1));x.callsite={sourceIndex:t[0]??0,line:t[1]??0,column:t[2]??0};continue}if(e.startsWith(`E`)){let e=_(w);w={...e.end},x.children.push(e);continue}break}let T=p(i.value++);if(!T?.startsWith(`F`))throw Error(`expected generated range end 'F', got "${T}"`);let E=g(T.slice(1)),D=E.length===2,O=w.line+(D?E[0]??0:0),k=E[+!!D]??0,A=O===w.line?w.column+k:k;return x.end={line:O,column:A},l=O,u=A,x}let v=Array.from({length:n.length},()=>null);for(let e=0;e<n.length&&i.value<r.length;e++){if((r[i.value]??``)===``){i.value++;continue}if(!(r[i.value]??``).startsWith(`B`))break;v[e]=m(e,{line:0,column:0}),(r[i.value]??``)===``&&i.value++}let y=[];for(;i.value<r.length;){if((r[i.value]??``)===``){i.value++;continue}y.push(_({line:l,column:u}))}return{originalScopes:v,generatedRanges:y}}var ie=class{collector;extension;sourcemap;constructor(e){this.collector=e;let t={collector:e};this.extension=new A(t),this.sourcemap=new re(t)}async handleExtensionListInstalledTool(e){return o(async()=>await this.handleExtensionListInstalled(e))}handleExtensionListInstalled(e){return this.extension.handleExtensionListInstalled(e)}async handleExtensionExecuteInContextTool(e){return o(async()=>await this.handleExtensionExecuteInContext(e))}handleExtensionExecuteInContext(e){return this.extension.handleExtensionExecuteInContext(e)}async handleSourcemapDiscoverTool(e){return o(async()=>await this.handleSourcemapDiscover(e))}handleSourcemapDiscover(e){return this.sourcemap.handleSourcemapDiscover(e)}async handleSourcemapFetchAndParseTool(e){return o(async()=>await this.handleSourcemapFetchAndParse(e))}handleSourcemapFetchAndParse(e){return this.sourcemap.handleSourcemapFetchAndParse(e)}async handleSourcemapCoverageTool(e){return o(async()=>await this.handleSourcemapCoverage(e))}handleSourcemapCoverage(e){return this.sourcemap.handleSourcemapCoverage(e)}async handleSourcemapLookupTool(e){return o(async()=>await this.handleSourcemapLookup(e))}handleSourcemapLookup(e){return this.sourcemap.handleSourcemapLookup(e)}async handleSourcemapReconstructTreeTool(e){return o(async()=>await this.handleSourcemapReconstructTree(e))}handleSourcemapReconstructTree(e){return this.sourcemap.handleSourcemapReconstructTree(e)}async handleSourcemapParseV4Tool(e){return o(async()=>await this.handleSourcemapParseV4(e))}handleSourcemapParseV4(e){return this.sourcemap.handleSourcemapParseV4(e)}async handleSourcemapDiffTool(e){return o(async()=>await this.handleSourcemapDiff(e))}handleSourcemapDiff(e){return this.sourcemap.handleSourcemapDiff(e)}};export{ie as SourcemapToolHandlers};
@@ -0,0 +1,15 @@
1
+ import{t as e}from"./logger-BGCcd-jJ.mjs";import{_ as t,g as n}from"./constants-nvsLpSri.mjs";import{i as r}from"./artifacts-Bx9GLx4J.mjs";import{t as i}from"./RingBuffer-B6RTHmij.mjs";import{d as a,u as o}from"./ensure-browser-core-BP70x0TB.mjs";import{r as s}from"./ResponseBuilder-BLicSCjn.mjs";import{n as c}from"./grpc-raw-Dp7ps2sv.mjs";import"./definitions-BKpRDjcI.mjs";import{writeFile as l}from"node:fs/promises";function u(e){return{collector:e,wsSession:null,wsListeners:null,wsConfig:{enabled:!1,maxFrames:1e3},wsFramesByRequest:new Map,wsFrameOrder:new i(1e3),wsConnections:new Map,sseConfig:{maxEvents:2e3},fetchStreamConfig:{maxEvents:2e3},webrtcConfig:{maxEvents:2e3},grpcSession:null,grpcListeners:null,grpcConfig:{enabled:!1,maxCalls:100},grpcCalls:new Map,grpcCallOrder:new i(100)}}function d(e){return typeof e==`string`?e.trim().toLowerCase().startsWith(`application/grpc`):!1}function f(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function p(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function m(e,t){let n;if(typeof e==`number`&&Number.isFinite(e))n=e;else if(typeof e==`string`){let t=Number(e.trim());Number.isFinite(t)&&(n=t)}return n===void 0&&(n=t.defaultValue),t.integer&&(n=Math.trunc(n)),n<t.min&&(n=t.min),n>t.max&&(n=t.max),n}function h(e){return e===`sent`||e===`received`||e===`all`?e:`all`}function g(e,t){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return t}function _(e){try{return{regex:new RegExp(e)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}const v=e=>typeof e==`object`&&e?e:void 0,y=(e,t)=>{let n=v(e)?.[t];return typeof n==`string`?n:void 0},b=(e,t)=>{let n=v(e)?.[t];return typeof n==`number`?n:void 0},x=(e,t)=>{let n=v(e)?.[t];return v(n)},S=e=>e===`ndjson`?`ndjson`:`json`;function C(){let e=window;if(e.__jshookWsInstancesPatched)return{success:!0,patched:!1,alreadyPatched:!0};let t={};e.__jshookWsInstances=t;let n=e.WebSocket,r=function(e,r){let i=r===void 0?new n(e):new n(e,r),a=String(e),o=t[a]??[];return o.push(i),t[a]=o,i.addEventListener(`close`,()=>{let e=t[a];if(!e)return;let n=e.indexOf(i);n>=0&&e.splice(n,1),e.length===0&&delete t[a]}),i};r.prototype=n.prototype;try{r.CONNECTING=n.CONNECTING,r.OPEN=n.OPEN,r.CLOSING=n.CLOSING,r.CLOSED=n.CLOSED}catch{}return e.WebSocket=r,e.__jshookWsInstancesPatched=!0,{success:!0,patched:!0}}var w=class{s;constructor(e){this.s=e}async teardownWsSession(){if(this.s.wsSession&&this.s.wsListeners){try{this.s.wsSession.off(`Network.webSocketCreated`,this.s.wsListeners.created)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketCreated listener`,t)}try{this.s.wsSession.off(`Network.webSocketClosed`,this.s.wsListeners.closed)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketClosed listener`,t)}try{this.s.wsSession.off(`Network.webSocketHandshakeResponseReceived`,this.s.wsListeners.handshake)}catch(t){e.debug(`[ws-teardown] Failed to remove handshakeResponseReceived listener`,t)}try{this.s.wsSession.off(`Network.webSocketFrameSent`,this.s.wsListeners.frameSent)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketFrameSent listener`,t)}try{this.s.wsSession.off(`Network.webSocketFrameReceived`,this.s.wsListeners.frameReceived)}catch(t){e.debug(`[ws-teardown] Failed to remove webSocketFrameReceived listener`,t)}}if(this.s.wsSession)try{await this.s.wsSession.detach()}catch(t){e.debug(`[ws-teardown] Failed to detach CDP session`,t)}this.s.wsSession=null,this.s.wsListeners=null}handleWsFrame(e,r){let i=y(r,`requestId`);if(!i)return;if(!this.s.wsConnections.get(i)){if(this.s.wsConfig.urlFilter)return;this.s.wsConnections.set(i,{requestId:i,url:`unknown`,status:`open`,framesCount:0,createdTimestamp:Date.now()/1e3})}let a=this.s.wsConnections.get(i);if(!a||this.s.wsConfig.urlFilter&&a.url!==`unknown`&&!this.s.wsConfig.urlFilter.test(a.url))return;let o=x(r,`response`),s=b(o,`opcode`)??-1,c=y(o,`payloadData`)??``,l=c.length>n?`${c.slice(0,n)}…`:c,u=c.length>t?c.slice(0,t):c,d={requestId:i,timestamp:b(r,`timestamp`)??Date.now()/1e3,direction:e,opcode:s,payloadLength:c.length,payloadPreview:l,payloadSample:u,payload:c,isBinary:s===2};this.appendWsFrame(i,d)}appendWsFrame(e,t){let n=this.s.wsFramesByRequest.get(e)??[];n.push(t),this.s.wsFramesByRequest.set(e,n);let r=this.s.wsConnections.get(e);r&&(r.framesCount+=1,r.status===`connecting`&&(r.status=`open`)),this.s.wsFrameOrder.push({requestId:e,frame:t}),this.enforceWsFrameLimit()}enforceWsFrameLimit(){for(;this.s.wsFrameOrder.length>this.s.wsConfig.maxFrames;){let e=this.s.wsFrameOrder.shift();if(!e)break;let t=this.s.wsFramesByRequest.get(e.requestId);t&&t.length>0&&(t.shift(),t.length===0?this.s.wsFramesByRequest.delete(e.requestId):this.s.wsFramesByRequest.set(e.requestId,t));let n=this.s.wsConnections.get(e.requestId);n&&(n.framesCount=Math.max(0,n.framesCount-1))}}getWsFrameStats(){let e=0,t=0;for(let n of this.s.wsFrameOrder)n.frame.direction===`sent`?e+=1:t+=1;return{total:this.s.wsFrameOrder.length,sent:e,received:t}}selectWsFrames(e){let t=h(e.direction),n=p(e.payloadFilter),r;if(n){let e=_(n);if(e.error)return{direction:t,payloadFilterRaw:n,filtered:[],error:`Invalid payloadFilter regex: ${e.error}`};r=e.regex}return{direction:t,payloadFilterRaw:n,filtered:this.s.wsFrameOrder.toArray().map(e=>e.frame).filter(e=>t===`all`?!0:e.direction===t).filter(e=>r?r.test(e.payload??e.payloadSample):!0)}}getConnectionDurationSeconds(e){return e.closedTimestamp===void 0?null:Math.max(0,Number((e.closedTimestamp-e.createdTimestamp).toFixed(3)))}async handleWsMonitorEnable(t){let n=m(t.maxFrames,{defaultValue:1e3,min:1,max:2e4,integer:!0}),r=p(t.urlFilter),o=g(t.exposeInstances,!1),s;if(r){let e=_(r);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`});s=e.regex}await this.teardownWsSession(),this.s.wsFramesByRequest.clear(),this.s.wsFrameOrder=new i(n),this.s.wsConnections.clear();let c=await this.s.collector.getActivePage(),l=await c.createCDPSession();await l.send(`Network.enable`);let u={created:e=>{let t=y(e,`requestId`),n=y(e,`url`);if(!t||!n||s&&!s.test(n))return;let r=this.s.wsConnections.get(t);this.s.wsConnections.set(t,{requestId:t,url:n,status:r?.status??`connecting`,framesCount:r?.framesCount??0,createdTimestamp:r?.createdTimestamp??Date.now()/1e3,closedTimestamp:r?.closedTimestamp,handshakeStatus:r?.handshakeStatus})},closed:e=>{let t=y(e,`requestId`);if(!t)return;let n=this.s.wsConnections.get(t);if(!n)return;n.status=`closed`;let r=b(e,`timestamp`);n.closedTimestamp=r===void 0?Date.now()/1e3:r},handshake:e=>{let t=y(e,`requestId`);if(!t)return;let n=this.s.wsConnections.get(t);if(!n)return;let r=b(x(e,`response`),`status`);r!==void 0&&(n.handshakeStatus=r,n.status=r>=100&&r<400?`open`:`error`)},frameSent:e=>{this.handleWsFrame(`sent`,e)},frameReceived:e=>{this.handleWsFrame(`received`,e)}};if(l.on(`Network.webSocketCreated`,u.created),l.on(`Network.webSocketClosed`,u.closed),l.on(`Network.webSocketHandshakeResponseReceived`,u.handshake),l.on(`Network.webSocketFrameSent`,u.frameSent),l.on(`Network.webSocketFrameReceived`,u.frameReceived),this.s.wsSession=l,this.s.wsListeners=u,this.s.wsConfig={enabled:!0,maxFrames:n,urlFilterRaw:r,urlFilter:s},o)try{await a(c,C)}catch(t){e.debug(`[ws-monitor] failed to install instance-exposure wrapper`,t)}return f({success:!0,message:`WebSocket monitor enabled`,config:{maxFrames:n,urlFilter:r??null,exposeInstances:o},stats:{trackedConnections:this.s.wsConnections.size,capturedFrames:this.s.wsFrameOrder.length}})}async handleWsMonitorDisable(e){let t=this.getWsFrameStats(),n=Array.from(this.s.wsConnections.values()),r={success:!0,message:`WebSocket monitor disabled`,config:{maxFrames:this.s.wsConfig.maxFrames,urlFilter:this.s.wsConfig.urlFilterRaw??null},summary:{trackedConnections:n.length,activeConnections:n.filter(e=>e.status===`open`||e.status===`connecting`).length,closedConnections:n.filter(e=>e.status===`closed`).length,totalFrames:t.total,sentFrames:t.sent,receivedFrames:t.received}};return await this.teardownWsSession(),this.s.wsConfig={...this.s.wsConfig,enabled:!1},f(r)}async handleWsGetFrames(e){let t=m(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),n=m(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0}),r=g(e.fullPayload,!1),{direction:i,payloadFilterRaw:a,filtered:o,error:s}=this.selectWsFrames(e);if(s)return f({success:!1,error:s});let c=o.slice(n,n+t).map(e=>{let t={requestId:e.requestId,timestamp:e.timestamp,direction:e.direction,opcode:e.opcode,payloadLength:e.payloadLength,payloadPreview:e.payloadPreview,isBinary:e.isBinary};return r&&(t.payload=e.payload??e.payloadSample),t});return f({success:!0,monitorEnabled:this.s.wsConfig.enabled,filters:{direction:i,payloadFilter:a??null,fullPayload:r},page:{offset:n,limit:t,returned:c.length,totalAfterFilter:o.length,hasMore:n+c.length<o.length,nextOffset:n+c.length<o.length?n+c.length:null},frames:c})}async handleWsGetConnections(e){let t=Array.from(this.s.wsConnections.values()).toSorted((e,t)=>e.createdTimestamp-t.createdTimestamp).map(e=>{let t=this.getConnectionDurationSeconds(e);return{requestId:e.requestId,url:e.url,status:e.status,framesCount:e.framesCount,createdTimestamp:e.createdTimestamp,closedTimestamp:e.closedTimestamp??null,durationSeconds:t,framesPerSecond:t&&t>0?Number((e.framesCount/t).toFixed(3)):null,handshakeStatus:e.handshakeStatus??null}});return f({success:!0,monitorEnabled:this.s.wsConfig.enabled,total:t.length,connections:t})}async handleWsExportCapture(e){let t=S(e.format),n=g(e.includePayload,!0),{direction:i,payloadFilterRaw:a,filtered:o,error:s}=this.selectWsFrames(e);if(s)return f({success:!1,error:s});let c=new Date().toISOString(),u=o.map(e=>{let t=this.s.wsConnections.get(e.requestId),r={requestId:e.requestId,url:t?.url??null,timestamp:e.timestamp,direction:e.direction,opcode:e.opcode,payloadLength:e.payloadLength,payloadPreview:e.payloadPreview,isBinary:e.isBinary,connectionStatus:t?.status??null,handshakeStatus:t?.handshakeStatus??null};return n&&(r.payload=e.payload??e.payloadSample),r}),d={schema:`jshookmcp.streaming.ws.capture.v1`,exportedAt:c,format:t,filters:{direction:i,payloadFilter:a??null,includePayload:n},monitor:{enabled:this.s.wsConfig.enabled,maxFrames:this.s.wsConfig.maxFrames,urlFilter:this.s.wsConfig.urlFilterRaw??null,connectionCount:this.s.wsConnections.size},recordCount:u.length},p=t===`ndjson`?[JSON.stringify({type:`metadata`,...d}),...u.map(e=>JSON.stringify({type:`frame`,...e}))].join(`
2
+ `)+`
3
+ `:`${JSON.stringify({...d,frames:u},null,2)}\n`,m=await r({category:`captures`,toolName:`ws-capture`,target:i,ext:t});return await l(m.absolutePath,p,`utf8`),f({success:!0,artifactPath:m.displayPath,format:t,bytes:Buffer.byteLength(p,`utf8`),recordCount:u.length,filters:d.filters,monitor:d.monitor})}async handleWsSendFrame(e){let t=p(e.url),n=e.payload;if(!t)return f({success:!1,error:`url is required`});if(typeof n!=`string`)return f({success:!1,error:`payload is required`});let r=g(e.binary,!1);return f(await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookWsInstances;if(!t)return{success:!1,message:`WebSocket instance exposure is not enabled. Call ws_monitor with exposeInstances=true first.`};let n=t[e.url];if(!n||n.length===0)return{success:!1,message:`No reachable WebSocket instance for this url. Only sockets created AFTER exposeInstances=true was enabled are reachable.`};let r=n.filter(e=>{try{return e.readyState===1}catch{return!1}});if(r.length===0)return{success:!1,message:`Found ${n.length} instance(s) for this url but none in OPEN state (readyState=1).`,readyStates:n.map(e=>{try{return e.readyState}catch{return-1}})};let i=r[r.length-1],a;if(e.binary){let t=Uint8Array.from(atob(e.payload),e=>e.charCodeAt(0));i.send(t),a=t.length}else i.send(e.payload),a=e.payload.length;return{success:!0,url:e.url,readyState:i.readyState,bytesSent:a,binary:e.binary}},{url:t,payload:n,binary:r}))}};const T=e=>e===`ndjson`?`ndjson`:`json`;function E(e){let t=window;t.__jshookSSEMonitor||={enabled:!0,patched:!1,maxEvents:e.maxEvents,urlFilterRaw:e.urlFilterRaw,events:[],sources:{}};let n=t.__jshookSSEMonitor;n.enabled=!0,n.maxEvents=e.maxEvents,n.urlFilterRaw=e.urlFilterRaw,n.events.length>n.maxEvents&&(n.events=n.events.slice(-n.maxEvents));let r=e=>{if(!n.urlFilterRaw)return!0;try{return new RegExp(n.urlFilterRaw).test(e)}catch{return!0}},i=e=>{if(typeof e==`string`)return e;if(e==null)return``;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return`[unserializable]`}return String(e)},a=(e,t,a,o)=>{if(!n.enabled||!r(e))return;let s=i(a),c={sourceUrl:e,eventType:t,dataPreview:s.length>200?`${s.slice(0,200)}…`:s,data:s,dataLength:s.length,lastEventId:o,timestamp:Date.now()};for(n.events.push(c);n.events.length>n.maxEvents;)n.events.shift();let l=n.sources[e]??{url:e,status:`connecting`,eventCount:0};l.eventCount+=1,l.lastEventTimestamp=c.timestamp,n.sources[e]=l};if(t.EventSource===void 0)return{success:!1,error:`EventSource is not available in current page context`};if(!n.patched){let e=t.EventSource,i=function(t,i){let o=String(t),s=new e(t,i);if(r(o)){let e=n.sources[o]??{url:o,status:`connecting`,eventCount:0};n.sources[o]=e}s.addEventListener(`open`,()=>{let e=n.sources[o];e&&(e.status=`open`),a(o,`open`,``,null)}),s.addEventListener(`error`,()=>{let e=n.sources[o];e&&(e.status=`error`),a(o,`error`,``,null)}),s.addEventListener(`message`,e=>{let t=typeof e.lastEventId==`string`&&e.lastEventId.length>0?e.lastEventId:null;a(o,e.type||`message`,e.data,t)});let c=s.addEventListener.bind(s),l=(e,t,n)=>{c(e,t,n)};return Object.defineProperty(s,"addEventListener",{value:(e,t,n)=>{if(e!==`message`&&e!==`open`&&e!==`error`&&t){l(e,n=>{let r=n,i=typeof r.lastEventId==`string`&&r.lastEventId.length>0?r.lastEventId:null;a(o,e,r.data,i),typeof t==`function`?t.call(s,n):t.handleEvent(n)},n);return}l(e,t,n)},configurable:!0,writable:!0}),s};i.prototype=e.prototype;try{Object.defineProperty(i,"CONNECTING",{value:e.CONNECTING}),Object.defineProperty(i,"OPEN",{value:e.OPEN}),Object.defineProperty(i,"CLOSED",{value:e.CLOSED})}catch{}t.EventSource=i,n.originalEventSource=e,n.patched=!0}return{success:!0,message:`SSE monitor enabled`,patched:n.patched,urlFilter:n.urlFilterRaw,maxEvents:n.maxEvents,existingEvents:n.events.length}}var D=class{s;constructor(e){this.s=e}async enableSseInterceptor(e,t,n){let r=await this.s.collector.getActivePage();return n?.persistent?(await o(r,E,{maxEvents:e,urlFilterRaw:t}),{success:!0,message:`SSE monitor enabled (persistent — survives navigations)`,patched:!0,urlFilter:t,maxEvents:e,existingEvents:0}):await a(r,E,{maxEvents:e,urlFilterRaw:t})}async handleSseMonitorEnable(e){let t=m(e.maxEvents,{defaultValue:2e3,min:1,max:5e4,integer:!0}),n=p(e.urlFilter);if(n){let e=_(n);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`})}let r=e.persistent===!0,i=await this.enableSseInterceptor(t,n,{persistent:r});return i.success?(this.s.sseConfig={maxEvents:t,urlFilterRaw:n},f({success:!0,message:i.message,patched:i.patched,config:{maxEvents:this.s.sseConfig.maxEvents,urlFilter:this.s.sseConfig.urlFilterRaw??null},existingEvents:i.existingEvents})):f(i)}async handleSseGetEvents(e){let t=p(e.sourceUrl),n=p(e.eventType),r=g(e.fullData,!1),i=m(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),o=m(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0});return f(await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookSSEMonitor;if(!t)return{success:!1,message:`SSE monitor is not enabled. Call sse_monitor_enable first.`};let n=t.events;e.sourceUrl&&(n=n.filter(t=>t.sourceUrl===e.sourceUrl)),e.eventType&&(n=n.filter(t=>t.eventType===e.eventType));let r=n.length,i=n.slice(e.offset,e.offset+e.limit).map(t=>{if(e.fullData)return t;let{data:n,...r}=t;return r});return{success:!0,filters:{sourceUrl:e.sourceUrl??null,eventType:e.eventType??null,fullData:e.fullData},page:{offset:e.offset,limit:e.limit,returned:i.length,totalAfterFilter:r,hasMore:e.offset+i.length<r,nextOffset:e.offset+i.length<r?e.offset+i.length:null},monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,sourceCount:Object.keys(t.sources).length},events:i}},{sourceUrl:t,eventType:n,limit:i,offset:o,fullData:r}))}async handleSseExportCapture(e){let t=p(e.sourceUrl),n=p(e.eventType),i=g(e.includeData,!0),o=T(e.format),s=await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookSSEMonitor;if(!t)return{success:!1,message:`SSE monitor is not enabled. Call sse_monitor_enable first.`};let n=t.events;return e.sourceUrl&&(n=n.filter(t=>t.sourceUrl===e.sourceUrl)),e.eventType&&(n=n.filter(t=>t.eventType===e.eventType)),{success:!0,monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,sourceCount:Object.keys(t.sources).length},filters:{sourceUrl:e.sourceUrl??null,eventType:e.eventType??null,includeData:e.includeData},events:n.map(t=>{if(e.includeData)return t;let{data:n,...r}=t;return r})}},{sourceUrl:t,eventType:n,includeData:i});if(!s.success)return f(s);let c=s.events??[],u={schema:`jshookmcp.streaming.sse.capture.v1`,exportedAt:new Date().toISOString(),format:o,filters:s.filters??{sourceUrl:t??null,eventType:n??null},monitor:s.monitor??null,recordCount:c.length},d=o===`ndjson`?[JSON.stringify({type:`metadata`,...u}),...c.map(e=>JSON.stringify({type:`event`,...e}))].join(`
4
+ `)+`
5
+ `:`${JSON.stringify({...u,events:c},null,2)}\n`,m=await r({category:`captures`,toolName:`sse-capture`,target:n??t??`all`,ext:o});return await l(m.absolutePath,d,`utf8`),f({success:!0,artifactPath:m.displayPath,format:o,bytes:Buffer.byteLength(d,`utf8`),recordCount:c.length,filters:u.filters,monitor:u.monitor})}};const O=e=>e===`ndjson`?`ndjson`:`json`,k=e=>typeof e==`object`&&e?e:void 0,A=(e,t)=>{let n=k(e)?.[t];return typeof n==`string`?n:void 0},j=(e,t)=>{let n=k(e)?.[t];return typeof n==`number`?n:void 0},M=(e,t)=>{let n=k(e)?.[t];return k(n)};function N(e){let t=k(e);if(!t)return null;for(let e of Object.keys(t))if(e.toLowerCase()===`content-type`){let n=t[e];return typeof n==`string`?n:null}return null}var P=class{s;pending=new Map;constructor(e){this.s=e}async teardownGrpcSession(){if(this.s.grpcSession&&this.s.grpcListeners){let t=this.s.grpcListeners;try{this.s.grpcSession.off(`Network.requestWillBeSent`,t.requestWillBeSent)}catch(t){e.debug(`[grpc-teardown] failed to remove requestWillBeSent`,t)}try{this.s.grpcSession.off(`Network.responseReceived`,t.responseReceived)}catch(t){e.debug(`[grpc-teardown] failed to remove responseReceived`,t)}try{this.s.grpcSession.off(`Network.loadingFinished`,t.loadingFinished)}catch(t){e.debug(`[grpc-teardown] failed to remove loadingFinished`,t)}}if(this.s.grpcSession)try{await this.s.grpcSession.detach()}catch(t){e.debug(`[grpc-teardown] failed to detach CDP session`,t)}this.s.grpcSession=null,this.s.grpcListeners=null,this.pending.clear()}enforceGrpcCallLimit(){for(;this.s.grpcCallOrder.length>this.s.grpcConfig.maxCalls;){let e=this.s.grpcCallOrder.shift();if(!e)break;this.s.grpcCalls.delete(e)}}async fetchAndParse(e,t,n){try{let r=await e.send(`Network.getResponseBody`,{requestId:t}),i=typeof r?.body==`string`?r.body:``,a=r?.base64Encoded===!0;if(i){let e=c(i,a?`base64`:`hex`);n.responseMessages=e.frames,n.responseBodyBytes=e.totalBytes,e.warnings.length>0&&n.warnings.push(...e.warnings)}}catch(e){n.bodyError=e instanceof Error?e.message:String(e)}try{let r=await e.send(`Network.getRequestPostData`,{requestId:t}),i=typeof r?.postData==`string`?r.postData:``;if(i){let e=c(i,`base64`);n.requestMessages=e.frames,n.requestBodyBytes=e.totalBytes,e.warnings.length>0&&n.warnings.push(...e.warnings)}}catch{}}async handleGrpcMonitorEnable(e){let t=m(e.maxCalls,{defaultValue:100,min:1,max:5e3,integer:!0}),n=p(e.urlFilter),r;if(n){let e=_(n);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`});r=e.regex}await this.teardownGrpcSession(),this.s.grpcCalls.clear(),this.s.grpcCallOrder=new i(t),this.pending.clear();let a=await(await this.s.collector.getActivePage()).createCDPSession();await a.send(`Network.enable`);let o={requestWillBeSent:e=>{let t=A(e,`requestId`);if(!t)return;let n=M(e,`request`),i=A(n,`url`)??``;r&&i&&!r.test(i)||this.pending.set(t,{url:i,method:A(n,`method`)??`UNKNOWN`,requestContentType:N(M(n,`headers`)),createdTimestamp:j(e,`timestamp`)??Date.now()/1e3})},responseReceived:e=>{let t=A(e,`requestId`);if(!t)return;let n=M(e,`response`);if(!n)return;let r=N(n.headers)??A(n,`mimeType`)??null;if(!d(r)){this.pending.delete(t);return}let i=this.pending.get(t),a=i?.url??A(n,`url`)??``;if(this.s.grpcConfig.urlFilter&&a&&!this.s.grpcConfig.urlFilter.test(a)){this.pending.delete(t);return}let o={requestId:t,url:a,method:i?.method??`UNKNOWN`,status:j(n,`status`)??0,requestContentType:i?.requestContentType??null,responseContentType:r,createdTimestamp:i?.createdTimestamp??Date.now()/1e3,finishedTimestamp:null,requestBodyBytes:0,responseBodyBytes:0,responseMessages:[],requestMessages:[],warnings:[],bodyError:null};this.s.grpcCalls.set(t,o),this.s.grpcCallOrder.push(t),this.enforceGrpcCallLimit()},loadingFinished:e=>{let t=A(e,`requestId`);if(!t)return;let n=this.s.grpcCalls.get(t);if(!n){this.pending.delete(t);return}n.finishedTimestamp=j(e,`timestamp`)??Date.now()/1e3,this.fetchAndParse(a,t,n).catch(e=>{n.bodyError=e instanceof Error?e.message:String(e)})}};return a.on(`Network.requestWillBeSent`,o.requestWillBeSent),a.on(`Network.responseReceived`,o.responseReceived),a.on(`Network.loadingFinished`,o.loadingFinished),this.s.grpcSession=a,this.s.grpcListeners=o,this.s.grpcConfig={enabled:!0,maxCalls:t,urlFilterRaw:n,urlFilter:r},f({success:!0,message:`gRPC monitor enabled`,config:{maxCalls:t,urlFilter:n??null},note:`gRPC calls are detected by content-type application/grpc(-web)?(+proto)? and parsed on loadingFinished. Feed each message payloadBase64 to protobuf_decode_raw.`})}async handleGrpcMonitorDisable(e){let t=Array.from(this.s.grpcCalls.values()),n={success:!0,message:`gRPC monitor disabled`,config:{maxCalls:this.s.grpcConfig.maxCalls,urlFilter:this.s.grpcConfig.urlFilterRaw??null},summary:{capturedCalls:t.length,callsWithParsedMessages:t.filter(e=>e.responseMessages.length>0).length,callsWithBodyError:t.filter(e=>e.bodyError!==null).length,totalResponseMessages:t.reduce((e,t)=>e+t.responseMessages.length,0)}};return await this.teardownGrpcSession(),this.s.grpcConfig={...this.s.grpcConfig,enabled:!1},f(n)}async handleGrpcGetCalls(e){let t=m(e.limit,{defaultValue:50,min:1,max:1e3,integer:!0}),n=m(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0}),r=g(e.fullMessages,!1),i=p(e.urlFilter),a;if(i){let e=_(i);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`});a=e.regex}let o=Array.from(this.s.grpcCallOrder.toArray()).map(e=>this.s.grpcCalls.get(e)).filter(e=>e!==void 0).filter(e=>a?a.test(e.url):!0),s=o.slice(n,n+t).map(e=>{let t={requestId:e.requestId,url:e.url,method:e.method,status:e.status,requestContentType:e.requestContentType,responseContentType:e.responseContentType,createdTimestamp:e.createdTimestamp,finishedTimestamp:e.finishedTimestamp,responseMessageCount:e.responseMessages.length,requestMessageCount:e.requestMessages.length,responseBodyBytes:e.responseBodyBytes,requestBodyBytes:e.requestBodyBytes,compressedResponseMessages:e.responseMessages.filter(e=>e.compressed).length,hasTrailer:e.responseMessages.some(e=>e.isTrailer),bodyError:e.bodyError,warningCount:e.warnings.length};return r&&(t.responseMessages=e.responseMessages,t.requestMessages=e.requestMessages,t.warnings=e.warnings),t});return f({success:!0,monitorEnabled:this.s.grpcConfig.enabled,filters:{urlFilter:i??null,fullMessages:r},page:{offset:n,limit:t,returned:s.length,totalAfterFilter:o.length,hasMore:n+s.length<o.length,nextOffset:n+s.length<o.length?n+s.length:null},calls:s})}async handleGrpcExportCapture(e){let t=O(e.format),n=g(e.includeMessages,!0),i=p(e.urlFilter),a;if(i){let e=_(i);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`});a=e.regex}let o=Array.from(this.s.grpcCallOrder.toArray()).map(e=>this.s.grpcCalls.get(e)).filter(e=>e!==void 0).filter(e=>a?a.test(e.url):!0).map(e=>{let t={requestId:e.requestId,url:e.url,method:e.method,status:e.status,requestContentType:e.requestContentType,responseContentType:e.responseContentType,createdTimestamp:e.createdTimestamp,finishedTimestamp:e.finishedTimestamp,requestBodyBytes:e.requestBodyBytes,responseBodyBytes:e.responseBodyBytes,responseMessageCount:e.responseMessages.length,requestMessageCount:e.requestMessages.length,compressedResponseMessages:e.responseMessages.filter(e=>e.compressed).length,hasTrailer:e.responseMessages.some(e=>e.isTrailer),bodyError:e.bodyError,warningCount:e.warnings.length};return n&&(t.responseMessages=e.responseMessages,t.requestMessages=e.requestMessages,t.warnings=e.warnings),t}),s={schema:`jshookmcp.streaming.grpc.capture.v1`,exportedAt:new Date().toISOString(),format:t,filters:{urlFilter:i??null,includeMessages:n},monitor:{enabled:this.s.grpcConfig.enabled,maxCalls:this.s.grpcConfig.maxCalls,urlFilter:this.s.grpcConfig.urlFilterRaw??null,capturedCalls:this.s.grpcCalls.size},recordCount:o.length},c=t===`ndjson`?[JSON.stringify({type:`metadata`,...s}),...o.map(e=>JSON.stringify({type:`call`,...e}))].join(`
6
+ `)+`
7
+ `:`${JSON.stringify({...s,calls:o},null,2)}\n`,u=await r({category:`captures`,toolName:`grpc-capture`,target:i??`all`,ext:t});return await l(u.absolutePath,c,`utf8`),f({success:!0,artifactPath:u.displayPath,format:t,bytes:Buffer.byteLength(c,`utf8`),recordCount:o.length,filters:s.filters,monitor:s.monitor})}};const F=e=>e===`ndjson`?`ndjson`:`json`;function I(e){let t=window;t.__jshookFetchStreamMonitor||={enabled:!0,patched:!1,maxEvents:e.maxEvents,urlFilterRaw:e.urlFilterRaw,events:[],sources:{}};let n=t.__jshookFetchStreamMonitor;n.enabled=!0,n.maxEvents=e.maxEvents,n.urlFilterRaw=e.urlFilterRaw,n.events.length>n.maxEvents&&(n.events=n.events.slice(-n.maxEvents));let r=e=>{if(!n.urlFilterRaw)return!0;try{return new RegExp(n.urlFilterRaw).test(e)}catch{return!0}},i=e=>{if(typeof e==`string`)return e;if(e==null)return``;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return`[unserializable]`}return String(e)},a=(e,t,a,o)=>{if(!n.enabled||!r(e))return;let s=i(a),c={sourceUrl:e,eventType:t,dataPreview:s.length>200?`${s.slice(0,200)}…`:s,data:s,dataLength:s.length,lastEventId:o,timestamp:Date.now()};for(n.events.push(c);n.events.length>n.maxEvents;)n.events.shift();let l=n.sources[e]??{url:e,status:`open`,eventCount:0};l.eventCount+=1,l.lastEventTimestamp=c.timestamp,n.sources[e]=l},o=e=>{let t=`message`,n=``,r=null,i=!1;for(let a of e.split(/\r?\n/)){if(a===``||a.startsWith(`:`))continue;i=!0;let e=a.indexOf(`:`),o=e===-1?a:a.slice(0,e),s=e===-1?``:a.slice(e+1);s.startsWith(` `)&&(s=s.slice(1)),o===`event`?t=s:o===`data`?n=n===``?s:`${n}\n${s}`:o===`id`&&(r=s)}return i?{eventType:t,data:n,lastEventId:r}:null},s=e=>{let t=-1,n=0;for(let[r,i]of[[`
8
+
9
+ `,2],[`\r
10
+ \r
11
+ `,4],[`\r\r`,2]]){let a=e.indexOf(r);a!==-1&&(t===-1||a<t)&&(t=a,n=i)}return t===-1?null:{offset:t,after:t+n}},c=async(e,t)=>{let r=t.getReader(),i=new TextDecoder(`utf-8`),c=``;try{for(;;){let{done:t,value:n}=await r.read();if(t)break;c+=i.decode(n,{stream:!0});let l=s(c);for(;l;){let t=c.slice(0,l.offset);c=c.slice(l.after);let n=o(t);n&&a(e,n.eventType,n.data,n.lastEventId),l=s(c)}}if(c+=i.decode(),c.length>0){let t=o(c);t&&a(e,t.eventType,t.data,t.lastEventId)}let t=n.sources[e];t&&(t.status=`closed`)}catch{let t=n.sources[e];t&&(t.status=`error`)}};if(t.fetch===void 0)return{success:!1,error:`fetch is not available in current page context`};if(!n.patched){let e=t.fetch.bind(t);n.originalFetch=e,t.fetch=async(t,n)=>{let i=await e(t,n);try{let e=t instanceof Request?t.url:String(t);(i.headers?.get?.(`content-type`)??``).toLowerCase().includes(`text/event-stream`)&&e&&r(e)&&i.body&&typeof i.body.getReader==`function`&&c(e,(typeof i.clone==`function`?i.clone():i).body)}catch{}return i},n.patched=!0}return{success:!0,message:`fetch-stream monitor enabled`,patched:n.patched,urlFilter:n.urlFilterRaw,maxEvents:n.maxEvents,existingEvents:n.events.length}}var L=class{s;constructor(e){this.s=e}async enable(e,t,n){let r=await this.s.collector.getActivePage();return n?.persistent?(await o(r,I,{maxEvents:e,urlFilterRaw:t}),{success:!0,message:`fetch-stream monitor enabled (persistent — survives navigations)`,patched:!0,urlFilter:t,maxEvents:e,existingEvents:0}):await a(r,I,{maxEvents:e,urlFilterRaw:t})}async handleFetchStreamMonitorEnable(e){let t=m(e.maxEvents,{defaultValue:2e3,min:1,max:5e4,integer:!0}),n=p(e.urlFilter);if(n){let e=_(n);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`})}let r=e.persistent===!0,i=await this.enable(t,n,{persistent:r});return typeof i==`object`&&i&&i.success===!1||(this.s.fetchStreamConfig={maxEvents:t,urlFilterRaw:n}),f(i)}async handleFetchStreamMonitorDisable(e){return await a(await this.s.collector.getActivePage(),()=>{let e=window;e.__jshookFetchStreamMonitor&&(e.__jshookFetchStreamMonitor.enabled=!1)}),f({success:!0,message:`fetch-stream monitor disabled (wrapper remains installed; capture paused)`})}async handleFetchStreamGetEvents(e){let t=p(e.sourceUrl),n=p(e.eventType),r=g(e.fullData,!1),i=m(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),o=m(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0});return f(await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookFetchStreamMonitor;if(!t)return{success:!1,message:`fetch-stream monitor is not enabled. Call fetch_stream_monitor first.`};let n=t.events;e.sourceUrl&&(n=n.filter(t=>t.sourceUrl===e.sourceUrl)),e.eventType&&(n=n.filter(t=>t.eventType===e.eventType));let r=n.length,i=n.slice(e.offset,e.offset+e.limit).map(t=>{if(e.fullData)return t;let{data:n,...r}=t;return r});return{success:!0,filters:{sourceUrl:e.sourceUrl??null,eventType:e.eventType??null,fullData:e.fullData},page:{offset:e.offset,limit:e.limit,returned:i.length,totalAfterFilter:r,hasMore:e.offset+i.length<r,nextOffset:e.offset+i.length<r?e.offset+i.length:null},monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,sourceCount:Object.keys(t.sources).length},events:i}},{sourceUrl:t,eventType:n,limit:i,offset:o,fullData:r}))}async handleFetchStreamExportCapture(e){let t=p(e.sourceUrl),n=p(e.eventType),i=g(e.includeData,!0),o=F(e.format),s=await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookFetchStreamMonitor;if(!t)return{success:!1,message:`fetch-stream monitor is not enabled. Call fetch_stream_monitor first.`};let n=t.events;return e.sourceUrl&&(n=n.filter(t=>t.sourceUrl===e.sourceUrl)),e.eventType&&(n=n.filter(t=>t.eventType===e.eventType)),{success:!0,monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,sourceCount:Object.keys(t.sources).length},filters:{sourceUrl:e.sourceUrl??null,eventType:e.eventType??null,includeData:e.includeData},events:n.map(t=>{if(e.includeData)return t;let{data:n,...r}=t;return r})}},{sourceUrl:t,eventType:n,includeData:i});if(!s.success)return f(s);let c=s.events??[],u={schema:`jshookmcp.streaming.fetch-stream.capture.v1`,exportedAt:new Date().toISOString(),format:o,filters:s.filters??{sourceUrl:t??null,eventType:n??null},monitor:s.monitor??null,recordCount:c.length},d=o===`ndjson`?[JSON.stringify({type:`metadata`,...u}),...c.map(e=>JSON.stringify({type:`event`,...e}))].join(`
12
+ `)+`
13
+ `:`${JSON.stringify({...u,events:c},null,2)}\n`,m=await r({category:`captures`,toolName:`fetch-stream-capture`,target:n??t??`all`,ext:o});return await l(m.absolutePath,d,`utf8`),f({success:!0,artifactPath:m.displayPath,format:o,bytes:Buffer.byteLength(d,`utf8`),recordCount:c.length,filters:u.filters,monitor:u.monitor})}};const R=e=>e===`ndjson`?`ndjson`:`json`;function z(e){let t=window;t.__jshookWebRtcMonitor||={enabled:!0,patched:!1,maxEvents:e.maxEvents,urlFilterRaw:e.urlFilterRaw,events:[],nextPcId:1,channels:0};let n=t.__jshookWebRtcMonitor;n.enabled=!0,n.maxEvents=e.maxEvents,n.urlFilterRaw=e.urlFilterRaw,n.events.length>n.maxEvents&&(n.events=n.events.slice(-n.maxEvents));let r=e=>{if(typeof e==`string`)return e;if(e==null)return``;if(typeof e==`object`)try{return JSON.stringify(e)}catch{return`[unserializable]`}return String(e)},i=(e,t,i,a)=>{if(!n.enabled)return;let o=typeof a!=`string`&&(a instanceof ArrayBuffer||(typeof ArrayBuffer<`u`&&ArrayBuffer.isView?.(a))===!0),s=r(o?`[binary ${String(a.byteLength??0)} bytes]`:a),c=s.length>200?`${s.slice(0,200)}…`:s;for(n.events.push({pcId:e,label:t,direction:i,dataPreview:c,data:s,dataLength:o?a.byteLength:s.length,isBinary:o,timestamp:Date.now()});n.events.length>n.maxEvents;)n.events.shift()},a=(e,t,r)=>{n.channels+=1;let a=r||(typeof t.label==`string`?t.label:``),o=t.send.bind(t);t.send=function(t){return i(e,a,`sent`,t),o(t)},t.addEventListener(`message`,t=>{i(e,a,`received`,t?.data)})};if(t.RTCPeerConnection===void 0)return{success:!1,error:`RTCPeerConnection is not available in current page context`};if(!n.patched){let e=t.RTCPeerConnection,r=function(t){let r=new e(t),i=n.nextPcId;n.nextPcId+=1,r.__jshookPcId=i;let o=r.createDataChannel.bind(r);r.createDataChannel=function(e,t){let n=o(e,t);return a(i,n,e),n};let s=r.addEventListener.bind(r);return r.addEventListener=function(e,t,n){return e===`datachannel`&&t?s(e,e=>{let n=e;n?.channel&&a(i,n.channel,n.channel.label),typeof t==`function`?t.call(r,e):t.handleEvent(e)},n):s(e,t,n)},r};r.prototype=e.prototype;try{r.generateCertificate=e.generateCertificate}catch{}t.RTCPeerConnection=r,n.patched=!0}return{success:!0,message:`WebRTC monitor enabled`,patched:n.patched,urlFilter:n.urlFilterRaw,maxEvents:n.maxEvents,existingEvents:n.events.length}}var B=class{s;constructor(e){this.s=e}async enable(e,t,n){let r=await this.s.collector.getActivePage();return n?.persistent?(await o(r,z,{maxEvents:e,urlFilterRaw:t}),{success:!0,message:`WebRTC monitor enabled (persistent — survives navigations)`,patched:!0,urlFilter:t,maxEvents:e,existingEvents:0}):await a(r,z,{maxEvents:e,urlFilterRaw:t})}async handleWebRtcMonitorEnable(e){let t=m(e.maxEvents,{defaultValue:2e3,min:1,max:5e4,integer:!0}),n=p(e.urlFilter);if(n){let e=_(n);if(e.error)return f({success:!1,error:`Invalid urlFilter regex: ${e.error}`})}let r=e.persistent===!0,i=await this.enable(t,n,{persistent:r});return typeof i==`object`&&i&&i.success===!1||(this.s.webrtcConfig={maxEvents:t,urlFilterRaw:n}),f(i)}async handleWebRtcMonitorDisable(e){return await a(await this.s.collector.getActivePage(),()=>{let e=window;e.__jshookWebRtcMonitor&&(e.__jshookWebRtcMonitor.enabled=!1)}),f({success:!0,message:`WebRTC monitor disabled (wrapper remains installed; capture paused)`})}async handleWebRtcGetEvents(e){let t=p(e.label),n=p(e.direction),r=g(e.fullData,!1),i=m(e.limit,{defaultValue:100,min:1,max:5e3,integer:!0}),o=m(e.offset,{defaultValue:0,min:0,max:2**53-1,integer:!0});return f(await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookWebRtcMonitor;if(!t)return{success:!1,message:`WebRTC monitor is not enabled. Call webrtc_monitor first.`};let n=t.events;e.label&&(n=n.filter(t=>t.label===e.label)),e.direction&&(n=n.filter(t=>t.direction===e.direction));let r=n.length,i=n.slice(e.offset,e.offset+e.limit).map(t=>{if(e.fullData)return t;let{data:n,...r}=t;return r});return{success:!0,filters:{label:e.label??null,direction:e.direction??null,fullData:e.fullData},page:{offset:e.offset,limit:e.limit,returned:i.length,totalAfterFilter:r,hasMore:e.offset+i.length<r,nextOffset:e.offset+i.length<r?e.offset+i.length:null},monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,peerConnectionsSeen:t.nextPcId-1,dataChannels:t.channels},events:i}},{label:t,direction:n,limit:i,offset:o,fullData:r}))}async handleWebRtcExportCapture(e){let t=p(e.label),n=p(e.direction),i=g(e.includeData,!0),o=R(e.format),s=await a(await this.s.collector.getActivePage(),e=>{let t=window.__jshookWebRtcMonitor;if(!t)return{success:!1,message:`WebRTC monitor is not enabled. Call webrtc_monitor first.`};let n=t.events;return e.label&&(n=n.filter(t=>t.label===e.label)),e.direction&&(n=n.filter(t=>t.direction===e.direction)),{success:!0,monitor:{enabled:t.enabled,patched:t.patched,maxEvents:t.maxEvents,urlFilter:t.urlFilterRaw??null,peerConnectionsSeen:t.nextPcId-1,dataChannels:t.channels},filters:{label:e.label??null,direction:e.direction??null,includeData:e.includeData},events:n.map(t=>{if(e.includeData)return t;let{data:n,...r}=t;return r})}},{label:t,direction:n,includeData:i});if(!s.success)return f(s);let c=s.events??[],u={schema:`jshookmcp.streaming.webrtc.capture.v1`,exportedAt:new Date().toISOString(),format:o,filters:s.filters??{label:t??null,direction:n??null},monitor:s.monitor??null,recordCount:c.length},d=o===`ndjson`?[JSON.stringify({type:`metadata`,...u}),...c.map(e=>JSON.stringify({type:`message`,...e}))].join(`
14
+ `)+`
15
+ `:`${JSON.stringify({...u,events:c},null,2)}\n`,m=await r({category:`captures`,toolName:`webrtc-capture`,target:n??t??`all`,ext:o});return await l(m.absolutePath,d,`utf8`),f({success:!0,artifactPath:m.displayPath,format:o,bytes:Buffer.byteLength(d,`utf8`),recordCount:c.length,filters:u.filters,monitor:u.monitor})}},V=class{collector;state;ws;sse;grpc;fetchStream;webrtc;get wsConnections(){return this.state.wsConnections}get wsFrameOrder(){return this.state.wsFrameOrder}get wsConfig(){return this.state.wsConfig}get wsFramesByRequest(){return this.state.wsFramesByRequest}get sseConfig(){return this.state.sseConfig}get grpcCalls(){return this.state.grpcCalls}get grpcCallOrder(){return this.state.grpcCallOrder}constructor(e){this.collector=e,this.state=u(e),this.ws=new w(this.state),this.sse=new D(this.state),this.grpc=new P(this.state),this.fetchStream=new L(this.state),this.webrtc=new B(this.state)}async handleWsMonitorDispatchTool(e){return s(async()=>await this.handleWsMonitorDispatch(e))}async handleWsGetFramesTool(e){return s(async()=>await this.handleWsGetFrames(e))}async handleWsGetConnectionsTool(e){return s(async()=>await this.handleWsGetConnections(e))}async handleWsExportCaptureTool(e){return s(async()=>await this.handleWsExportCapture(e))}handleWsMonitorDispatch=e=>String(e.action??``)===`disable`?this.ws.handleWsMonitorDisable(e):this.ws.handleWsMonitorEnable(e);handleWsMonitorEnable=e=>this.ws.handleWsMonitorEnable(e);handleWsMonitorDisable=e=>this.ws.handleWsMonitorDisable(e);handleWsGetFrames=e=>this.ws.handleWsGetFrames(e);handleWsGetConnections=e=>this.ws.handleWsGetConnections(e);handleWsExportCapture=e=>this.ws.handleWsExportCapture(e);async handleWsSendFrameTool(e){return s(async()=>this.ws.handleWsSendFrame(e))}handleWsSendFrame=e=>this.ws.handleWsSendFrame(e);async handleSseMonitorEnableTool(e){return s(async()=>await this.handleSseMonitorEnable(e))}async handleSseGetEventsTool(e){return s(async()=>await this.handleSseGetEvents(e))}async handleSseExportCaptureTool(e){return s(async()=>await this.handleSseExportCapture(e))}handleSseMonitorEnable=e=>this.sse.handleSseMonitorEnable(e);handleSseGetEvents=e=>this.sse.handleSseGetEvents(e);handleSseExportCapture=e=>this.sse.handleSseExportCapture(e);async handleGrpcMonitorTool(e){return s(async()=>this.handleGrpcMonitorDispatch(e))}async handleGrpcGetCallsTool(e){return s(async()=>this.grpc.handleGrpcGetCalls(e))}async handleGrpcExportCaptureTool(e){return s(async()=>this.grpc.handleGrpcExportCapture(e))}handleGrpcMonitorDispatch=e=>String(e.action??``)===`disable`?this.grpc.handleGrpcMonitorDisable(e):this.grpc.handleGrpcMonitorEnable(e);handleGrpcExportCapture=e=>this.grpc.handleGrpcExportCapture(e);async handleFetchStreamMonitorTool(e){return s(async()=>String(e.action??`enable`)===`disable`?this.fetchStream.handleFetchStreamMonitorDisable(e):this.fetchStream.handleFetchStreamMonitorEnable(e))}async handleFetchStreamGetEventsTool(e){return s(async()=>this.fetchStream.handleFetchStreamGetEvents(e))}async handleFetchStreamExportCaptureTool(e){return s(async()=>this.fetchStream.handleFetchStreamExportCapture(e))}handleFetchStreamExportCapture=e=>this.fetchStream.handleFetchStreamExportCapture(e);async handleWebRtcMonitorTool(e){return s(async()=>String(e.action??`enable`)===`disable`?this.webrtc.handleWebRtcMonitorDisable(e):this.webrtc.handleWebRtcMonitorEnable(e))}async handleWebRtcGetEventsTool(e){return s(async()=>this.webrtc.handleWebRtcGetEvents(e))}async handleWebRtcExportCaptureTool(e){return s(async()=>this.webrtc.handleWebRtcExportCapture(e))}handleWebRtcExportCapture=e=>this.webrtc.handleWebRtcExportCapture(e)};export{V as StreamingToolHandlers};
@@ -0,0 +1 @@
1
+ import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{readFileSync as t}from"node:fs";import n from"node:path";import r from"koffi";let i=null;function a(){return i||=r.load(`ntdll.dll`),i}function o(e){return e>=0}let s=null;function c(){return s||=a().func(`int32 NtOpenProcess(_Out_ void **, uint32, _In_ void *, _In_ void *)`),s}function l(e,t,n=!1){let i=Buffer.alloc(16);i.writeBigUInt64LE(BigInt(e),0);let a=n?2:0,s=Buffer.alloc(48);s.writeUInt32LE(48,0),s.writeUInt32LE(a,16);let l=Buffer.alloc(8),u=c()(r.address(l),t,r.address(s),r.address(i));if(!o(u))throw Error(`NtOpenProcess failed for PID ${e}: NTSTATUS 0x${(u>>>0).toString(16).padStart(8,`0`)}`);return l.readBigUInt64LE(0)}let u=null;function d(){return u||=a().func(`int32 NtReadVirtualMemory(void *, _In_ void *, _Out_ void *, ulonglong, _Out_ ulonglong *)`),u}function f(e,t,n){let i=Buffer.alloc(n),a=Buffer.alloc(8),s=d()(e,t,r.address(i),BigInt(n),r.address(a));if(!o(s))throw Error(`NtReadVirtualMemory failed: NTSTATUS 0x${(s>>>0).toString(16).padStart(8,`0`)}`);return i.subarray(0,Number(a.readBigUInt64LE(0)))}let p=null;function m(){return p||=a().func(`int32 NtWriteVirtualMemory(void *, _In_ void *, _In_ void *, ulonglong, _Out_ ulonglong *)`),p}function h(e,t,n){let i=Buffer.alloc(8),a=m()(e,t,r.address(n),BigInt(n.length),r.address(i));if(!o(a))throw Error(`NtWriteVirtualMemory failed: NTSTATUS 0x${(a>>>0).toString(16).padStart(8,`0`)}`);return Number(i.readBigUInt64LE(0))}let g=null;function _(){return g||=a().func(`int32 NtAllocateVirtualMemory(void *, _Inout_ void **, uint32, _Inout_ ulonglong *, uint32, uint32)`),g}function v(e,t,n,i){let a=Buffer.alloc(8),s=Buffer.alloc(8);s.writeBigUInt64LE(BigInt(t),0);let c=_()(e,r.address(a),0,r.address(s),n,i);if(!o(c))throw Error(`NtAllocateVirtualMemory failed: NTSTATUS 0x${(c>>>0).toString(16).padStart(8,`0`)}`);return a.readBigUInt64LE(0)}let y=null;function b(){return y||=a().func(`int32 NtProtectVirtualMemory(void *, _Inout_ void **, _Inout_ ulonglong *, uint32, _Out_ uint32 *)`),y}function x(e,t,n,i){let a=Buffer.alloc(8);a.writeBigUInt64LE(t,0);let s=Buffer.alloc(8);s.writeBigUInt64LE(BigInt(n),0);let c=Buffer.alloc(4),l=b()(e,r.address(a),r.address(s),i,r.address(c));if(!o(l))throw Error(`NtProtectVirtualMemory failed: NTSTATUS 0x${(l>>>0).toString(16).padStart(8,`0`)}`);return{oldProtect:c.readUInt32LE(0)}}let S=null;function C(){return S||=a().func(`int32 NtFreeVirtualMemory(void *, _Inout_ void **, _Inout_ ulonglong *, uint32)`),S}function w(e,t,n,i){let a=Buffer.alloc(8);a.writeBigUInt64LE(t,0);let s=Buffer.alloc(8);s.writeBigUInt64LE(BigInt(n),0);let c=C()(e,r.address(a),r.address(s),i);if(!o(c))throw Error(`NtFreeVirtualMemory failed: NTSTATUS 0x${(c>>>0).toString(16).padStart(8,`0`)}`)}let T=null;function E(){return T||=r.load(`ntdll.dll`),T}let D=null;function O(){return D||=E().func(`int32 NtQuerySystemInformation(uint32, void *, uint32, uint32 *)`),D}const k={0:`STATUS_SUCCESS`,3221225476:`STATUS_INFO_LENGTH_MISMATCH`,3221225507:`STATUS_BUFFER_TOO_SMALL`,3221225477:`STATUS_ACCESS_VIOLATION`,3221225506:`STATUS_ACCESS_DENIED`,3221225485:`STATUS_INVALID_PARAMETER`,3221225495:`STATUS_NO_MEMORY`,3221225794:`STATUS_DLL_INIT_FAILED`};function A(e){let t=e>>>0;return`${`0x${t.toString(16).padStart(8,`0`)}`} (${k[t]??`UNKNOWN`})`}function j(e){let t=e.readUInt32LE(0),n=[];for(let r=0;r<t;r++){let t=8+r*296;if(t+296>e.length)break;let i=e.readBigUInt64LE(t+16),a=e.readUInt32LE(t+24),o=e.readUInt16LE(t+38),s=t+40,c=e.subarray(s,s+256),l=c.indexOf(0),u=(l>=0?c.subarray(0,l):c).toString(`ascii`),d=``;if(o>0&&o<256){let e=c.subarray(o),t=e.indexOf(0);d=(t>=0?e.subarray(0,t):e).toString(`ascii`)}n.push({imageBase:i,imageSize:a,fullPath:u,shortName:d})}return n}function M(){if(process.platform!==`win32`)throw Error(`NtQuerySystemInformation module enumeration is Windows-only`);let e=O(),t=Buffer.alloc(16),n=Buffer.alloc(4),i=e(11,r.address(t),t.length,r.address(n));if(i>>>0!=3221225476&&i>>>0)throw Error(`NtQuerySystemInformation probe failed: ${A(i)}`);let a=n.readUInt32LE(0);if(a===0)return[];let o=Buffer.alloc(a);if(n.writeUInt32LE(0,0),i=e(11,r.address(o),o.length,r.address(n)),i>>>0)throw Error(`NtQuerySystemInformation query failed: ${A(i)}`);return j(o)}function N(e){let t=e.toLowerCase();return M().find(e=>e.shortName.toLowerCase().includes(t))??null}function P(){try{let e=N(`ntoskrnl`);return e?`0x${e.imageBase.toString(16).toUpperCase()}`:void 0}catch{return}}function F(){if(process.platform!==`win32`)throw Error(`SyscallResolver: ntdll resolution is only supported on Windows`);let e=process.env.SystemRoot||process.env.WINDIR||`C:\\Windows`;return n.join(e,`System32`,`ntdll.dll`)}const I=Buffer.from([15,5,195]),L=[76,139,209];let R=null;function z(e){if(R)return R;let n=e??F(),r=[],i;try{i=t(n)}catch(e){throw Error(`SyscallResolver: cannot read ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}let a=i.readUInt32LE(60);if(i.readUInt32LE(a)!==17744)throw Error(`SyscallResolver: invalid PE signature`);if(i.readUInt16LE(a+4)!==34404)throw Error(`SyscallResolver: ntdll is not x64`);let o=i.readUInt16LE(a+6),s=i.readUInt16LE(a+20),c=a+24+s,l=i.readUInt32LE(a+24+112+0),u=i.readUInt32LE(a+24+112+4);function d(e){for(let t=0;t<o;t++){let n=c+t*40;if(n+40>i.length)break;let r=i.readUInt32LE(n+12),a=i.readUInt32LE(n+8),o=i.readUInt32LE(n+20);if(e>=r&&e<r+a)return o+(e-r)}return-1}let f=[],p={};if(l===0||u===0)throw Error(`SyscallResolver: ntdll has no export directory`);let m=d(l);if(m<0)throw Error(`SyscallResolver: cannot resolve export directory RVA`);let h=i.readUInt32LE(m+24),g=i.readUInt32LE(m+28),_=i.readUInt32LE(m+32),v=i.readUInt32LE(m+36),y=d(g),b=d(_),x=d(v);if(y<0||b<0||x<0)throw Error(`SyscallResolver: cannot resolve export table arrays`);for(let e=0;e<h;e++){let t=i.readUInt32LE(b+e*4),n=i.readUInt16LE(x+e*2),a=i.readUInt32LE(y+n*4),o=d(t);if(o<0)continue;let s=i.indexOf(0,o),c=i.subarray(o,s>o?s:o+128).toString(`ascii`);if(!c.startsWith(`Zw`))continue;let l=d(a);if(l<0||l+8>i.length){r.push(`${c}: cannot map RVA to file offset`);continue}let u=i.subarray(l,l+8);if(u[0]!==L[0]||u[1]!==L[1]||u[2]!==L[2]||u[3]!==184){r.push(`${c}: prologue does not match "mov r10, rcx; mov eax, imm" — got ${[...u.subarray(0,8)].map(e=>e.toString(16).padStart(2,`0`)).join(` `)}`);continue}let m={name:c,ssn:u.readUInt32LE(4),rva:a};f.push(m),p[c]=m,p[c.replace(/^Zw/,`Nt`)]=m}let S=0;for(let e=0;e<i.length-3;e++)if(i[e]===I[0]&&i[e+1]===I[1]&&i[e+2]===I[2]){for(let t=0;t<o;t++){let n=c+t*40,r=i.readUInt32LE(n+12),a=i.readUInt32LE(n+8),o=i.readUInt32LE(n+20);if(e>=o&&e<o+a){S=r+(e-o);break}}if(S!==0)break}if(S===0)throw Error(`SyscallResolver: no syscall;ret gadget found in ntdll .text`);let C=P();return R={path:n,syscalls:f,byName:p,syscallGadgetRva:S,warnings:r,kernelImageBase:C},R}var B=e({resolveNtdll:()=>z});export{x as a,l as i,v as n,f as o,w as r,h as s,B as t};