@jshookmcp/jshook 0.3.2 → 0.3.3

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 (241) hide show
  1. package/README.md +3 -3
  2. package/README.zh.md +3 -3
  3. package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
  4. package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
  5. package/dist/CodeInjector-Btj9upnf.mjs +1 -0
  6. package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
  7. package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
  8. package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
  9. package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
  10. package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
  11. package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
  12. package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
  13. package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
  14. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
  15. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  16. package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
  17. package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
  18. package/dist/MemoryScanner-Dxd657li.mjs +1 -0
  19. package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
  20. package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
  21. package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
  22. package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
  23. package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
  24. package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
  25. package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
  26. package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
  27. package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
  28. package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
  29. package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
  30. package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
  31. package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
  32. package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
  33. package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
  34. package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
  35. package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
  36. package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
  37. package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
  38. package/dist/antidebug-CsnpOR9z.mjs +1 -0
  39. package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
  40. package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
  41. package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
  42. package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
  43. package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
  44. package/dist/browser-BUaB25bk.mjs +11 -0
  45. package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
  46. package/dist/collector-CB2syQEg.mjs +1 -0
  47. package/dist/constants-DMv3svps.mjs +2 -0
  48. package/dist/coordination-Dbohmj6D.mjs +1 -0
  49. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  50. package/dist/debugger-CLzkObIO.mjs +1 -0
  51. package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
  52. package/dist/definitions-B3a9QC2t.mjs +1 -0
  53. package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
  54. package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
  55. package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
  56. package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
  57. package/dist/definitions-DBYSxChX.mjs +1 -0
  58. package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
  59. package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
  60. package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
  61. package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
  62. package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
  63. package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
  64. package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
  65. package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
  66. package/dist/definitions-EGmqr85H.mjs +1 -0
  67. package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
  68. package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
  69. package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
  70. package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
  71. package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
  72. package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
  73. package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
  74. package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
  75. package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
  76. package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
  77. package/dist/handlers-6iNsXOVT.mjs +7 -0
  78. package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
  79. package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
  80. package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
  81. package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
  82. package/dist/handlers-CWKBBjai.mjs +1 -0
  83. package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
  84. package/dist/handlers-CrJsKnEI.mjs +1 -0
  85. package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
  86. package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
  87. package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
  88. package/dist/handlers-gVscChvl.mjs +1 -0
  89. package/dist/handlers-xFvI9P_y.mjs +1 -0
  90. package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
  91. package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
  92. package/dist/index.mjs +11 -11
  93. package/dist/macro-p8kuJVcm.mjs +2 -0
  94. package/dist/maintenance-DAqADb6Z.mjs +302 -0
  95. package/dist/manifest-4lmM6MZR.mjs +1 -0
  96. package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
  97. package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
  98. package/dist/manifest-Box-jWfr.mjs +1 -0
  99. package/dist/manifest-Bp33di0Q.mjs +1 -0
  100. package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
  101. package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
  102. package/dist/manifest-C7TdXCWY.mjs +1 -0
  103. package/dist/manifest-CM-n64K0.mjs +1 -0
  104. package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
  105. package/dist/manifest-CWJS45iO.mjs +1 -0
  106. package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
  107. package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
  108. package/dist/manifest-Cgxu2qdv.mjs +1 -0
  109. package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
  110. package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
  111. package/dist/manifest-CvDpVToN.mjs +1 -0
  112. package/dist/manifest-D8TL9RLE.mjs +1 -0
  113. package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
  114. package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
  115. package/dist/manifest-DLGtZH-0.mjs +1 -0
  116. package/dist/manifest-DXHdPt2T.mjs +1 -0
  117. package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
  118. package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
  119. package/dist/manifest-G2H52LKz.mjs +131 -0
  120. package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
  121. package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
  122. package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
  123. package/dist/manifest-dG6MuR1U.mjs +1 -0
  124. package/dist/manifest-nWXtgq5Y2.mjs +1 -0
  125. package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
  126. package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
  127. package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
  128. package/dist/native-g095qhpK.mjs +961 -0
  129. package/dist/network-Dvxm7eEI.mjs +7 -0
  130. package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
  131. package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
  132. package/dist/platform-DjWbuiF8.mjs +93 -0
  133. package/dist/process-Dq5I-KZW.mjs +2 -0
  134. package/dist/proxy-DPNgM7TE.mjs +2 -0
  135. package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
  136. package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
  137. package/dist/search-defaults-CJik67or.mjs +1 -0
  138. package/dist/server/plugin-api.mjs +1 -1
  139. package/dist/sourcemap-DqEW15Ao.mjs +1 -0
  140. package/dist/streaming-Dbk4eStJ.mjs +1 -0
  141. package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
  142. package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
  143. package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
  144. package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
  145. package/package.json +2 -2
  146. package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
  147. package/dist/DOMInspector-C19J4zeq.mjs +0 -95
  148. package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
  149. package/dist/ExtensionManager-BD724zkO.mjs +0 -1
  150. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
  151. package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
  152. package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
  153. package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
  154. package/dist/PageController-Dfsm1_o7.mjs +0 -1
  155. package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
  156. package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
  157. package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
  158. package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
  159. package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
  160. package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
  161. package/dist/VersionDetector-CHT36Az0.mjs +0 -9
  162. package/dist/apk-packer-BqXcInnX.mjs +0 -1
  163. package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
  164. package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
  165. package/dist/browser-Qqco2rOT.mjs +0 -11
  166. package/dist/collector-Bpl6qy2L.mjs +0 -1
  167. package/dist/constants-BYj8Xek8.mjs +0 -1
  168. package/dist/coordination-CWXW1o8K.mjs +0 -1
  169. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  170. package/dist/debugger-DyALjYMk.mjs +0 -1
  171. package/dist/definitions-BftdXgXI.mjs +0 -1
  172. package/dist/definitions-Bio5XJYy.mjs +0 -1
  173. package/dist/definitions-CMZRSy3k.mjs +0 -1
  174. package/dist/definitions-DP1vgxEY.mjs +0 -1
  175. package/dist/definitions-Tls8c0A0.mjs +0 -1
  176. package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
  177. package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
  178. package/dist/handlers-8zN_vBIz.mjs +0 -1
  179. package/dist/handlers-DHO3rjsW.mjs +0 -1
  180. package/dist/handlers-FJ80VzUI.mjs +0 -2
  181. package/dist/handlers-VHWrxbM_.mjs +0 -1
  182. package/dist/handlers-mPFiNPe8.mjs +0 -302
  183. package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
  184. package/dist/maintenance-BUpIukhg.mjs +0 -1
  185. package/dist/manifest-B7NB2rh2.mjs +0 -1
  186. package/dist/manifest-BDi4nbH1.mjs +0 -1
  187. package/dist/manifest-BLDfkE7n.mjs +0 -1
  188. package/dist/manifest-BcXbB4gf.mjs +0 -1
  189. package/dist/manifest-Bdnc_vrc.mjs +0 -1
  190. package/dist/manifest-BuYKgCnp.mjs +0 -1
  191. package/dist/manifest-CBfNnGPV.mjs +0 -1
  192. package/dist/manifest-CPS1Xv69.mjs +0 -1
  193. package/dist/manifest-CRryuZF4.mjs +0 -1
  194. package/dist/manifest-CvTe5ZGV2.mjs +0 -1
  195. package/dist/manifest-D-5GH0DV.mjs +0 -1
  196. package/dist/manifest-D3Ssf3IC.mjs +0 -1
  197. package/dist/manifest-D5ck3NvC.mjs +0 -1
  198. package/dist/manifest-DG19q-Ld.mjs +0 -1
  199. package/dist/manifest-DLMlD0Zc.mjs +0 -1
  200. package/dist/manifest-DwL2ik8P.mjs +0 -1
  201. package/dist/manifest-ItF5P8A12.mjs +0 -1
  202. package/dist/manifest-KZphqIyX.mjs +0 -1
  203. package/dist/manifest-RcpX_MyZ.mjs +0 -123
  204. package/dist/manifest-Zy7Odg5J.mjs +0 -1
  205. package/dist/manifest-ff1H7Pdp.mjs +0 -1
  206. package/dist/manifest-iuhF6pTL2.mjs +0 -1
  207. package/dist/manifest-yC16OhL2.mjs +0 -1
  208. package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
  209. package/dist/native-j8l473zn.mjs +0 -961
  210. package/dist/network-T0VRwNPd.mjs +0 -7
  211. package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
  212. package/dist/platform-CzaQtISh.mjs +0 -93
  213. package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
  214. package/dist/process-CWhsCWrf.mjs +0 -2
  215. package/dist/proxy-DZFlDsG3.mjs +0 -2
  216. package/dist/search-defaults-lYBVn_3L.mjs +0 -1
  217. package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
  218. package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
  219. package/dist/streaming-BcJ0B6ao.mjs +0 -1
  220. package/dist/types-D9EiE5o9.mjs +0 -1
  221. /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  222. /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  223. /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  224. /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  225. /package/dist/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
  226. /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.mjs} +0 -0
  227. /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
  228. /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  229. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  230. /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  231. /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  232. /package/dist/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
  233. /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
  234. /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  235. /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  236. /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  237. /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
  238. /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
  239. /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  240. /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  241. /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -1,7 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{At as t,Ot as n,f as r,fn as i,kt as a,pn as o}from"./constants-BYj8Xek8.mjs";import{t as s}from"./DetailedDataManager-DmQ1LT-W.mjs";import{r as c}from"./modules-BPBcSaM-.mjs";import{n as l,t as u}from"./parse-args-Bw413PlW.mjs";import{n as d,t as f}from"./ResponseBuilder-BfWP-uaT.mjs";import{a as p,c as m,i as h,l as g,n as _,o as v,r as y,s as b,t as x}from"./ssrf-policy-CsIJGkpd.mjs";import"./definitions-l7TjdE6V.mjs";import*as S from"node:http";import{createHash as C}from"node:crypto";import{promises as w}from"node:fs";import T from"koffi";import*as E from"node:net";import*as D from"node:dns/promises";import*as O from"node:tls";import*as ee from"node:http2";import*as te from"node:https";const ne=new Set([`Image`,`Font`,`Stylesheet`,`Media`,`Manifest`,`Ping`]),re={XHR:0,Fetch:1,Document:2,Script:3,WebSocket:4,EventSource:5},k=e=>typeof e==`object`&&!!e,ie=e=>k(e)?typeof e.url==`string`&&typeof e.method==`string`:!1,ae=e=>k(e)?typeof e.status==`number`:!1,oe=e=>typeof e==`number`&&Number.isFinite(e),A=e=>typeof e==`string`?e:void 0,se=e=>typeof e==`boolean`?e:void 0,j=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,ce=e=>{if(Array.isArray(e))return e.every(e=>typeof e==`string`)?e:void 0},le=e=>!(!k(e)||e.hitCount!==void 0&&typeof e.hitCount!=`number`||e.callFrame!==void 0&&!k(e.callFrame)||k(e.callFrame)&&(e.callFrame.functionName!==void 0&&typeof e.callFrame.functionName!=`string`||e.callFrame.url!==void 0&&typeof e.callFrame.url!=`string`||e.callFrame.lineNumber!==void 0&&typeof e.callFrame.lineNumber!=`number`)),ue=e=>!k(e)||!Array.isArray(e.nodes)||typeof e.startTime!=`number`||typeof e.endTime!=`number`||!e.nodes.every(e=>le(e))?null:{nodes:e.nodes,samples:Array.isArray(e.samples)?e.samples:void 0,startTime:e.startTime,endTime:e.endTime};function de(){return s.getInstance()}function M(e,t,n){e?.emit(t,n)}function N(e,t){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1?!0:e===0?!1:t;if(typeof e==`string`){let t=e.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(t))return!0;if([`false`,`0`,`no`,`off`].includes(t))return!1}return t}function P(e,t){let n;if(typeof e==`number`&&Number.isFinite(e))n=e;else if(typeof e==`string`){let t=e.trim();if(t.length>0){let e=Number(t);Number.isFinite(e)&&(n=e)}}return n===void 0&&(n=t.defaultValue),t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n}function fe(e,t,n){if(!k(t))return null;let r=A(t.url),i=A(t.method);if(!r||!i)return null;let a=j(t.timestamp),o=A(t.requestId)??`${e.toLowerCase()}-injected-${a??0}-${n}`;return{...t,requestId:o,url:r,method:i,type:A(t.type)??e,timestamp:a,injected:!0,captureSource:`inpage`}}function pe(e){let t=(e.type??``).toString().toLowerCase();return t.includes(`xhr`)?`xhr`:t.includes(`fetch`)?`fetch`:t||`unknown`}function me(e){return`${e.targetId??``}|${e.sessionId??``}|${e.method.toUpperCase()}|${e.url}|${pe(e)}`}function he(e){return`${e.targetId??``}|${e.sessionId??``}|${e.method.toUpperCase()}|${e.url}`}function ge(e,t){let n=j(e.timestamp),r=j(t.timestamp);return n===void 0||r===void 0?!1:Math.abs(n-r)<=1500}function _e(e,t){let n=pe(e),r=pe(t);return n===r||n===`unknown`||r===`unknown`}function ve(e,t,n,r,i){if(!e)return null;for(let a=0;a<e.length;a+=1){let o=e[a];if(o===void 0||n.has(o))continue;let s=t[o];if(!(!s||!ge(s,r))&&!(i&&!_e(s,r)))return e.splice(a,1),o}return null}async function ye(e){let t=e.getNetworkRequests().filter(e=>ie(e)).map(e=>({...e,captureSource:`cdp`})),[n,r]=await Promise.all([typeof e.getXHRRequests==`function`?e.getXHRRequests().catch(()=>[]):Promise.resolve([]),typeof e.getFetchRequests==`function`?e.getFetchRequests().catch(()=>[]):Promise.resolve([])]),i=n.map((e,t)=>fe(`XHR`,e,t)).filter(e=>e!==null),a=r.map((e,t)=>fe(`Fetch`,e,t)).filter(e=>e!==null),o=[...i,...a],s=new Set,c=new Map,l=new Map;t.forEach((e,t)=>{let n=me(e),r=he(e);c.set(n,[...c.get(n)??[],t]),l.set(r,[...l.get(r)??[],t])});for(let e of o){let n=e.requestId?t.findIndex((t,n)=>!s.has(n)&&t.requestId===e.requestId):-1,r=me(e),i=he(e),a=n>=0?n:ve(c.get(r),t,s,e,!1)??ve(l.get(i),t,s,e,!0);if(a===null||a===-1){t.push(e);continue}s.add(a);let o=t[a];t[a]={...e,...o,injected:!!(o.injected||e.injected),captureSource:e.captureSource??o.captureSource}}return t}const be=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,xe=/\/[0-9a-f]{16,}(?=[/?#]|$)/gi,Se=/\/\d{2,}(?=[/?#]|$)/g;function Ce(e){try{let t=new URL(e),n=t.pathname;return n=n.replace(be,`{id}`),n=n.replace(xe,`/{id}`),n=n.replace(Se,`/{id}`),`${t.origin}${n}`}catch{return e}}var we=class{deps;detailedDataManager=de();constructor(e){this.deps=e}async handleNetworkMonitor(e){let t=String(e.action??``);switch(t){case`enable`:return this.handleNetworkEnable(e);case`disable`:return this.handleNetworkDisable(e);case`status`:return this.handleNetworkGetStatus(e);default:return f.fail(`Invalid generic action parameter: ${t}. Expected enable, disable, status.`).json()}}async handleNetworkEnable(e){return d(async()=>{let t=N(e.enableExceptions,!0);await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:t});let n=this.deps.consoleMonitor.getNetworkStatus();return{message:` Network monitoring enabled successfully`,enabled:n.enabled,cdpSessionActive:n.cdpSessionActive,listenerCount:n.listenerCount,usage:{step1:`Network monitoring is now active`,step2:`Navigate to a page using page_navigate tool`,step3:`Use network_get_requests to retrieve captured requests`,step4:`Use network_get_response_body to get response content`},important:`Network monitoring must be enabled BEFORE navigating to capture requests`}})}async handleNetworkDisable(e){return d(async()=>(await this.deps.consoleMonitor.disable(),{message:`Network monitoring disabled`}))}async handleNetworkGetStatus(e){try{let e=this.deps.consoleMonitor.getNetworkStatus();return e.enabled?f.ok().merge({enabled:!0,message:` Network monitoring is active. Captured ${e.requestCount} requests and ${e.responseCount} responses.`,requestCount:e.requestCount,responseCount:e.responseCount,listenerCount:e.listenerCount,cdpSessionActive:e.cdpSessionActive,nextSteps:e.requestCount===0?{hint:`No requests captured yet`,action:`Navigate to a page using page_navigate to capture network traffic`}:{hint:`${e.requestCount} requests captured`,action:`Use network_get_requests to retrieve them`}}).json():f.fail(` Network monitoring is NOT enabled`).merge({enabled:!1,nextSteps:{step1:`Call network_enable tool to start monitoring`,step2:`Then navigate to a page using page_navigate`,step3:`Finally use network_get_requests to see captured requests`},example:`network_enable -> page_navigate -> network_get_requests`}).json()}catch(e){return f.fail(e).json()}}async getMergedNetworkRequests(){return await ye(this.deps.consoleMonitor)}async handleNetworkGetRequests(e){try{let t=N(e.autoEnable,!0),n=N(e.enableExceptions,!0),r=await this.ensureNetworkEnabled({autoEnable:t,enableExceptions:n});if(!r.enabled)return this.buildNotEnabledResponse(t,r.error);let i=A(e.url),a=A(e.urlRegex),o=A(e.method),s=oe(e.sinceTimestamp)?e.sinceTimestamp:void 0,c=A(e.sinceRequestId),l=oe(e.tail)&&e.tail>0?Math.floor(e.tail):void 0,u=N(e.deduplicateUrls,!1),d=e.fields,p=Array.isArray(d)&&d.length>0?d.filter(e=>typeof e==`string`):void 0,m=P(e.limit,{defaultValue:100,min:1,max:1e3,integer:!0}),h=P(e.offset,{defaultValue:0,min:0,integer:!0}),g=await this.getMergedNetworkRequests();if(g.length===0)return this.buildEmptyRequestsResponse(r.autoEnabled);let _=this.applyRequestFilters(g,{url:i,urlRegex:a,method:o,sinceTimestamp:s,sinceRequestId:c,tail:l,limit:m,offset:h,autoEnabled:r.autoEnabled,fields:p,deduplicateUrls:u}),v=this.detailedDataManager.smartHandle(_.finalPayload,25600);return f.ok().merge(v).json()}catch(e){return f.fail(e).json()}}async handleNetworkGetResponseBody(e){try{let t=A(e.requestId)||``,n=P(e.maxSize,{defaultValue:1e5,min:1024,max:20*1024*1024,integer:!0}),r=N(e.returnSummary,!1),i=P(e.retries,{defaultValue:3,min:0,max:10,integer:!0}),a=P(e.retryIntervalMs,{defaultValue:500,min:50,max:5e3,integer:!0}),o=N(e.autoEnable,!1),s=N(e.enableExceptions,!0);if(!t)return f.fail(`requestId parameter is required`).set(`hint`,`Get requestId from network_get_requests tool`).json();let c=await this.ensureNetworkEnabled({autoEnable:o,enableExceptions:s});if(!c.enabled)return f.fail(`Network monitoring is not enabled`).merge({hint:o?`Auto-enable failed. Check active page and call network_enable manually.`:`Use network_enable tool first, or set autoEnable=true`,detail:c.error}).json();let l=null,u=0;for(let e=0;e<=i&&(u=e+1,l=await this.deps.consoleMonitor.getResponseBody(t),!l);e+=1)e<i&&await new Promise(e=>setTimeout(e,a));return l?this.buildResponseBodyResult(t,l,u,n,r):f.fail(`No response body found for requestId: ${t}`).merge({hint:`The request may not have completed yet, or the requestId is invalid`,attempts:u,waitedMs:i*a,retryConfig:{retries:i,retryIntervalMs:a}}).json()}catch(e){return f.fail(e).json()}}async handleNetworkGetStats(e){return d(async()=>{if(!this.deps.consoleMonitor.isNetworkEnabled())throw Error(`Network monitoring is not enabled. Use network_enable tool first`);let e=this.deps.consoleMonitor.getNetworkRequests().filter(e=>ie(e)),t=this.deps.consoleMonitor.getNetworkResponses().filter(ae),n={};e.forEach(e=>{n[e.method]=(n[e.method]||0)+1});let r={};t.forEach(e=>{r[e.status]=(r[e.status]||0)+1});let i={};e.forEach(e=>{let t=e.type||`unknown`;i[t]=(i[t]||0)+1});let a=e.map(e=>e.timestamp).filter(e=>oe(e)),o=a.length>0?{earliest:Math.min(...a),latest:Math.max(...a),duration:Math.max(...a)-Math.min(...a)}:null;return{stats:{totalRequests:e.length,totalResponses:t.length,byMethod:n,byStatus:r,byType:i,timeStats:o,monitoringEnabled:!0}}})}async ensureNetworkEnabled(e){if(this.deps.consoleMonitor.isNetworkEnabled())return{enabled:!0,autoEnabled:!1};if(!e.autoEnable)return{enabled:!1,autoEnabled:!1};try{return await this.deps.consoleMonitor.enable({enableNetwork:!0,enableExceptions:e.enableExceptions}),{enabled:this.deps.consoleMonitor.isNetworkEnabled(),autoEnabled:!0}}catch(e){return{enabled:!1,autoEnabled:!1,error:e instanceof Error?e.message:String(e)}}}buildNotEnabledResponse(e,t){return e&&t?f.fail(`Failed to auto-enable network monitoring`).merge({detail:t,solution:{step1:`Ensure browser page is active and reachable`,step2:`Call network_enable manually`,step3:`Navigate to target page: page_navigate(url)`,step4:`Get requests: network_get_requests`}}).json():f.fail(` Network monitoring is not enabled`).merge({requests:[],total:0,solution:{step1:`Enable network monitoring: network_enable`,step2:`Navigate to target page: page_navigate(url)`,step3:`Get requests: network_get_requests`},tip:`Set autoEnable=true to auto-enable monitoring in this call`}).json()}buildEmptyRequestsResponse(e){return f.ok().merge({message:`No network requests captured yet`,requests:[],total:0,hint:`Network monitoring is enabled, but no requests have been captured`,possibleReasons:[`1. You haven't navigated to any page yet (use page_navigate)`,`2. The page has already loaded before network monitoring was enabled`,`3. The page doesn't make any network requests`,`4. The page uses frontend-wrapped fetch/XHR not captured by CDP`],recommended_actions:[`console_inject_fetch_interceptor() — capture frontend-wrapped fetch calls (SPAs, React, Vue)`,`console_inject_xhr_interceptor() — capture XMLHttpRequest calls`,`page_navigate(url, enableNetworkMonitoring=true) — re-navigate with monitoring enabled`],nextAction:`Call console_inject_fetch_interceptor(), then re-navigate or trigger the target action`,monitoring:{autoEnabled:e}}).json()}applyRequestFilters(e,t){let{url:n,urlRegex:r,method:i,sinceTimestamp:a,sinceRequestId:o,tail:s,limit:c,offset:l,autoEnabled:u,fields:d,deduplicateUrls:f}=t,p=e.length,m=e.map(e=>e.url),h=!!(n||r||i&&i.toUpperCase()!==`ALL`||a||o||s),g=0;if(!h){let t=e.length;e=e.filter(e=>!e.type||!ne.has(e.type)),g=t-e.length}if(o){let t=e.findIndex(e=>e.requestId===o);t>=0&&(e=e.slice(t+1))}if(a!==void 0&&(e=e.filter(e=>(e.timestamp??0)>a)),r){if(r.length>500)throw Error(`urlRegex too long (max 500 characters)`);let t=new RegExp(r,`i`);if(e.length>0){let n=performance.now();t.test(e[0].url);let r=performance.now()-n;if(r>100)throw Error(`urlRegex pattern is too expensive (${r.toFixed(0)}ms on first URL). Use a simpler pattern.`)}e=e.filter(e=>t.test(e.url))}else if(n){let t=n.toLowerCase();e=e.filter(e=>e.url.toLowerCase().includes(t))}i&&i.toUpperCase()!==`ALL`&&(e=e.filter(e=>e.method.toUpperCase()===i.toUpperCase())),s!==void 0&&e.length>s&&(e=e.slice(-s)),e.sort((e,t)=>(re[e.type??``]??6)-(re[t.type??``]??6));let _=e.length;e=e.slice(l,l+c);let v=l+e.length<_,y=_===0&&p>0&&!!(n||i&&i.toUpperCase()!==`ALL`),b=y?m.slice(0,10).map(e=>e.substring(0,120)):void 0;if(f){let t=new Map;for(let n of e){let e=Ce(n.url),r=`${n.method.toUpperCase()} ${e}`,i=t.get(r);i?i.count++:t.set(r,{pattern:e,method:n.method.toUpperCase(),count:1,example:n.url})}let n=[...t.values()].toSorted((e,t)=>t.count-e.count);return{finalPayload:{message:` Deduplicated ${e.length} requests into ${n.length} unique endpoint(s)`,endpoints:n,totalRequests:e.length,uniqueEndpoints:n.length,stats:{totalCaptured:p,afterFilter:_},filtered:h,monitoring:{autoEnabled:u}}}}let x=d?e.map(e=>{let t={};for(let n of d)n in e&&(t[n]=e[n]);return t}):e;return{finalPayload:{message:` Retrieved ${e.length} network request(s)`,requests:x,total:e.length,page:{offset:l,limit:c,returned:e.length,totalAfterFilter:_,hasMore:v,nextOffset:v?l+e.length:null},stats:{totalCaptured:p,afterFilter:_,returned:e.length,truncated:_>l+c},filtered:h,filters:{url:n,urlRegex:r,method:i,sinceTimestamp:a,sinceRequestId:o,tail:s,limit:c,offset:l},monitoring:{autoEnabled:u},...y&&{filterMiss:!0,hint:`URL filter "${n}" matched 0 of ${p} captured requests. Check urlSamples to verify the correct filter substring.`,urlSamples:b},tip:e.length>0?`Use network_get_response_body(requestId) to get response content`:void 0,...g>0&&{staticResourcesExcluded:g,staticFilterNote:`${g} static resources (Image/Font/Stylesheet/Media) excluded by default. Set any filter to include all types.`},...p>100&&!h&&{optimizationHint:`${p} requests captured. Use url/method filters to reduce payload size.`}}}}buildResponseBodyResult(e,t,n,r,i){let a=t.body.length,o=a>r;if(i||o){let i=t.body.substring(0,500);return f.ok().merge({requestId:e,attempts:n,summary:{size:a,sizeKB:(a/1024).toFixed(2),base64Encoded:t.base64Encoded,preview:i+(a>500?`...`:``),truncated:o,reason:o?`Response too large (${(a/1024).toFixed(2)} KB > ${(r/1024).toFixed(2)} KB)`:`Summary mode enabled`},tip:o?`Use collect_code tool to collect and compress this script, or increase maxSize parameter`:`Set returnSummary=false to get full body`}).json()}return f.ok().merge({requestId:e,attempts:n,body:t.body,base64Encoded:t.base64Encoded,size:a,sizeKB:(a/1024).toFixed(2)}).json()}},Te=class{deps;constructor(e){this.deps=e}async handlePerformanceGetMetrics(e){return d(async()=>{let t=e.includeTimeline===!0,n=this.deps.getPerformanceMonitor(),r={metrics:await n.getPerformanceMetrics()};return t&&(r.timeline=await n.getPerformanceTimeline()),r})}async handlePerformanceCoverage(e){return l(e,`action`,new Set([`start`,`stop`]))===`stop`?this.handlePerformanceStopCoverage(e):this.handlePerformanceStartCoverage(e)}async handlePerformanceStartCoverage(e){return d(async()=>(await this.deps.getPerformanceMonitor().startCoverage(),{message:`Code coverage collection started`}))}async handlePerformanceStopCoverage(e){return d(async()=>{let e=await this.deps.getPerformanceMonitor().stopCoverage(),t=e.length>0?e.reduce((e,t)=>e+t.coveragePercentage,0)/e.length:0;return{coverage:e,totalScripts:e.length,avgCoverage:t}})}async handlePerformanceTakeHeapSnapshot(e){try{let e=this.deps.getTraceRecorder?.()??null;if(e?.getState()===`recording`)try{let t=await e.captureActiveHeapSnapshot();return f.ok().merge({snapshotSize:t,persistedToTrace:!0,message:`Heap snapshot taken and persisted to the active trace recording (data too large to return)`}).json()}catch(e){let t=await this.deps.getPerformanceMonitor().takeHeapSnapshot();return f.ok().merge({snapshotSize:t,persistedToTrace:!1,tracePersistenceError:e instanceof Error?e.message:String(e),message:`Heap snapshot taken, but the active trace recording could not persist it (data too large to return)`}).json()}let t=await this.deps.getPerformanceMonitor().takeHeapSnapshot();return f.ok().merge({snapshotSize:t,persistedToTrace:!1,message:`Heap snapshot taken (data too large to return, saved internally)`}).json()}catch(e){return f.fail(e).json()}}async handlePerformanceTraceStart(e){return d(async()=>{let t=this.deps.getPerformanceMonitor(),n=ce(e.categories),r=se(e.screenshots);return await t.startTracing({categories:n,screenshots:r}),{message:`Performance tracing started. Call performance_trace with action="stop" to save the trace.`}})}async handlePerformanceTraceStop(e){return d(async()=>{let t=this.deps.getPerformanceMonitor(),n=A(e.artifactPath),r=await t.stopTracing({artifactPath:n});return{artifactPath:r.artifactPath,eventCount:r.eventCount,sizeBytes:r.sizeBytes,sizeKB:(r.sizeBytes/1024).toFixed(1),hint:`Open the trace file in Chrome DevTools -> Performance tab -> Load profile`}})}async handleProfilerCpuStart(e){return d(async()=>(await this.deps.getPerformanceMonitor().startCPUProfiling(),{message:`CPU profiling started. Call profiler_cpu with action="stop" to save the profile.`}))}async handleProfilerCpuStop(e){return d(async()=>{let t=await this.deps.getPerformanceMonitor().stopCPUProfiling(),n=ue(t)||t,{writeFile:r}=await import(`node:fs/promises`),{resolveArtifactPath:i}=await import(`./artifacts-CkodUM4j.mjs`).then(e=>e.t),a=A(e.artifactPath),o=JSON.stringify(n,null,2),s;if(a)await r(a,o,`utf-8`),s=a;else{let{absolutePath:e,displayPath:t}=await i({category:`profiles`,toolName:`cpu-profile`,ext:`cpuprofile`});await r(e,o,`utf-8`),s=t}let c=n.nodes.filter(e=>(e.hitCount||0)>0).toSorted((e,t)=>(t.hitCount||0)-(e.hitCount||0)).slice(0,20).map(e=>({functionName:e.callFrame?.functionName||`(anonymous)`,url:e.callFrame?.url,line:e.callFrame?.lineNumber,hitCount:e.hitCount}));return{artifactPath:s,totalNodes:n.nodes.length,totalSamples:n.samples?.length||0,durationMs:n.endTime-n.startTime,hotFunctions:c,hint:`Open the .cpuprofile file in Chrome DevTools -> Performance tab`}})}async handleProfilerHeapSamplingStart(e){return d(async()=>{let t=this.deps.getPerformanceMonitor(),n=j(e.samplingInterval);return await t.startHeapSampling({samplingInterval:n}),{message:`Heap sampling started. Call profiler_heap_sampling with action="stop" to save the report.`}})}async handleProfilerHeapSamplingStop(e){return d(async()=>{let t=this.deps.getPerformanceMonitor(),n=A(e.artifactPath),r=j(e.topN),i=await t.stopHeapSampling({artifactPath:n,topN:r});return{artifactPath:i.artifactPath,sampleCount:i.sampleCount,topAllocations:i.topAllocations}})}},Ee=class{deps;constructor(e){this.deps=e}async handleConsoleGetExceptions(e){return d(async()=>{let t=A(e.url),n=P(e.limit,{defaultValue:50,min:1,max:1e3,integer:!0}),r=this.deps.consoleMonitor.getExceptions();return t&&(r=r.filter(e=>e.url?.includes(t))),r=r.slice(0,n),{exceptions:r,total:r.length}})}async handleConsoleInjectScriptMonitor(e){return d(async()=>{let t=u(e,`persistent`,!1);return await this.deps.consoleMonitor.enableDynamicScriptMonitoring({persistent:t}),{message:t?`Dynamic script monitoring enabled (persistent — survives navigations)`:`Dynamic script monitoring enabled`}})}async handleConsoleInjectXhrInterceptor(e){return d(async()=>{let t=u(e,`persistent`,!1);return await this.deps.consoleMonitor.injectXHRInterceptor({persistent:t}),{message:t?`XHR interceptor injected (persistent)`:`XHR interceptor injected`}})}async handleConsoleInjectFetchInterceptor(e){return d(async()=>{let t=u(e,`persistent`,!1);return await this.deps.consoleMonitor.injectFetchInterceptor({persistent:t}),{message:t?`Fetch interceptor injected (persistent)`:`Fetch interceptor injected`}})}async handleConsoleClearInjectedBuffers(e){return d(async()=>({message:`Injected buffers cleared`,...await this.deps.consoleMonitor.clearInjectedBuffers()}))}async handleConsoleResetInjectedInterceptors(e){return d(async()=>({message:`Injected interceptors/monitors reset`,...await this.deps.consoleMonitor.resetInjectedInterceptors()}))}async handleConsoleInjectFunctionTracer(e){return d(async()=>{let t=A(e.functionName)||``;if(!t)throw Error(`functionName is required`);let n=u(e,`persistent`,!1);return await this.deps.consoleMonitor.injectFunctionTracer(t,{persistent:n}),{message:n?`Function tracer injected for: ${t} (persistent — survives navigations)`:`Function tracer injected for: ${t}`}})}};const De=[`authorization`,`cookie`,`x-token`,`x-auth-token`,`x-access-token`,`x-api-key`,`x-signature`,`x-sign`,`x-csrf-token`],Oe=/^(token|access_token|refresh_token|sign|signature|auth|jwt|api_key|apikey|key|secret)$/i,ke=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ae=/^Bearer\s+\S+/i;function je(e){let t=e.trim();return t.length<=12?`***`:`${t.slice(0,6)}***${t.slice(-4)}`}function F(e){let t=e.trim();return Ae.test(t)?.95:ke.test(t)?.9:t.length>20&&/^[A-Za-z0-9+/=_-]+$/.test(t)?.7:t.length>10?.5:.3}function Me(e){let t=[],n=new Set;for(let r of e){let e=r.headers??{};for(let[i,a]of Object.entries(e)){let e=i.toLowerCase();if(!De.includes(e)||!a||a.length<4)continue;if(e===`cookie`){for(let e of a.split(`;`)){let i=e.indexOf(`=`);if(i===-1)continue;let a=e.slice(0,i).trim(),o=e.slice(i+1).trim();if(!o||o.length<8)continue;let s=`cookie:${a}:${o.slice(0,8)}`;n.has(s)||(n.add(s),t.push({header:`cookie[${a}]`,value_masked:je(o),request_url:r.url,confidence:F(o),source:`cookie`}))}continue}let o=`header:${e}:${a.slice(0,8)}`;n.has(o)||(n.add(o),t.push({header:i,value_masked:je(a),request_url:r.url,confidence:F(a),source:`header`}))}try{let e=new URL(r.url);for(let[i,a]of e.searchParams.entries()){if(!Oe.test(i)||!a||a.length<8)continue;let e=`query:${i}:${a.slice(0,8)}`;n.has(e)||(n.add(e),t.push({header:i,value_masked:je(a),request_url:r.url,confidence:F(a)*.9,source:`query`}))}}catch{}if(r.postData)try{let e=JSON.parse(r.postData);if(e&&typeof e==`object`)for(let[i,a]of Object.entries(e)){if(!Oe.test(i)||typeof a!=`string`||a.length<8)continue;let e=`body:${i}:${a.slice(0,8)}`;n.has(e)||(n.add(e),t.push({header:i,value_masked:je(a),request_url:r.url,confidence:F(a)*.85,source:`body`}))}}catch{}}return t.toSorted((e,t)=>t.confidence-e.confidence)}function Ne(e={}){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function Pe(e){return e.split(`;`).map(e=>{let t=e.indexOf(`=`);return t===-1?{name:e.trim(),value:``}:{name:e.slice(0,t).trim(),value:e.slice(t+1).trim()}})}function Fe(e){try{let t=new URL(e);return Array.from(t.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{return[]}}async function Ie(e){let{requests:t,getResponse:n,getResponseBody:r,includeBodies:a,creatorVersion:o=`unknown`}=e,s=[],c=new Map;if(a){let e=i;for(let n=0;n<t.length;n+=e){let i=t.slice(n,n+e),a=await Promise.allSettled(i.map(async e=>{try{let t=await r(e.requestId);return t?{requestId:e.requestId,text:t.body}:{requestId:e.requestId,_bodyUnavailable:!0}}catch{return{requestId:e.requestId,_bodyUnavailable:!0}}}));for(let e of a)if(e.status===`fulfilled`){let t=e.value;c.set(t.requestId,`_bodyUnavailable`in t?{_bodyUnavailable:!0}:{text:t.text})}}}for(let e of t){let t=n(e.requestId),r=e.timestamp?new Date(e.timestamp*1e3).toISOString():new Date().toISOString(),i=a?c.get(e.requestId)??{_bodyUnavailable:!0}:{},o=e.postData?{mimeType:e.headers?.[`content-type`]??`application/octet-stream`,text:e.postData}:void 0,l=e.headers?.cookie??``,u=t?.headers?.[`set-cookie`]??``,d={startedDateTime:r,time:t?.timing?.receiveHeadersEnd??0,request:{method:e.method,url:e.url,httpVersion:`HTTP/1.1`,headers:Ne(e.headers),queryString:Fe(e.url),cookies:l?Pe(l):[],headersSize:-1,bodySize:e.postData?e.postData.length:0,...o?{postData:o}:{}},response:{status:t?.status??0,statusText:t?.statusText??``,httpVersion:`HTTP/1.1`,headers:Ne(t?.headers),cookies:u?Pe(u):[],content:{size:i.text?i.text.length:-1,mimeType:t?.mimeType??`application/octet-stream`,...i},redirectURL:t?.headers?.location??``,headersSize:-1,bodySize:i.text?i.text.length:-1},cache:{},timings:{send:0,wait:t?.timing?.receiveHeadersEnd??0,receive:0},_requestId:e.requestId};s.push(d)}return{log:{version:`1.2`,creator:{name:`jshookmcp`,version:o},entries:s}}}const Le=new Set([`host`,`content-length`,`transfer-encoding`,`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailers`,`upgrade`]),Re=new Set([`__proto__`,`constructor`,`prototype`]);function ze(e){let t=[];for(let n of e.cookies)n.name&&t.push(`${n.name}=${n.value}`);return t.length>0?t.join(`; `):void 0}function Be(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))!Le.has(n.toLowerCase())&&!Re.has(n)&&(t[n]=r);return t}async function Ve(e,t,n=512e3){let r=t.urlOverride??e.url,i=(t.methodOverride??e.method).toUpperCase(),a=Be({...e.headers,...t.headerPatch}),s=t.sessionProfile?ze(t.sessionProfile):void 0;s&&(a.Cookie=s),t.sessionProfile?.userAgent&&!a[`User-Agent`]&&!a[`user-agent`]&&(a[`User-Agent`]=t.sessionProfile.userAgent),t.sessionProfile?.acceptLanguage&&!a[`Accept-Language`]&&!a[`accept-language`]&&(a[`Accept-Language`]=t.sessionProfile.acceptLanguage),t.sessionProfile?.referer&&!a.Referer&&!a.referer&&(a.Referer=t.sessionProfile.referer);let c=t.bodyPatch===void 0?e.postData:t.bodyPatch,l=x(t.authorization),u=!l&&h();if(l&&(l.allowPrivateNetwork||l.allowInsecureHttp)&&!_(l))throw Error(`Replay authorization must include at least one allowed host or CIDR when enabling private network or insecure HTTP access.`);if(v(l))throw Error(`Replay authorization expired before the request was executed.`);let d=e=>u?!0:l?.allowPrivateNetwork===!0&&y(l,e),f=e=>e.parsedUrl.protocol!==`http:`||u||p(e.hostname)?!0:l?.allowInsecureHttp===!0&&y(l,e),S=async e=>{let t;try{t=await g(e)}catch{throw Error(`Replay blocked: DNS resolution failed for "${e}"`)}if(!f(t))throw Error(`Replay blocked: insecure HTTP is only allowed for loopback or explicitly authorized targets, got "${e}"`);let n=b(t.hostname),r=b(t.resolvedAddress??``);if((n||r)&&!d(t))throw!n&&r&&t.resolvedAddress?Error(`Replay blocked: "${e}" resolved to private IP ${t.resolvedAddress}`):Error(`Replay blocked: target URL "${e}" resolves to a private/reserved address.`);if(t.parsedUrl.protocol===`https:`||t.isIpLiteral)return{pinnedUrl:e,originalHost:t.parsedUrl.host,target:t};let i=t.parsedUrl.host;return t.parsedUrl.hostname=t.resolvedAddress&&t.resolvedAddress.includes(`:`)?`[${t.resolvedAddress}]`:t.resolvedAddress??t.hostname,{pinnedUrl:t.parsedUrl.toString(),originalHost:i,target:t}};if(t.dryRun!==!1){if(await m(r,t.authorization))throw Error(`Replay blocked: target URL "${r}" resolves to a private/reserved address.`);let e=await g(r).catch(()=>null);if(e&&!f(e))throw Error(`Replay blocked: insecure HTTP is only allowed for loopback or explicitly authorized targets, got "${r}"`);return{dryRun:!0,preview:{url:r,method:i,headers:a,body:c}}}let C=new AbortController,w=setTimeout(()=>C.abort(),t.timeoutMs??3e4),T=o;try{let e=r,o=i,s=c,l;for(let t=0;t<T;t++){let{pinnedUrl:t,originalHost:n,target:r}=await S(e),i={...a};if(r.parsedUrl.protocol===`http:`&&r.resolvedAddress&&!r.isIpLiteral&&(i.Host=n),l=await fetch(t,{method:o,headers:i,body:o!==`GET`&&o!==`HEAD`?s:void 0,signal:C.signal,redirect:`manual`}),l.status>=300&&l.status<400){let t=l.headers.get(`location`);if(!t)break;e=new URL(t,e).toString(),(l.status===301||l.status===302||l.status===303)&&(o=`GET`,s=void 0),delete a.Host,delete a.host;continue}break}if(l.status>=300&&l.status<400)throw Error(`Replay blocked: too many redirects (>${T})`);let u={};l.headers.forEach((e,t)=>{u[t]=e});let d=await l.text(),f=d.length>n,p=f?d.slice(0,n):d;return{dryRun:!1,status:l.status,statusText:l.statusText,headers:u,body:p,bodyTruncated:f,requestId:t.requestId}}finally{clearTimeout(w)}}const He=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.requestId==`string`&&typeof t.url==`string`&&typeof t.method==`string`},Ue=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`${t} must be an array of strings`);return e.map(e=>e.trim()).filter(e=>e.length>0)},We=(e,t)=>{if(e===void 0)return;if(typeof e!=`string`)throw Error(`${t} must be a string`);let n=e.trim();return n.length>0?n:void 0},Ge=(e,t)=>{if(e!==void 0){if(typeof e!=`boolean`)throw Error(`${t} must be a boolean`);return e}},Ke=(e,t)=>{if(typeof e!=`string`||e.trim().length===0)throw Error(`authorizationCapability must be a non-empty base64url string`);let n;try{n=JSON.parse(Buffer.from(e,`base64url`).toString(`utf8`))}catch{throw Error(`authorizationCapability must be valid base64url-encoded JSON`)}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`authorizationCapability payload must be an object`);let r=n;if(r.version!==void 0&&r.version!==1)throw Error(`authorizationCapability version ${String(r.version)} is not supported`);if(r.requestId!==t)throw Error(`authorizationCapability requestId does not match the replay requestId`);return r},qe=(e,t)=>{let n=e.authorization,r=e.authorizationCapability;if(n!==void 0&&r!==void 0)throw Error(`Provide either authorization or authorizationCapability, not both`);let i;if(n!==void 0){if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`authorization must be an object`);i=n}else if(r!==void 0)i=Ke(r,t);else return;let a=Ue(i.allowedHosts,`authorization.allowedHosts`),o=Ue(i.allowedCidrs,`authorization.allowedCidrs`),s=Ge(i.allowPrivateNetwork,`authorization.allowPrivateNetwork`),c=Ge(i.allowInsecureHttp,`authorization.allowInsecureHttp`),l=We(i.expiresAt,`authorization.expiresAt`),u=We(i.reason,`authorization.reason`),d={};return a.length>0&&(d.allowedHosts=a),o.length>0&&(d.allowedCidrs=o),s!==void 0&&(d.allowPrivateNetwork=s),c!==void 0&&(d.allowInsecureHttp=c),l!==void 0&&(d.expiresAt=l),u!==void 0&&(d.reason=u),d};var Je=class{deps;detailedDataManager=de();constructor(e){this.deps=e}async handleNetworkExtractAuth(e){return d(async()=>{let t=P(e.minConfidence,{defaultValue:.4}),n=this.deps.consoleMonitor.getNetworkRequests();if(n.length===0)throw Error(`No captured requests found. Call network_enable then page_navigate first.`);let r=Me(n).filter(e=>e.confidence>=t);return{scannedRequests:n.length,found:r.length,findings:r,note:`Values are masked (first 6 + last 4 chars). Use network_replay_request to test with actual values.`}})}async handleNetworkExportHar(e){try{let t=e.outputPath,n=N(e.includeBodies,!1),r;if(t){let e=await import(`node:path`),n=await import(`node:fs/promises`),i=e.resolve(t),a=await n.realpath(process.cwd()),o=await n.realpath((await import(`node:os`)).tmpdir()),s=e.dirname(i),c;try{c=await n.realpath(s)}catch{c=s}let l=e.join(c,e.basename(i)),u=l===a||l.startsWith(a+e.sep),d=l===o||l.startsWith(o+e.sep);if(!u&&!d)return f.fail(`outputPath must be within the current working directory or system temp dir.`).json();r=l}let i=this.deps.consoleMonitor.getNetworkRequests();if(i.length===0)return f.fail(`No captured requests to export. Call network_enable then page_navigate first.`).json();let a=await Ie({requests:i,getResponse:e=>this.deps.consoleMonitor.getNetworkActivity(e)?.response,getResponseBody:async e=>{try{return await this.deps.consoleMonitor.getResponseBody(e)}catch{return null}},includeBodies:n,creatorVersion:`1.0.0`});if(r){try{if((await w.lstat(r)).isSymbolicLink())return f.fail(`outputPath must not be a symbolic link.`).json()}catch{}return await w.writeFile(r,JSON.stringify(a,null,2),`utf-8`),f.ok().merge({message:`HAR exported to ${r}`,entryCount:a.log.entries.length,outputPath:r}).json()}let o=this.detailedDataManager.smartHandle({entryCount:a.log.entries.length,har:a},51200);return f.ok().merge(o).json()}catch(e){return f.fail(e).json()}}async handleNetworkReplayRequest(e){let t=e.requestId;if(!t)return f.fail(`requestId is required`).json();try{let n=this.deps.consoleMonitor.getNetworkRequests().find(e=>He(e)&&e.requestId===t);return n?d(async()=>{let r=qe(e,t);return await Ve(n,{requestId:t,headerPatch:e.headerPatch,sessionProfile:e.sessionProfile,bodyPatch:e.bodyPatch,methodOverride:e.methodOverride,urlOverride:e.urlOverride,timeoutMs:e.timeoutMs,dryRun:e.dryRun!==!1,authorization:r})}):f.fail(`Request ${t} not found in captured requests`).set(`hint`,`Use network_get_requests to see available request IDs`).json()}catch(e){return f.fail(e).json()}}};const Ye=e=>typeof e==`object`&&!!e;var Xe=class{deps;constructor(e){this.deps=e}async handleNetworkInterceptResponse(e){try{let t=this.parseInterceptRules(e);if(t.length===0)return f.fail(`No valid rules provided. Provide either "urlPattern" (single) or "rules" array (batch).`).merge({usage:{single:{urlPattern:`*api/status*`,responseCode:200,responseBody:`{"status":"active"}`},batch:{rules:[{urlPattern:`*api/status*`,responseBody:`{"status":"active"}`}]}}}).json();let n=await this.deps.consoleMonitor.enableFetchIntercept(t),r=this.deps.consoleMonitor.getFetchInterceptStatus();return M(this.deps.eventBus,`network:intercept_started`,{interceptType:`fetch`,timestamp:new Date().toISOString()}),f.ok().merge({message:`Added ${n.length} interception rule(s)`,createdRules:n.map(e=>({id:e.id,urlPattern:e.urlPattern,interceptAction:e.interceptAction,stage:e.stage,responseCode:e.responseCode})),totalActiveRules:r.rules.length,hint:`Use network_intercept(action: "list") to see all rules and hit counts. Use network_intercept(action: "disable") to remove rules.`}).json()}catch(e){return f.fail(e instanceof Error?e.message:String(e)).merge({hint:`Ensure browser is launched and a page is active before enabling interception.`}).json()}}async handleNetworkInterceptList(e){let t=this.deps.consoleMonitor.getFetchInterceptStatus();return f.ok().merge(t).merge({hint:t.rules.length>0?`Use network_intercept(action: "disable", ruleId) to remove a specific rule, or network_intercept(action: "disable", all: true) to remove all.`:`No active interception rules. Use network_intercept(action: "add") to add rules.`}).json()}async handleNetworkInterceptDisable(e){let t=typeof e.ruleId==`string`?e.ruleId:void 0,n=e.all===!0;return!t&&!n?f.fail(`Provide either "ruleId" to remove a specific rule, or "all": true to disable all.`).json():d(async()=>{if(n){let e=await this.deps.consoleMonitor.disableFetchIntercept();return{message:`Disabled all interception. Removed ${e.removedRules} rule(s).`,removedRules:e.removedRules}}let e=await this.deps.consoleMonitor.removeFetchInterceptRule(t),r=this.deps.consoleMonitor.getFetchInterceptStatus();return{success:e,message:e?`Rule ${t} removed.`:`Rule ${t} not found.`,remainingRules:r.rules.length}})}parseInterceptRules(e){let t=[];if(Array.isArray(e.rules))for(let n of e.rules)Ye(n)&&typeof n.urlPattern==`string`&&t.push(this.toInterceptRule(n));else typeof e.urlPattern==`string`&&t.push(this.toInterceptRule(e));return t}toInterceptRule(e){return{urlPattern:e.urlPattern,urlPatternType:e.urlPatternType===`regex`?`regex`:`glob`,stage:e.stage===`Request`?`Request`:`Response`,interceptAction:this.toInterceptAction(e.interceptAction),responseCode:typeof e.responseCode==`number`?e.responseCode:200,responseHeaders:Ye(e.responseHeaders)?e.responseHeaders:void 0,responseBody:typeof e.responseBody==`string`?e.responseBody:typeof e.responseBody==`object`?JSON.stringify(e.responseBody):void 0}}toInterceptAction(e){return e===`continue`||e===`abort`?e:`fulfill`}},Ze=class{chunks=[];totalLength=0;get length(){return this.totalLength}append(e){e.length!==0&&(this.chunks.push(e),this.totalLength+=e.length)}toBuffer(){if(this.chunks.length===0)return Buffer.alloc(0);if(this.chunks.length===1)return this.chunks[0];let e=Buffer.concat(this.chunks,this.totalLength);return this.chunks=[e],e}reset(){this.chunks=[],this.totalLength=0}get isEmpty(){return this.totalLength===0}};const Qe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$e=/^(?:text\/|application\/(?:json|ld\+json|xml|xhtml\+xml|javascript|x-javascript|problem\+json|problem\+xml|graphql-response\+json|x-www-form-urlencoded)|image\/svg\+xml)/i;function et(e,t){if(e.includes(`\r`)||e.includes(`
2
- `))throw Error(`${t} must not contain CR or LF characters`)}function I(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}function tt(e,t){return e.find(e=>e.name.toLowerCase()===t.toLowerCase())?.value??null}function nt(e,t){return t?.toUpperCase()===`HEAD`||e>=100&&e<200||e===204||e===304}function rt(e){let t=e.indexOf(`\r
3
- \r
4
- `);if(t>=0)return t+4;let n=e.indexOf(`
5
-
6
- `);return n>=0?n+2:null}function it(e,t){let n=e.indexOf(10,t);return n<0?null:{lineEnd:n>t&&e[n-1]===13?n-1:n,nextOffset:n+1}}function at(e){let t=[],n=0;for(;n<e.length;){let r=it(e,n);if(!r)return{complete:!1,consumedBytes:n,body:Buffer.concat(t)};let i=e.subarray(n,r.lineEnd).toString(`latin1`).trim().split(`;`,1)[0]?.trim()??``,a=Number.parseInt(i,16);if(!Number.isFinite(a)||a<0)return{complete:!1,consumedBytes:n,body:Buffer.concat(t)};if(a===0){let i=e.subarray(r.nextOffset),a=rt(i);return a===null?i.length>=2&&i[0]===13&&i[1]===10?{complete:!0,consumedBytes:r.nextOffset+2,body:Buffer.concat(t)}:i.length>=1&&i[0]===10?{complete:!0,consumedBytes:r.nextOffset+1,body:Buffer.concat(t)}:{complete:!1,consumedBytes:n,body:Buffer.concat(t)}:{complete:!0,consumedBytes:r.nextOffset+a,body:Buffer.concat(t)}}let o=r.nextOffset,s=o+a;if(s>e.length)return{complete:!1,consumedBytes:n,body:Buffer.concat(t)};t.push(e.subarray(o,s));let c=it(e,s);if(!c||c.lineEnd!==s)return{complete:!1,consumedBytes:n,body:Buffer.concat(t)};n=c.nextOffset}return{complete:!1,consumedBytes:n,body:Buffer.concat(t)}}function ot(e){let t=Object.entries(e);return t.length===0?``:`${t.map(([e,t])=>`${e}: ${t}`).join(`\r
7
- `)}\r\n`}function st(e){let t=e.method.trim().toUpperCase(),n=e.target.trim(),r=e.httpVersion??`1.1`;if(!Qe.test(t))throw Error(`method must be a valid HTTP token`);if(n.length===0)throw Error(`target is required`);if(et(n,`target`),r!==`1.0`&&r!==`1.1`)throw Error(`httpVersion must be either "1.0" or "1.1"`);let i={};for(let[t,n]of Object.entries(e.headers??{})){if(!Qe.test(t))throw Error(`Invalid HTTP header name: ${t}`);if(typeof n!=`string`)throw Error(`HTTP header "${t}" must be a string`);et(n,`headers.${t}`),i[t]=n}e.addHostHeader!==!1&&e.host&&!I(i,`Host`)&&(et(e.host,`host`),i.Host=e.host);let a=e.body??``;e.body!==void 0&&e.addContentLength!==!1&&!I(i,`Content-Length`)&&(I(i,`Transfer-Encoding`)||(i[`Content-Length`]=String(Buffer.byteLength(a,`utf8`)))),e.addConnectionClose!==!1&&!I(i,`Connection`)&&(i.Connection=`close`);let o=`${t} ${n} HTTP/${r}`,s=`${o}\r\n${ot(i)}\r\n${a}`,c=Buffer.from(s,`utf8`);return{requestText:s,requestHex:c.toString(`hex`),requestBytes:c.length,startLine:o,headers:i,bodyBytes:Buffer.byteLength(a,`utf8`),httpVersion:r}}function ct(e,t){let n=rt(e);if(n===null)return null;let r=e.subarray(0,n).toString(`latin1`).replace(/\r?\n\r?\n$/,``).split(/\r?\n/).filter(e=>e.length>0);if(r.length===0)throw Error(`HTTP response did not contain a status line`);let i=r[0],a=/^HTTP\/(\d+\.\d+)\s+(\d{3})(?:\s+(.*))?$/.exec(i);if(!a)throw Error(`Invalid HTTP status line: ${i}`);let o=[],s={};for(let e of r.slice(1)){let t=e.indexOf(`:`);if(t<=0)continue;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();o.push({name:n,value:r}),n in s?(n.toLowerCase(),s[n]=`${s[n]}, ${r}`):s[n]=r}let c=Number.parseInt(a[2],10),l=e.subarray(n);if(nt(c,t))return{statusLine:i,httpVersion:a[1],statusCode:c,statusText:a[3]??``,headers:s,rawHeaders:o,headerBytes:n,bodyBytes:0,bodyBuffer:Buffer.alloc(0),bodyMode:`none`,complete:!0,expectedRawBytes:n,chunkedDecoded:!1};if(tt(o,`transfer-encoding`)?.toLowerCase().includes(`chunked`)){let e=at(l);return{statusLine:i,httpVersion:a[1],statusCode:c,statusText:a[3]??``,headers:s,rawHeaders:o,headerBytes:n,bodyBytes:e.body.length,bodyBuffer:e.complete?e.body:l,bodyMode:`chunked`,complete:e.complete,expectedRawBytes:e.complete?n+e.consumedBytes:null,chunkedDecoded:e.complete}}let u=tt(o,`content-length`);if(u!==null){let e=Number.parseInt(u,10);if(Number.isFinite(e)&&e>=0){let t=l.subarray(0,Math.min(l.length,e));return{statusLine:i,httpVersion:a[1],statusCode:c,statusText:a[3]??``,headers:s,rawHeaders:o,headerBytes:n,bodyBytes:t.length,bodyBuffer:t,bodyMode:`content-length`,complete:l.length>=e,expectedRawBytes:n+e,chunkedDecoded:!1}}}return{statusLine:i,httpVersion:a[1],statusCode:c,statusText:a[3]??``,headers:s,rawHeaders:o,headerBytes:n,bodyBytes:l.length,bodyBuffer:l,bodyMode:`until-close`,complete:!1,expectedRawBytes:null,chunkedDecoded:!1}}function lt(e,t){if(t.length===0||e&&$e.test(e))return!0;let n=t.subarray(0,Math.min(t.length,64));for(let e of n)if(e===0)return!1;return!0}const L=2147483647,ut=4294967295,R={DATA:0,RST_STREAM:3,SETTINGS:4,PING:6,GOAWAY:7,WINDOW_UPDATE:8};function z(e,t,n,r){if(!Number.isInteger(e)||e<n||e>r)throw Error(`${t} must be an integer between ${String(n)} and ${String(r)}`)}function dt(e,t){let n=e.replace(/\s+/g,``).trim();if(n.length===0)return Buffer.alloc(0);if(n.length%2!=0||!/^[0-9a-fA-F]+$/.test(n))throw Error(`${t} must be an even-length hexadecimal string`);return Buffer.from(n,`hex`)}function ft(e,t){return Buffer.from(e,t)}function pt(e,t,n){if(e!==void 0&&t!==void 0)throw Error(`payloadHex and payloadText are mutually exclusive`);return e===void 0?t===void 0?Buffer.alloc(0):ft(t,n):dt(e,`payloadHex`)}function mt(e){let t=Buffer.alloc(e.length*6);return e.forEach((e,n)=>{z(e.id,`settings[${String(n)}].id`,0,65535),z(e.value,`settings[${String(n)}].value`,0,ut),t.writeUInt16BE(e.id,n*6),t.writeUInt32BE(e.value>>>0,n*6+2)}),t}function ht(e,t){z(e,t,0,L);let n=Buffer.alloc(4);return n.writeUInt32BE(e>>>0,0),n[0]&=127,n}function gt(e){let t=e.frameType,n=e.flags??0;switch(z(n,`flags`,0,255),t){case`DATA`:return{payload:pt(e.payloadHex,e.payloadText,e.payloadEncoding??`utf8`),typeCode:R.DATA,flags:n};case`SETTINGS`:if(e.ack===!0&&(e.settings?.length??0)>0)throw Error(`SETTINGS ack frames must not include settings payload`);return{payload:mt(e.settings??[]),typeCode:R.SETTINGS,flags:e.ack?n|1:n};case`PING`:{let t=e.pingOpaqueDataHex?dt(e.pingOpaqueDataHex,`pingOpaqueDataHex`):Buffer.alloc(8);if(t.length!==8)throw Error(`PING frames require exactly 8 bytes of opaque data`);return{payload:t,typeCode:R.PING,flags:e.ack?n|1:n}}case`WINDOW_UPDATE`:{let t=e.windowSizeIncrement;if(t===void 0)throw Error(`windowSizeIncrement is required for WINDOW_UPDATE frames`);return z(t,`windowSizeIncrement`,1,L),{payload:ht(t,`windowSizeIncrement`),typeCode:R.WINDOW_UPDATE,flags:n}}case`RST_STREAM`:{let t=e.errorCode??0;z(t,`errorCode`,0,ut);let r=Buffer.alloc(4);return r.writeUInt32BE(t>>>0,0),{payload:r,typeCode:R.RST_STREAM,flags:n}}case`GOAWAY`:{let t=e.lastStreamId??0,r=e.errorCode??0;z(t,`lastStreamId`,0,L),z(r,`errorCode`,0,ut);let i=e.debugDataText===void 0?Buffer.alloc(0):ft(e.debugDataText,e.debugDataEncoding??`utf8`);return{payload:Buffer.concat([ht(t,`lastStreamId`),Buffer.from([r>>>24&255,r>>>16&255,r>>>8&255,r&255]),i]),typeCode:R.GOAWAY,flags:n}}case`RAW`:{let t=e.frameTypeCode;if(t===void 0)throw Error(`frameTypeCode is required when frameType is RAW`);return z(t,`frameTypeCode`,0,255),{payload:pt(e.payloadHex,e.payloadText,e.payloadEncoding??`utf8`),typeCode:t,flags:n}}}}function _t(e,t){if((e===`SETTINGS`||e===`PING`||e===`GOAWAY`)&&t!==0)throw Error(`${e} frames must use streamId 0`);if((e===`DATA`||e===`RST_STREAM`)&&t===0)throw Error(`${e} frames must use a non-zero streamId`)}function vt(e){let t=e.streamId??0;z(t,`streamId`,0,L),_t(e.frameType,t);let{payload:n,typeCode:r,flags:i}=gt(e);if(n.length>16777215)throw Error(`payload exceeds the HTTP/2 maximum frame size of 16777215 bytes`);let a=Buffer.alloc(9);a[0]=n.length>>>16&255,a[1]=n.length>>>8&255,a[2]=n.length&255,a[3]=r&255,a[4]=i&255,a.writeUInt32BE(t>>>0,5),a[5]&=127;let o=Buffer.concat([a,n]);return{frameType:e.frameType,typeCode:r,streamId:t,flags:i,payloadBytes:n.length,payloadHex:n.toString(`hex`),frameHeaderHex:a.toString(`hex`),frameHex:o.toString(`hex`)}}const yt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function B(e,t){if(e===void 0)return;if(typeof e!=`string`)throw Error(`${t} must be a string`);let n=e.trim();return n.length>0?n:void 0}function bt(e,t,n={}){if(e!==void 0){if(typeof e!=`string`)throw Error(`${t} must be a string`);if(!(e.length===0&&!n.allowEmpty))return e}}function xt(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`${t} must be a boolean`);return e}}function V(e,t){if(e===void 0)return[];if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`${t} must be an array of strings`);return e.map(e=>e.trim()).filter(e=>e.length>0)}function St(e,t){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let n={};for(let[r,i]of Object.entries(e)){if(!yt.test(r))throw Error(`${t} contains an invalid HTTP header name: ${r}`);if(typeof i!=`string`)throw Error(`${t}.${r} must be a string`);n[r]=i}return n}function H(e,t=`authorization`){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let n=e,r=V(n.allowedHosts,`${t}.allowedHosts`),i=V(n.allowedCidrs,`${t}.allowedCidrs`),a=xt(n.allowPrivateNetwork,`${t}.allowPrivateNetwork`),o=xt(n.allowInsecureHttp,`${t}.allowInsecureHttp`),s=B(n.expiresAt,`${t}.expiresAt`),c=B(n.reason,`${t}.reason`),l={};return r.length>0&&(l.allowedHosts=r),i.length>0&&(l.allowedCidrs=i),a!==void 0&&(l.allowPrivateNetwork=a),o!==void 0&&(l.allowInsecureHttp=o),s!==void 0&&(l.expiresAt=s),c!==void 0&&(l.reason=c),l}function U(e,t,n){return Math.min(Math.max(e,t),n)}function W(e){return Math.round(e*100)/100}function Ct(e){let t=[...e].toSorted((e,t)=>e-t);return t.length===0?null:{count:t.length,minMs:t[0],maxMs:t[t.length-1],avgMs:W(t.reduce((e,t)=>e+t,0)/t.length),p50Ms:t[Math.floor(t.length*.5)],p90Ms:t[Math.floor(t.length*.9)],p95Ms:t[Math.floor(t.length*.95)],p99Ms:t[Math.floor(t.length*.99)]}}async function G(e,t,n){let r;try{r=new URL(e)}catch{throw Error(`url must be an absolute http:// or https:// URL`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`url must use the http:// or https:// scheme`);let i=x(t),a=!i&&h();if(i&&(i.allowPrivateNetwork||i.allowInsecureHttp)&&!_(i))throw Error(`authorization must include at least one allowed host or CIDR when enabling private network or insecure HTTP access.`);if(v(i))throw Error(`authorization expired before the request was executed.`);let o;try{o=await g(r.toString())}catch{throw Error(`${n} blocked: DNS resolution failed for "${r.toString()}"`)}let s=e=>a?!0:i?.allowPrivateNetwork===!0&&y(i,e),c=e=>a||p(e.hostname)?!0:i?.allowInsecureHttp===!0&&y(i,e),l=Number.parseInt(r.port||(r.protocol===`https:`?`443`:`80`),10);if(r.protocol===`http:`&&!c(o))throw Error(`${n} blocked: insecure HTTP is only allowed for loopback or explicitly authorized targets, got "${o.hostname}:${String(l)}"`);let u=b(o.hostname),d=b(o.resolvedAddress??``),f=p(o.hostname)||p(o.resolvedAddress??``);if((u||d)&&!f&&!s(o))throw!u&&d&&o.resolvedAddress?Error(`${n} blocked: "${o.hostname}:${String(l)}" resolved to private IP ${o.resolvedAddress}`):Error(`${n} blocked: target "${o.hostname}:${String(l)}" resolves to a private or reserved address.`);return{url:r,target:o,authorizationPolicy:i,allowLegacyLocalSsrf:a}}function wt(e){let t=e.trim();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function Tt(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Et(e){let t=(e.split(/\r?\n/,1)[0]?.trim()??``).split(/\s+/,1)[0]?.trim().toUpperCase()??``;if(!yt.test(t))throw Error(`requestText must start with a valid HTTP request line`);return t}async function Dt(e,t,n,r,i,a){return await new Promise((o,s)=>{let c=E.createConnection({host:e,port:t}),l=!1,u=!1,d=new Ze,f=()=>{c.removeAllListeners(),c.destroy()},p=e=>{l||(l=!0,f(),o({rawResponse:d.toBuffer(),endedBy:e}))},m=e=>{l||(l=!0,f(),s(e))};c.setTimeout(i),c.once(`connect`,()=>{c.end(n)}),c.on(`data`,e=>{if(u=!0,d.append(e),d.length>a){p(`max-bytes`);return}let t=ct(d.toBuffer(),r);if(!(!t||!t.complete)){if(t.bodyMode===`none`){p(`no-body`);return}if(t.bodyMode===`content-length`){p(`content-length`);return}t.bodyMode===`chunked`&&p(`chunked`)}}),c.once(`timeout`,()=>{if(!u){m(Error(`Timed out waiting for HTTP response from ${e}:${String(t)}`));return}p(`timeout`)}),c.once(`end`,()=>{p(`socket-close`)}),c.once(`error`,e=>{m(e)})})}function Ot(e){return e===void 0?null:Array.isArray(e)?e.map(e=>String(e)):String(e)}function kt(e){let t={};for(let[n,r]of Object.entries(e)){let e=Ot(r);e!==null&&(t[n]=e)}return t}async function At(e,t,n){let r=x(t),i=!r&&h();if(r&&r.allowPrivateNetwork&&!_(r))throw Error(`authorization must include at least one allowed host or CIDR when enabling private network access.`);if(v(r))throw Error(`authorization expired before the request was executed.`);let a;if(E.isIPv4(e))a=e;else try{a=(await D.resolve(e,`A`))[0]}catch{throw Error(`${n} blocked: DNS resolution failed for "${e}"`)}let o=b(e),s=b(a),c=p(e)||p(a);if((o||s)&&!c&&!i&&!(r?.allowPrivateNetwork===!0&&y(r,{hostname:e,resolvedAddress:a})))throw Error(!o&&s?`${n} blocked: "${e}" resolved to private IP ${a}`:`${n} blocked: target "${e}" resolves to a private or reserved address.`);return a}function jt(e){if(!e)return null;let t=e.trim();return t.length>0?t:null}function Mt(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n.toLowerCase()]=r;return t}function Nt(e){let{url:t,target:n,method:r,requestHeaders:i,bodyBuffer:a,timeoutMs:o,maxBodyBytes:s,effectivePort:c,requestedAlpnProtocols:l,connectTimeoutMs:u=1e4}=e,d=null;return new Promise((e,f)=>{let p=!1,m,h=new Ze,g=!1,_=null,v=null,y=ee.connect(t.origin,{createConnection:()=>{if(t.protocol===`https:`){let e=O.connect({host:n.resolvedAddress??n.hostname,port:c,servername:n.hostname,ALPNProtocols:l,rejectUnauthorized:!0}),r=setTimeout(()=>{e.destroy(Error(`Timed out connecting to ${t.toString()} (${u}ms)`))},u);return e.once(`secureConnect`,()=>{clearTimeout(r),d=jt(e.alpnProtocol)}),e.once(`error`,()=>clearTimeout(r)),e.setTimeout(o,()=>{e.destroy(Error(`Timed out probing HTTP/2 endpoint ${t.toString()}`))}),v=e,e}let e=E.connect({host:n.resolvedAddress??n.hostname,port:c});return e.setTimeout(o,()=>{e.destroy(Error(`Timed out probing HTTP/2 endpoint ${t.toString()}`))}),v=e,e}}),b=()=>{_?.removeAllListeners(),y.removeAllListeners()},x=()=>{p||(p=!0,b(),y.close(),e({responseHeaders:m??{},bodyBuffer:h.toBuffer(),truncated:g,alpnProtocol:d}))},S=e=>{p||(p=!0,b(),y.destroy(e),f(e))};y.once(`error`,e=>{v instanceof O.TLSSocket&&(d=jt(v.alpnProtocol)),S(e instanceof Error?e:Error(String(e)))}),y.once(`connect`,()=>{v instanceof O.TLSSocket&&(d=jt(v.alpnProtocol)),_=y.request({":method":r,":path":`${t.pathname}${t.search}`,":scheme":t.protocol.slice(0,-1),":authority":t.host,...i}),_.once(`response`,e=>{m=e}),_.on(`data`,e=>{let t=Buffer.isBuffer(e)?e:Buffer.from(e,`utf8`),n=s-h.length;n>0&&h.append(t.subarray(0,n)),t.length>n&&!g&&(g=!0,_?.close(ee.constants.NGHTTP2_CANCEL))}),_.once(`end`,x),_.once(`close`,()=>{g&&x()}),_.once(`error`,e=>{S(e instanceof Error?e:Error(String(e)))}),a.length>0?_.end(a):_.end()})})}const K=[`A`,`AAAA`,`MX`,`TXT`,`NS`,`CNAME`,`SOA`,`PTR`,`SRV`,`ANY`];function Pt(e){return e?e===`ENOTFOUND`?`NXDOMAIN`:e===`ENODATA`?`NODATA`:e===`ESERVFAIL`?`SERVFAIL`:e===`ETIMEOUT`?`TIMEOUT`:e===`ECONNREFUSED`?`CONNREFUSED`:e===`EREFUSED`?`REFUSED`:`ERROR`:`ERROR`}function q(e){return Math.round((performance.now()-e)*100)/100}var Ft=class{eventBus;constructor(e){this.eventBus=e}async handleDnsResolve(e){try{let t=B(e.hostname,`hostname`);if(!t)return f.text(`hostname is required`,!0);let n=B(e.rrType,`rrType`)??`A`;if(!K.includes(n))return f.text(`Invalid rrType: "${n}". Expected one of: ${K.join(`, `)}`,!0);let r=performance.now(),i=await D.resolve(t,n),a=q(r);return f.ok().json({hostname:t,rrType:n,records:i,timing:a})}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`DNS resolve failed: ${t}`).json()}}async handleDnsReverse(e){try{let t=B(e.ip,`ip`);if(!t)return f.text(`ip is required`,!0);let n=performance.now(),r=await D.reverse(t),i=q(n);return f.ok().json({ip:t,hostnames:r,timing:i})}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`DNS reverse lookup failed: ${t}`).json()}}async handleDnsProbe(e){try{let t=B(e.hostname,`hostname`);if(!t)return f.text(`hostname is required`,!0);let n=B(e.rrType,`rrType`)??`A`;if(!K.includes(n))return f.text(`Invalid rrType: "${n}". Expected one of: ${K.join(`, `)}`,!0);let r=performance.now();try{let e=await D.resolve(t,n),i=q(r);return f.ok().json({hostname:t,rrType:n,status:`NOERROR`,records:e,timing:i})}catch(e){let i=q(r),a=e instanceof Error&&`code`in e?e.code:void 0,o=Pt(a);return f.ok().json({hostname:t,rrType:n,status:o,records:[],timing:i,errorCode:a??null})}}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`DNS probe failed: ${t}`).json()}}async handleDnsCnameChain(e){try{let t=B(e.hostname,`hostname`);if(!t)return f.text(`hostname is required`,!0);let n=P(e.maxDepth,{defaultValue:10,min:1,max:30,integer:!0}),r=[],i=t;for(let e=0;e<n;e++){let t=performance.now();try{let n=await D.resolve(i,`CNAME`),a=q(t),o=n[0]??null;if(r.push({host:i,target:o,status:`CNAME`,depth:e,timing:a}),o)i=o;else break}catch(n){let a=q(t),o=n instanceof Error&&`code`in n?n.code:void 0,s=o===`ENOTFOUND`||o===`ENODATA`?`TERMINAL`:Pt(o);r.push({host:i,target:null,status:s,depth:e,timing:a});break}}return f.ok().json({hostname:t,chain:r,depth:r.length})}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`CNAME chain trace failed: ${t}`).json()}}async handleDnsBulkResolve(e){try{let t=V(e.hostnames,`hostnames`);if(t.length===0)return f.text(`hostnames must be a non-empty array`,!0);if(t.length>1e3)return f.text(`hostnames array too large (max 1000)`,!0);let n=B(e.rrType,`rrType`)??`A`;if(!K.includes(n))return f.text(`Invalid rrType: "${n}". Expected one of: ${K.join(`, `)}`,!0);let r=P(e.concurrency,{defaultValue:10,min:1,max:50,integer:!0}),i=[];for(let e=0;e<t.length;e+=r){let a=t.slice(e,e+r),o=await Promise.all(a.map(async e=>{let t=performance.now();try{return{hostname:e,status:`NOERROR`,records:await D.resolve(e,n),timing:q(t)}}catch(n){let r=q(t);return{hostname:e,status:Pt(n instanceof Error&&`code`in n?n.code:void 0),records:[],timing:r}}}));i.push(...o)}let a=i.filter(e=>e.status!==`NOERROR`).length;return f.ok().json({results:i,total:i.length,errors:a,rrType:n})}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`Bulk DNS resolve failed: ${t}`).json()}}async handleHttpRequestBuild(e){try{let t=B(e.method,`method`),n=B(e.target,`target`);if(!t)throw Error(`method is required`);if(!n)throw Error(`target is required`);let r=st({method:t,target:n,host:B(e.host,`host`),headers:St(e.headers,`headers`),body:bt(e.body,`body`,{allowEmpty:!0}),httpVersion:B(e.httpVersion,`httpVersion`)??`1.1`,addHostHeader:N(e.addHostHeader,!0),addContentLength:N(e.addContentLength,!0),addConnectionClose:N(e.addConnectionClose,!0)});return M(this.eventBus,`network:http_request_built`,{method:r.startLine.split(` `,1)[0]??`UNKNOWN`,target:n,byteLength:r.requestBytes,timestamp:new Date().toISOString()}),f.ok().merge(r).json()}catch(e){return f.fail(e instanceof Error?e.message:String(e)).json()}}async handleHttpPlainRequest(e){try{let t=B(e.host,`host`),n=bt(e.requestText,`requestText`);if(!t)throw Error(`host is required`);if(!n)throw Error(`requestText is required`);let r=wt(t),i=P(e.port,{defaultValue:80,min:1,max:65535,integer:!0}),a=P(e.timeoutMs,{defaultValue:3e4,min:1,max:12e4,integer:!0}),o=P(e.maxResponseBytes,{defaultValue:512e3,min:256,max:5242880,integer:!0}),s=Et(n),c=H(e.authorization),{target:l}=await G(`http://${Tt(r)}:${String(i)}/`,c,`HTTP request`);if(c){let e=(n.split(/\r?\n/,1)[0]??``).split(/\s+/)[1]??``;if(e.includes(`://`))try{let t=wt(new URL(e).hostname);if(t!==r&&t!==(l.resolvedAddress??``))throw Error(`HTTP request blocked: request-line target host "${t}" does not match authorized host "${r}"`)}catch(e){if(e instanceof Error&&e.message.startsWith(`HTTP request blocked:`))throw e}let t=n.match(/^Host:\s*(\S+)/im)?.[1];if(t){let e=wt(t.replace(/:\d+$/,``));if(e!==r&&e!==(l.resolvedAddress??``))throw Error(`HTTP request blocked: Host header "${t}" does not match authorized host "${r}"`)}}let u=await Dt(l.resolvedAddress??l.hostname,i,Buffer.from(n,`utf8`),s,a,o),d=ct(u.rawResponse,s);if(!d)throw Error(`Received data but could not parse complete HTTP response headers.`);let p=lt(d.rawHeaders.find(e=>e.name.toLowerCase()===`content-type`)?.value??null,d.bodyBuffer),m=d.complete||d.bodyMode===`until-close`&&u.endedBy===`socket-close`;return M(this.eventBus,`network:http_plain_request_completed`,{host:r,port:i,statusCode:d.statusCode,byteLength:u.rawResponse.length,timestamp:new Date().toISOString()}),f.ok().merge({host:r,port:i,resolvedAddress:l.resolvedAddress??l.hostname,requestBytes:Buffer.byteLength(n,`utf8`),response:{statusLine:d.statusLine,httpVersion:d.httpVersion,statusCode:d.statusCode,statusText:d.statusText,headers:d.headers,rawHeaders:d.rawHeaders,headerBytes:d.headerBytes,bodyBytes:d.bodyBytes,bodyMode:d.bodyMode,chunkedDecoded:d.chunkedDecoded,complete:m,truncated:u.endedBy===`max-bytes`,endedBy:u.endedBy,bodyText:p?d.bodyBuffer.toString(`utf8`):void 0,bodyBase64:p?void 0:d.bodyBuffer.toString(`base64`)}}).json()}catch(e){return f.fail(e instanceof Error?e.message:String(e)).json()}}},It=class{eventBus;constructor(e){this.eventBus=e}async handleHttp2Probe(e){let t=B(e.url,`url`),n=t??``,r=null,i=null,a=!1;try{if(!t)throw Error(`url is required`);let o=(B(e.method,`method`)??`GET`).toUpperCase();if(!yt.test(o))throw Error(`method must be a valid HTTP token`);let s=P(e.timeoutMs,{defaultValue:3e4,min:1,max:12e4,integer:!0}),c=P(e.maxBodyBytes,{defaultValue:32768,min:128,max:1048576,integer:!0}),l=e.body,u=l!=null&&typeof l!=`string`,d=typeof l==`string`?l:u?JSON.stringify(l):``,p=Buffer.from(d,`utf8`),m=V(e.alpnProtocols,`alpnProtocols`),h=Mt(St(e.headers,`headers`));u&&p.length>0&&!(`content-type`in h)&&(h[`content-type`]=`application/json`);let{url:g,target:_}=await G(t,H(e.authorization),`HTTP/2 probe`);n=g.toString(),!(`content-length`in h)&&p.length>0&&(h[`content-length`]=String(p.length));let{responseHeaders:v,bodyBuffer:y,truncated:b,alpnProtocol:x}=await Nt({url:g,target:_,method:o,requestHeaders:h,bodyBuffer:p,timeoutMs:s,maxBodyBytes:c,effectivePort:Number.parseInt(g.port||(g.protocol===`https:`?`443`:`80`),10),requestedAlpnProtocols:m.length>0?m:[`h2`,`http/1.1`]}),S=kt(v),C=v[`:status`],w=typeof C==`number`?C:typeof C==`string`?Number.parseInt(C,10):null,T=lt(typeof S[`content-type`]==`string`?S[`content-type`]:Array.isArray(S[`content-type`])?S[`content-type`][0]??null:null,y);return r=Number.isFinite(w??NaN)?w:null,i=x,a=!0,f.ok().merge({url:n,statusCode:r,alpnProtocol:i,headers:S,bodyBytes:y.length,truncated:b,bodyText:T?y.toString(`utf8`):void 0,bodyBase64:T?void 0:y.toString(`base64`)}).json()}catch(e){return f.fail(e instanceof Error?e.message:String(e)).json()}finally{M(this.eventBus,`network:http2_probed`,{url:n,success:a,statusCode:r,alpnProtocol:i,timestamp:new Date().toISOString()})}}async handleHttp2FrameBuild(e){let t=B(e.frameType,`frameType`);if(!t)throw Error(`frameType is required`);let n=[`DATA`,`SETTINGS`,`PING`,`WINDOW_UPDATE`,`RST_STREAM`,`GOAWAY`,`RAW`],r=t.toUpperCase();if(!n.includes(r))throw Error(`frameType must be one of: ${n.join(`, `)}`);let i=e.streamId===void 0?void 0:P(e.streamId,{defaultValue:0,min:0,integer:!0}),a=e.flags===void 0?void 0:P(e.flags,{defaultValue:0,min:0,max:255,integer:!0}),o=e.frameTypeCode===void 0?void 0:P(e.frameTypeCode,{defaultValue:0,min:0,max:255,integer:!0}),s=e.windowSizeIncrement===void 0?void 0:P(e.windowSizeIncrement,{defaultValue:1,min:1,integer:!0}),c=e.errorCode===void 0?void 0:P(e.errorCode,{defaultValue:0,min:0,integer:!0}),l=e.lastStreamId===void 0?void 0:P(e.lastStreamId,{defaultValue:0,min:0,integer:!0}),u=B(e.payloadHex,`payloadHex`),d=bt(e.payloadText,`payloadText`,{allowEmpty:!0}),p=B(e.payloadEncoding,`payloadEncoding`),m=xt(e.ack,`ack`),h=B(e.pingOpaqueDataHex,`pingOpaqueDataHex`),g=bt(e.debugDataText,`debugDataText`,{allowEmpty:!0}),_=B(e.debugDataEncoding,`debugDataEncoding`),v;if(e.settings!==void 0){if(!Array.isArray(e.settings))throw Error(`settings must be an array`);v=e.settings.map((e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`settings[${String(t)}] must be an object with id and value`);return{id:typeof e.id==`number`?e.id:(()=>{throw Error(`settings[${String(t)}].id must be a number`)})(),value:typeof e.value==`number`?e.value:(()=>{throw Error(`settings[${String(t)}].value must be a number`)})()}})}let y=vt({frameType:r,...i!==void 0&&{streamId:i},...a!==void 0&&{flags:a},...o!==void 0&&{frameTypeCode:o},...u!==void 0&&{payloadHex:u},...d!==void 0&&{payloadText:d},...p!==void 0&&{payloadEncoding:p},...v!==void 0&&{settings:v},...m!==void 0&&{ack:m},...h!==void 0&&{pingOpaqueDataHex:h},...s!==void 0&&{windowSizeIncrement:s},...c!==void 0&&{errorCode:c},...l!==void 0&&{lastStreamId:l},...g!==void 0&&{debugDataText:g},..._!==void 0&&{debugDataEncoding:_}});return M(this.eventBus,`network:http2_frame_build_completed`,{frameType:y.frameType,typeCode:y.typeCode,streamId:y.streamId,flags:y.flags,payloadBytes:y.payloadBytes,timestamp:new Date().toISOString()}),f.ok().merge(y).json()}};function J(e){return`${e&255}.${e>>>8&255}.${e>>>16&255}.${e>>>24&255}`}function Lt(e){let t=e.split(`.`);return t.length===4?t.every(e=>{let t=parseInt(e,10);return!isNaN(t)&&t>=0&&t<=255&&e===String(t)}):!1}let Y=null;const Rt={0:`SUCCESS`,11001:`BUF_TOO_SMALL`,11002:`DEST_NET_UNREACHABLE`,11003:`DEST_HOST_UNREACHABLE`,11004:`DEST_PROT_UNREACHABLE`,11005:`DEST_PORT_UNREACHABLE`,11009:`PACKET_TOO_BIG`,11010:`REQ_TIMED_OUT`,11013:`TTL_EXPIRED_TRANSIT`,11014:`TTL_EXPIRED_REASSEM`,11015:`PARAM_PROBLEM`,11016:`SOURCE_QUENCH`,11050:`GENERAL_FAILURE`};function zt(e){return Rt[e]??`UNKNOWN_${e}`}function Bt(e){return e===0?`success`:e===11010?`timeout`:e===11013||e===11014?`time_exceeded`:e>=11002&&e<=11005?`destination_unreachable`:e===11016?`source_quench`:e===11009?`packet_too_big`:e===11015?`parameter_problem`:`error`}let Vt=null,Ht=null,Ut=null,Wt=null;function Gt(){return Vt||(Vt=T.load(`iphlpapi.dll`),e.debug(`Loaded iphlpapi.dll via koffi`)),Vt}function Kt(){return Ht||(Ht=T.load(`ws2_32.dll`),e.debug(`Loaded ws2_32.dll via koffi`)),Ht}function qt(){if(!Ut){let e=Gt(),t=Kt(),n=e.func(`uint32 IcmpSendEcho(void *, uint32, void *, uint16, void *, void *, uint32, uint32)`);Ut={inetAddr:t.func(`uint32 inet_addr(char *)`),createFile:e.func(`void * IcmpCreateFile()`),closeHandle:e.func(`int IcmpCloseHandle(void *)`),sendEcho:n}}return Ut}function Jt(e){return Math.max(256,e+64)}function Yt(e){let t=Buffer.alloc(16,0);return t.writeUInt8(e,0),t}function Xt(e){return{address:e.readUInt32LE(0),status:e.readUInt32LE(4),rtt:e.readUInt32LE(8)}}function Zt(e){return qt().inetAddr(e)}function Qt(){return qt().createFile()}function $t(e){return qt().closeHandle(e)!==0}async function en(e,t,n,r,i){let a=Buffer.alloc(Jt(n.length));return{numReplies:await new Promise((o,s)=>{qt().sendEcho.async(e,t,n,n.length,r,a,a.length,i,(e,t)=>{if(e){s(e);return}o(Number(t))})}),replyBuf:a}}async function tn(e){let{target:t,ttl:r=128,packetSize:i=n,timeout:o=a}=e,s=Zt(t);if(s===4294967295)return{target:t,ip:``,alive:!1,rtt:null,ttl:r,icmpStatus:`INVALID_ADDRESS`,errorClass:`error`,packetSize:i};let c=Qt();try{let{numReplies:e,replyBuf:n}=await en(c,s,Buffer.alloc(i,170),Yt(r),o);if(e===0)return{target:t,ip:J(s),alive:!1,rtt:null,ttl:r,icmpStatus:`REQ_TIMED_OUT`,errorClass:`timeout`,packetSize:i};let a=Xt(n);return{target:t,ip:J(a.address),alive:a.status===0,rtt:a.status===0?a.rtt:null,ttl:r,icmpStatus:zt(a.status),errorClass:Bt(a.status),packetSize:i}}finally{$t(c)}}async function nn(e){let{target:r,maxHops:i=t,timeout:o=a,packetSize:s=n}=e,c=Zt(r);if(c===4294967295)return{target:r,ip:``,hops:[],reached:!1,totalHops:0,totalTime:0};let l=Qt(),u=[],d=performance.now();try{for(let e=1;e<=i;e++){let{numReplies:t,replyBuf:n}=await en(l,c,Buffer.alloc(s,170),Yt(e),o);if(t===0){u.push({hop:e,ip:null,rtt:null,status:`REQ_TIMED_OUT`,errorClass:`timeout`});continue}let r=Xt(n),i=J(r.address);if(u.push({hop:e,ip:i,rtt:r.rtt,status:zt(r.status),errorClass:Bt(r.status)}),r.status===0)break}}finally{$t(l)}let f=u[u.length-1];return{target:r,ip:J(c),hops:u,reached:f?.status===`SUCCESS`,totalHops:u.length,totalTime:Math.round((performance.now()-d)*100)/100}}const rn=process.platform===`darwin`?4102:20,an=process.platform===`darwin`?`/usr/lib/libSystem.B.dylib`:`libc.so.6`;let on=null;function sn(){return on||(on=T.load(an),e.debug(`Loaded ${an} via koffi for ICMP`)),on}function X(){if(!Wt){let e=sn();Wt={socket:e.func(`int socket(int, int, int)`),setsockopt:e.func(`int setsockopt(int, int, int, void *, int)`),sendto:e.func(`int sendto(int, void *, int, int, void *, int)`),recv:e.func(`int recv(int, void *, int, int)`),close:e.func(`int close(int)`)}}return Wt}function cn(e,t,n){return X().socket(e,t,n)}function ln(e,t,n,r,i){return X().setsockopt(e,t,n,r,i)}function un(e,t,n){return X().sendto(e,t,t.length,0,n,16)}function dn(e,t){return X().recv(e,t,t.length,0)}function fn(e){return X().close(e)}function pn(e){let t=0;for(let n=0;n<e.length-1;n+=2)t+=e.readUInt16BE(n);for(e.length&1&&(t+=(e[e.length-1]??0)<<8);t>65535;)t=(t&65535)+(t>>>16);return~t&65535}function mn(e,t,n){let r=Buffer.alloc(8+n);r[0]=8,r[1]=0,r.writeUInt16BE(e&65535,4),r.writeUInt16BE(t&65535,6);for(let e=8;e<r.length;e++)r[e]=170;return r.writeUInt16BE(pn(r),2),r}function hn(e){let t=Buffer.alloc(16,0);t.writeUInt16LE(2,0);let n=e.split(`.`).map(Number);return t[4]=n[0]??0,t[5]=n[1]??0,t[6]=n[2]??0,t[7]=n[3]??0,t}function gn(e,t,n){if(t<20)return null;let r=((e[0]??0)&15)*4;if(t<r+8)return null;let i=e[r]??0,a=e[r+1]??0,o=e.readUInt32LE(12);if(i===0)return e.readUInt16BE(r+4)===n?{type:i,code:a,fromIp:o}:null;if(i===11||i===3){let s=r+8;if(t<s+28)return null;let c=((e[s]??0)&15)*4;return t<s+c+8||e.readUInt16BE(s+c+4)!==n?null:{type:i,code:a,fromIp:o}}return null}function _n(e,t,n){return e===0?`SUCCESS`:n?`REQ_TIMED_OUT`:e===11&&t===0?`TTL_EXPIRED_TRANSIT`:e===11&&t===1?`TTL_EXPIRED_REASSEM`:e===3&&t===0?`DEST_NET_UNREACHABLE`:e===3&&t===1?`DEST_HOST_UNREACHABLE`:e===3&&t===2?`DEST_PROT_UNREACHABLE`:e===3&&t===3?`DEST_PORT_UNREACHABLE`:`UNKNOWN_${e}_${t}`}function vn(e,t,n){return e===0?`success`:n?`timeout`:e===11?`time_exceeded`:e===3?`destination_unreachable`:`error`}function yn(e,t){let n=Buffer.alloc(4);n.writeInt32LE(t),ln(e,0,2,n,4)}function bn(e,t){let n=Buffer.alloc(16,0);n.writeInt32LE(Math.floor(t/1e3),0),n.writeInt32LE(t%1e3*1e3,8),ln(e,1,rn,n,16)}function xn(e){let{target:t,ttl:r=128,packetSize:i=n,timeout:o=a}=e;if(!Lt(t))return{target:t,ip:``,alive:!1,rtt:null,ttl:r,icmpStatus:`INVALID_ADDRESS`,errorClass:`error`,packetSize:i};let s=cn(2,3,1);if(s<0)return{target:t,ip:``,alive:!1,rtt:null,ttl:r,icmpStatus:`SOCKET_ERROR`,errorClass:`error`,packetSize:i};try{yn(s,r),bn(s,o);let e=process.pid&65535,n=mn(e,1,i),a=hn(t),c=performance.now();if(un(s,n,a)<0)return{target:t,ip:t,alive:!1,rtt:null,ttl:r,icmpStatus:`SEND_ERROR`,errorClass:`error`,packetSize:i};let l=Buffer.alloc(512),u=dn(s,l),d=Math.round(performance.now()-c);if(u<=0)return{target:t,ip:t,alive:!1,rtt:null,ttl:r,icmpStatus:`REQ_TIMED_OUT`,errorClass:`timeout`,packetSize:i};let f=gn(l,u,e);if(!f)return{target:t,ip:t,alive:!1,rtt:null,ttl:r,icmpStatus:`UNEXPECTED_REPLY`,errorClass:`error`,packetSize:i};let p=f.type===0;return{target:t,ip:J(f.fromIp),alive:p,rtt:p?d:null,ttl:r,icmpStatus:_n(f.type,f.code,!1),errorClass:vn(f.type,f.code,!1),packetSize:i}}finally{fn(s)}}function Sn(e){let{target:r,maxHops:i=t,timeout:o=a,packetSize:s=n}=e;if(!Lt(r))return{target:r,ip:``,hops:[],reached:!1,totalHops:0,totalTime:0};let c=cn(2,3,1);if(c<0)return{target:r,ip:``,hops:[],reached:!1,totalHops:0,totalTime:0};let l=[],u=process.pid&65535,d=hn(r),f=performance.now(),p=0;try{bn(c,o);for(let e=1;e<=i;e++){yn(c,e);let t=mn(u,e,s),n=performance.now();if(un(c,t,d)<0){if(p++,l.push({hop:e,ip:null,rtt:null,status:`SEND_ERROR`,errorClass:`error`}),p>=5)break;continue}p=0;let r=Buffer.alloc(512),i=dn(c,r),a=Math.round(performance.now()-n);if(i<=0){l.push({hop:e,ip:null,rtt:null,status:`REQ_TIMED_OUT`,errorClass:`timeout`});continue}let o=gn(r,i,u);if(!o){l.push({hop:e,ip:null,rtt:null,status:`UNEXPECTED_REPLY`,errorClass:`error`});continue}let f=_n(o.type,o.code,!1),m=vn(o.type,o.code,!1);if(l.push({hop:e,ip:J(o.fromIp),rtt:a,status:f,errorClass:m}),o.type===0)break}}finally{fn(c)}return{target:r,ip:r,hops:l,reached:l[l.length-1]?.status===`SUCCESS`,totalHops:l.length,totalTime:Math.round((performance.now()-f)*100)/100}}const Cn=process.platform===`linux`||process.platform===`darwin`;function wn(){if(Y!==null)return Y;if(process.platform===`win32`)try{return T.load(`iphlpapi.dll`).unload(),Y=!0,!0}catch{return Y=!1,!1}if(Cn){try{let e=cn(2,3,1);e>=0?(fn(e),Y=!0):Y=!1}catch{Y=!1}return Y}return Y=!1,!1}async function Tn(e){let{target:t,ttl:r=128,packetSize:i=n,timeout:o=a}=e;return wn()?process.platform===`win32`?tn({target:t,ttl:r,packetSize:i,timeout:o}):xn({target:t,ttl:r,packetSize:i,timeout:o}):{target:t,ip:``,alive:!1,rtt:null,ttl:r,icmpStatus:`PLATFORM_NOT_SUPPORTED`,errorClass:`error`,packetSize:i}}async function En(e){let{target:r,maxHops:i=t,timeout:o=a,packetSize:s=n}=e;return wn()?process.platform===`win32`?nn({target:r,maxHops:i,timeout:o,packetSize:s}):Sn({target:r,maxHops:i,timeout:o,packetSize:s}):{target:r,ip:``,hops:[],reached:!1,totalHops:0,totalTime:0}}var Dn=class{eventBus;constructor(e){this.eventBus=e}async handleNetworkRttMeasure(e){let t=B(e.url,`url`);if(!t)throw Error(`url is required`);let n=B(e.probeType,`probeType`)??`tcp`;if(![`tcp`,`tls`,`http`].includes(n))throw Error(`probeType must be one of: tcp, tls, http`);let r=U(e.iterations===void 0?5:P(e.iterations,{defaultValue:5,min:1,integer:!0}),1,50),i=U(e.timeoutMs===void 0?5e3:P(e.timeoutMs,{defaultValue:5e3,min:100,integer:!0}),100,3e4),{url:a,target:o}=await G(t,H(e.authorization),`RTT measurement`),s=o.hostname,c=Number(a.port)||(a.protocol===`https:`?443:80),l=o.resolvedAddress??s,u=a.protocol===`https:`,d=[],p=[];for(let e=0;e<r;e+=1)try{let e=await this.measureSingleRtt(s,l,c,n,i,u);d.push(e)}catch(e){p.push(e instanceof Error?e.message:String(e))}let m=Ct(d);return M(this.eventBus,`network:rtt_measured`,{url:t,probeType:n,iterations:r,successCount:d.length,errorCount:p.length,stats:m,timestamp:new Date().toISOString()}),f.ok().merge({target:{hostname:s,port:c,resolvedIp:l,probeType:n},stats:m,samples:d,errors:p.length>0?p:void 0,timestamp:new Date().toISOString()}).json()}async handleNetworkTraceroute(e){try{if(!wn())return f.text(`ICMP traceroute not available on this platform (Windows: native API, Linux/macOS: requires root/CAP_NET_RAW)`,!0);let t=B(e.target,`target`);if(!t)return f.text(`target is required`,!0);let n=H(e.authorization),r;try{r=await At(t,n,`Traceroute`)}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(t).json()}let i=U(e.maxHops===void 0?30:Number(e.maxHops),1,64),a=U(e.timeout===void 0?5e3:Number(e.timeout),100,3e4),o=U(e.packetSize===void 0?32:Number(e.packetSize),8,65500),s=await En({target:r,maxHops:i,timeout:a,packetSize:o});return f.ok().merge({resolvedFrom:t}).json(s)}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`Traceroute failed: ${t}`).json()}}async handleNetworkLatencyStats(e){let t=B(e.url,`url`);if(!t)return f.text(`url is required`,!0);let n=B(e.probeType,`probeType`)??`http`;if(![`tcp`,`tls`,`http`].includes(n))return f.text(`Invalid probeType: "${n}". Expected one of: tcp, tls, http`,!0);let r=U(e.iterations===void 0?20:P(e.iterations,{defaultValue:20,min:5,integer:!0}),5,100),i=U(e.concurrency===void 0?5:P(e.concurrency,{defaultValue:5,min:1,integer:!0}),1,20),a=U(e.timeoutMs===void 0?5e3:P(e.timeoutMs,{defaultValue:5e3,min:100,integer:!0}),100,3e4),{url:o,target:s}=await G(t,H(e.authorization),`Latency stats`),c=s.hostname,l=Number(o.port)||(o.protocol===`https:`?443:80),u=s.resolvedAddress??c,d=o.protocol===`https:`,p=[],m=[];for(let e=0;e<r;e+=i){let t=Array.from({length:Math.min(i,r-e)},(t,n)=>n+e),o=await Promise.allSettled(t.map(()=>this.measureSingleRtt(c,u,l,n,a,d)));for(let e of o)e.status===`fulfilled`?p.push(e.value):m.push(e.reason instanceof Error?e.reason.message:String(e.reason))}let h=Ct(p);return f.ok().json({url:t,target:{hostname:c,port:l,resolvedIp:u,probeType:n},iterations:r,concurrency:i,stats:h,errors:m.length>0?m:void 0})}async handleNetworkIcmpProbe(e){try{if(!wn())return f.text(`ICMP probe not available on this platform (Windows: native API, Linux/macOS: requires root/CAP_NET_RAW)`,!0);let t=B(e.target,`target`);if(!t)return f.text(`target is required`,!0);let n=H(e.authorization),r;try{r=await At(t,n,`ICMP probe`)}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(t).json()}let i=U(e.ttl===void 0?128:Number(e.ttl),1,255),a=U(e.timeout===void 0?5e3:Number(e.timeout),100,3e4),o=U(e.packetSize===void 0?32:Number(e.packetSize),8,65500),s=await Tn({target:r,ttl:i,packetSize:o,timeout:a});return f.ok().merge({resolvedFrom:t}).json(s)}catch(e){let t=e instanceof Error?e.message:String(e);return f.fail(`ICMP probe failed: ${t}`).json()}}measureSingleRtt(e,t,n,r,i,a){switch(r){case`tcp`:return this.probeTcp(t,n,i);case`tls`:return this.probeTls(e,t,n,i);case`http`:return this.probeHttp(e,t,n,i,a)}}createPinnedLookup(e){let t=E.isIP(e)===6?6:4;return(n,r,i)=>{let a=typeof r==`function`?r:i;if(a){if(r&&typeof r==`object`&&`all`in r&&r.all){a(null,[{address:e,family:t}]);return}a(null,e,t)}}}probeTcp(e,t,n){return new Promise((r,i)=>{let a=performance.now(),o=setTimeout(()=>i(Error(`TCP probe timed out after ${n}ms`)),n),s=E.createConnection({host:e,port:t},()=>{clearTimeout(o),s.destroy(),r(W(performance.now()-a))});s.on(`error`,e=>{clearTimeout(o),s.destroy(),i(e)})})}probeTls(e,t,n,r){return new Promise((i,a)=>{let o=performance.now(),s=!1,c=null,l=e=>{s||(s=!0,clearTimeout(u),c?.destroy(),e())},u=setTimeout(()=>{l(()=>a(Error(`TLS probe timed out after ${r}ms`)))},r);c=O.connect({host:e,port:n,lookup:this.createPinnedLookup(t),...E.isIP(e)===0?{servername:e}:{}},()=>{l(()=>i(W(performance.now()-o)))}),c.on(`error`,e=>{l(()=>a(e))})})}probeHttp(e,t,n,r,i){return new Promise((a,o)=>{let s=performance.now(),c=!1,l=null,u=e=>{c||(c=!0,clearTimeout(d),l?.destroy(),e())},d=setTimeout(()=>{u(()=>o(Error(`HTTP probe timed out after ${r}ms`)))},r);l=(i?te.request:S.request)({host:e,port:n,path:`/`,method:`HEAD`,lookup:this.createPinnedLookup(t),...i&&E.isIP(e)===0?{servername:e}:{}},e=>{e.resume(),u(()=>a(W(performance.now()-s)))}),l.on(`error`,e=>{u(()=>o(e))}),l.end()})}},On=class extends Dn{dnsHttp;http2;constructor(e){super(e),this.dnsHttp=new Ft(e),this.http2=new It(e)}handleDnsResolve(e){return this.dnsHttp.handleDnsResolve(e)}handleDnsReverse(e){return this.dnsHttp.handleDnsReverse(e)}handleDnsProbe(e){return this.dnsHttp.handleDnsProbe(e)}handleDnsCnameChain(e){return this.dnsHttp.handleDnsCnameChain(e)}handleDnsBulkResolve(e){return this.dnsHttp.handleDnsBulkResolve(e)}handleHttpRequestBuild(e){return this.dnsHttp.handleHttpRequestBuild(e)}handleHttpPlainRequest(e){return this.dnsHttp.handleHttpPlainRequest(e)}handleHttp2Probe(e){return this.http2.handleHttp2Probe(e)}handleHttp2FrameBuild(e){return this.http2.handleHttp2FrameBuild(e)}};const kn=new Set([`0a0a`,`1a1a`,`2a2a`,`3a3a`,`4a4a`,`5a5a`,`6a6a`,`7a7a`,`8a8a`,`9a9a`,`aaaa`,`baba`,`caca`,`dada`,`eaea`,`fafa`]);function Z(e){return kn.has(e.replace(`0x`,``).toLowerCase().padStart(4,`0`))}function Q(e){return C(`sha256`).update(e).digest(`hex`).substring(0,12)}function $(e){return e.replace(`0x`,``).toLowerCase().padStart(4,`0`)}const An={"0304":`13`,"0303":`12`,"0302":`11`,"0301":`10`,"0300":`s3`,"0002":`s2`,feff:`d1`,fefd:`d2`,fefc:`d3`};function jn(e){return An[e.toLowerCase()]??`00`}function Mn(e){if(!e||e.length===0)return`00`;let t=e[0],n=e[e.length-1],r=/[0-9a-zA-Z]/.test(t),i=/[0-9a-zA-Z]/.test(n);if(r&&i)return`${t}${n}`;let a=Buffer.from(e,`utf8`).toString(`hex`);return`${a[0]??`0`}${a[a.length-1]??`0`}`}function Nn(e){let{protocol:t,tlsVersion:n,hasSni:r,ciphers:i,extensions:a,signatureAlgorithms:o,alpn:s}=e,c=t===`quic`?`q`:t===`dtls`?`d`:`t`,l=[n].map($).filter(e=>!Z(e)&&e!==`0303`),u=(n.length>0?l:[`0303`]).toSorted(),d=jn(u.length>0?u[u.length-1]:`0303`),f=r?`d`:`i`,p=i.map($).filter(e=>!Z(e)),m=a.map($).filter(e=>!Z(e)),h=`${c}${d}${f}${String(Math.min(p.length,99)).padStart(2,`0`)}${String(Math.min(m.length,99)).padStart(2,`0`)}${Mn(s)}`,g=p.toSorted().join(`,`),_=p.length>0?Q(g):`000000000000`,v=m.filter(e=>e!==`0000`&&e!==`0010`).toSorted(),y=o.map($),b;return b=y.length>0?`${v.join(`,`)}_${y.join(`,`)}`:v.join(`,`),{tls:`${h}_${_}_${v.length>0||y.length>0?Q(b):`000000000000`}`,tls_raw:`${h}_${p.join(`,`)}_${m.join(`,`)}_${y.join(`,`)}`}}function Pn(e,t,n,r,i){let a=e.toUpperCase(),o={GET:`ge`,POST:`po`,PUT:`pu`,DELETE:`de`,HEAD:`he`,PATCH:`pa`,OPTIONS:`ot`}[a]??a.toLowerCase().substring(0,2).padEnd(2,a.charAt(0).toLowerCase()),s=typeof n==`string`?n.trim().toLowerCase():``,c=s===`2`||s===`2.0`||s===`h2`||s===`http/2`?`20`:s===`3`||s===`3.0`||s===`h3`||s===`http/3`?`30`:s===`1.0`||s===`http/1.0`?`10`:s===`1.1`||s===`http/1.1`?`11`:`00`,l=t.map(e=>e.toLowerCase()),u=l.includes(`cookie`)?`c`:`n`,d=l.includes(`referer`)?`r`:`n`,f=l.filter(e=>e!==`cookie`&&e!==`referer`),p=String(Math.min(f.length,99)).padStart(2,`0`),m=`0000`;i&&i.length>0&&(m=(i.split(`,`)[0]??``).replace(/[-;]/g,``).toLowerCase().trim().padEnd(4,`0`).substring(0,4));let h=`${o}${c}${u}${d}${p}${m}`,g=f.filter(e=>!e.startsWith(`:`)).toSorted(),_=g.length>0?Q(g.join(`,`)):`000000000000`,v=`000000000000`,y=`000000000000`;if(u===`c`&&r){let e=r.split(`;`).map(e=>e.trim()).filter(Boolean),t=e.map(e=>e.split(`=`)[0]?.trim()??``).filter(Boolean).toSorted();v=t.length>0?Q(t.join(`,`)):`000000000000`;let n=e.map(e=>{let t=e.indexOf(`=`);return{name:t>=0?e.substring(0,t).trim():e.trim(),pair:e}}).toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>e.pair);y=n.length>0?Q(n.join(`,`)):`000000000000`}return{http:`${h}_${_}_${v}_${y}`}}function Fn(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`1.0`||t===`http/1.0`)return`1.0`;if(t===`1.1`||t===`http/1.1`)return`1.1`;if(t===`2`||t===`2.0`||t===`http/2`||t===`h2`)return`h2`;if(t===`3`||t===`3.0`||t===`http/3`||t===`h3`)return`h3`}function In(e,t,n){let r=[],i=0;!e||e.length===0?(r.push(`missing-user-agent`),i+=.3):(/bot|crawler|spider|headless|selenium|puppeteer|playwright|phantom|curl|wget|python|java|go-http|httpclient|okhttp|requests\/|aiohttp|axios|node-fetch|undici/i.test(e)&&(r.push(`bot-ua: ${e.substring(0,40)}`),i+=.5),/headless/i.test(e)&&(r.push(`headless-browser`),i+=.4),e.length<30&&!/bot|curl|wget|python/i.test(e)&&(r.push(`suspiciously-short-ua`),i+=.2));let a=t.map(e=>e.toLowerCase());a.includes(`accept`)||(r.push(`missing-accept-header`),i+=.15),a.includes(`accept-language`)||(r.push(`missing-accept-language`),i+=.1),a.includes(`accept-encoding`)||(r.push(`missing-accept-encoding`),i+=.1);let o=t.length;o<4&&(r.push(`suspicious-few-headers: ${o}`),i+=.2),n&&(n.cipherCount<=2&&(r.push(`anomalous-cipher-count: ${n.cipherCount} (real browsers typically 5-15)`),i+=.3),n.extensionCount<5&&(r.push(`few-tls-extensions: ${n.extensionCount} (real browsers 10-25+)`),i+=.2),/\bTLS\s*1\.[01]\b|\b1\.0\b|\b1\.1\b|\bSSL/i.test(n.tlsVersion)&&(r.push(`outdated-tls-version: ${n.tlsVersion}`),i+=.25));let s=[`host`,`connection`,`cache-control`,`sec-ch-ua`,`sec-ch-ua-mobile`,`sec-ch-ua-platform`,`upgrade-insecure-requests`,`user-agent`,`accept`,`sec-fetch-site`,`sec-fetch-mode`,`sec-fetch-user`,`sec-fetch-dest`,`referer`,`accept-encoding`,`accept-language`];return a.length>=5&&a.slice(0,5).filter((e,t)=>e===s[t]).length===0&&(r.push(`header-order-does-not-match-known-browser`),i+=.1),{score:Math.min(i,1),signals:r}}var Ln=class{consoleMonitor;constructor(e){this.consoleMonitor=e.consoleMonitor}async handleNetworkTlsFingerprint(e){let t=e.mode,n=e.includeAnalysis!==!1,r=[`compute_tls`,`compute_http`,`analyze_request`];if(!t||!r.includes(t))return f.fail(`Invalid mode: "${t}". Expected one of: ${r.join(`, `)}`).json();try{if(t===`compute_tls`){let t=e.tlsVersions||[],r=e.ciphers||[],i=e.extensions||[],a=e.signatureAlgorithms||[],o=e.protocol===`quic`?`quic`:e.protocol===`dtls`?`dtls`:`tls`,s=e.sni!==!1,c=e.alpn||``;if(r.length===0)return f.fail(`ciphers array is required for compute_tls mode`).json();let l=t.map($).filter(e=>!Z(e)).toSorted(),u=l.length>0?l[l.length-1]:`0303`,{tls:d,tls_raw:p}=Nn({protocol:o,tlsVersion:u,hasSni:s,ciphers:r,extensions:i,signatureAlgorithms:a,alpn:c}),m={success:!0,mode:`tls`,tls:d,tls_raw:p};if(n){let e=r.map($).filter(e=>!Z(e)),t=i.map($).filter(e=>!Z(e));m.analysis={protocol:o.toUpperCase(),tlsVersion:u,sni:s,cipherCount:e.length,extensionCount:t.length,signatureAlgorithmCount:a.length,alpn:c||`(none)`,sortedCiphers:e.toSorted(),sortedExtensions:t.filter(e=>e!==`0000`&&e!==`0010`).toSorted()}}return f.ok().merge(m).json()}if(t===`compute_http`){let t=e.httpHeaders||[],r=e.userAgent||``,i=e.httpMethod||`GET`,a=e.httpVersion||`1.1`,o=e.cookieHeader||``,s=e.acceptLanguage||``;if(t.length===0)return f.fail(`httpHeaders array is required for compute_http mode`).json();let{http:c}=Pn(i,t,a,o,s),l={success:!0,mode:`http`,http:c};if(n){let e=t.map(e=>e.toLowerCase());l.analysis={method:i,httpVersion:a,headerCount:t.length,nonCookieRefererHeaders:e.filter(e=>e!==`cookie`&&e!==`referer`).length,hasCookie:e.includes(`cookie`),hasAcceptLanguage:e.includes(`accept-language`),sortedHeaders:e.filter(e=>e!==`cookie`&&e!==`referer`&&!e.startsWith(`:`)).toSorted(),userAgentLength:r.length}}return f.ok().merge(l).json()}let r=e.requestId;if(!r)return f.fail(`requestId is required for analyze_request mode`).json();let i=this.consoleMonitor.getNetworkRequests().find(e=>e.requestId===r);if(!i)return f.fail(`Request ${r} not found`).json();let a=i.headers||{},o=Object.keys(a),s=a[`user-agent`]||a[`User-Agent`]||``,c=i.method||`GET`,l=a.cookie||a.Cookie||``,u=a[`accept-language`]||a[`Accept-Language`]||``,d=Fn(i.httpVersion),{http:p}=Pn(c,o,d,l,u),m=i.securityDetails,h=m&&typeof m==`object`?{cipherCount:typeof m.cipherCount==`number`?m.cipherCount:5,extensionCount:typeof m.extensionCount==`number`?m.extensionCount:10,tlsVersion:typeof m.protocol==`string`?m.protocol:``}:void 0,g={success:!0,mode:`analyze_request`,requestId:r,url:i.url,method:c,httpVersion:d??`unknown`,http:p},_={requestId:r,url:i.url,method:c,httpVersion:d??`unknown`,http:p,headerCount:o.length,headerOrder:o.join(`, `),userAgent:s.length>80?s.substring(0,80)+`...`:s,securityHeaders:{hasCSP:void 0,hasHSTS:void 0,hasCORS:void 0},botSignals:In(s,o,h)};return n&&(g.analysis=_),f.ok().merge(g).json()}catch(e){return f.fail(e instanceof Error?e.message:String(e)).json()}}async handleNetworkBotDetectAnalyze(e){let t=typeof e.limit==`number`?e.limit:r,n=e.includeDetails===!0,i=this.consoleMonitor.getNetworkRequests(),a=i.slice(0,t);if(a.length===0)return f.ok().merge({analyzed:0,summary:`No captured requests to analyze. Enable network monitoring first.`}).json();let o=[],s=[],c=0,l=new Map,u=0,d=0,p=new Map,m=null;for(let e of a){let t=e.headers||{},r=Object.keys(t),i=t[`user-agent`]||t[`User-Agent`]||``,a=e.url||``,f=e.method||`GET`,h=t.cookie||t.Cookie||``,g=t[`accept-language`]||t[`Accept-Language`]||``,_=Fn(e.httpVersion),v=e.securityDetails,y=In(i,r,v&&typeof v==`object`?{cipherCount:typeof v.cipherCount==`number`?v.cipherCount:5,extensionCount:typeof v.extensionCount==`number`?v.extensionCount:10,tlsVersion:typeof v.protocol==`string`?v.protocol:``}:void 0),b=/\/api\/|\/v\d+\/|\/graphql/i.test(a),{http:x}=Pn(f,r,_,h,g);l.set(x,(l.get(x)??0)+1),p.has(x)?p.get(x)!==i&&u++:p.set(x,i),m===null?m=r.join(`,`):r.join(`,`)!==m&&d++;let S={requestId:e.requestId,url:a.length>100?a.substring(0,100)+`...`:a,method:f,http:x,botScore:y.score,signals:y.signals};c+=y.score,y.score>.5&&o.push(`Request ${e.requestId}: ${y.signals.join(`, `)}`),b&&(S.apiPattern=!0),n&&s.push(S)}let h=a.length>0?c/a.length:0,g=l.size,_=g/a.length,v=[];_>.8&&v.push(`High fingerprint diversity (${g} unique HTTP fingerprints in ${a.length} requests) — may indicate multiple clients or rotation`),_===1&&a.length>5&&v.push(`Every request has a unique HTTP fingerprint — likely automated tool rotating headers`);let y=[];u>0&&y.push(`${u} request(s) with different UA for same HTTP fingerprint — UA drift detected`),d>0&&y.push(`${d} request(s) with different header order — header rotation detected`);let b=a.length>1?Math.max(0,1-(u+d)/(a.length*2)):1;return f.ok().merge({analyzed:a.length,totalRequests:i.length,averageBotScore:Math.round(h*100)/100,suspiciousRequests:o.length,httpFingerprintSummary:{uniqueFingerprints:g,diversity:Math.round(_*100)/100,topFingerprints:[...l.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({http_fingerprint:e,count:t}))},signals:o.slice(0,20),...v.length>0?{diversitySignals:v}:{},interRequestConsistency:{consistencyScore:Math.round(b*100)/100,uaDriftCount:u,headerOrderDriftCount:d,...y.length>0?{signals:y}:{}},details:n?s:void 0,recommendations:h>.5?[`High bot-like signal detected. Consider TLS fingerprint rotation.`,`Review User-Agent consistency across requests.`,`Check header ordering matches real browser behavior.`,`HTTP fingerprint diversity can distinguish botnets from real users.`]:_>.8?[`Traffic appears human but fingerprint diversity is high — investigate further.`]:[`Traffic appears to follow normal browser patterns.`]}).json()}},Rn=class{collector;consoleMonitor;eventBus;performanceMonitor=null;detailedDataManager=s.getInstance();core;perf;consoleHandlers;replay;intercept;raw;tlsBot;constructor(e,t,n,r){this.collector=e,this.consoleMonitor=t,this.eventBus=n,this.core=new we({collector:e,consoleMonitor:t,eventBus:n}),this.perf=new Te({collector:e,getPerformanceMonitor:()=>this.getPerformanceMonitor(),getTraceRecorder:r}),this.consoleHandlers=new Ee({consoleMonitor:t}),this.replay=new Je({consoleMonitor:t}),this.intercept=new Xe({consoleMonitor:t,eventBus:n}),this.raw=new On(n),this.tlsBot=new Ln({consoleMonitor:t})}getPerformanceMonitor(){return this.performanceMonitor||=new c(this.collector),this.performanceMonitor}handleNetworkEnable=e=>this.core.handleNetworkEnable(e);handleNetworkDisable=e=>this.core.handleNetworkDisable(e);handleNetworkGetStatus=e=>this.core.handleNetworkGetStatus(e);handleNetworkMonitor=e=>this.core.handleNetworkMonitor(e);handleNetworkGetRequests=e=>this.core.handleNetworkGetRequests(e);handleNetworkGetResponseBody=e=>this.core.handleNetworkGetResponseBody(e);handleNetworkGetStats=e=>this.core.handleNetworkGetStats(e);handlePerformanceGetMetrics=e=>this.perf.handlePerformanceGetMetrics(e);handlePerformanceCoverage=e=>this.perf.handlePerformanceCoverage(e);handlePerformanceStartCoverage=e=>this.perf.handlePerformanceStartCoverage(e);handlePerformanceStopCoverage=e=>this.perf.handlePerformanceStopCoverage(e);handlePerformanceTakeHeapSnapshot=e=>this.perf.handlePerformanceTakeHeapSnapshot(e);handlePerformanceTraceStart=e=>this.perf.handlePerformanceTraceStart(e);handlePerformanceTraceStop=e=>this.perf.handlePerformanceTraceStop(e);handlePerformanceTraceDispatch=e=>String(e.action??``)===`stop`?this.perf.handlePerformanceTraceStop(e):this.perf.handlePerformanceTraceStart(e);handleProfilerCpuStart=e=>this.perf.handleProfilerCpuStart(e);handleProfilerCpuStop=e=>this.perf.handleProfilerCpuStop(e);handleProfilerCpuDispatch=e=>String(e.action??``)===`stop`?this.perf.handleProfilerCpuStop(e):this.perf.handleProfilerCpuStart(e);handleProfilerHeapSamplingStart=e=>this.perf.handleProfilerHeapSamplingStart(e);handleProfilerHeapSamplingStop=e=>this.perf.handleProfilerHeapSamplingStop(e);handleProfilerHeapSamplingDispatch=e=>String(e.action??``)===`stop`?this.perf.handleProfilerHeapSamplingStop(e):this.perf.handleProfilerHeapSamplingStart(e);handleConsoleGetExceptions=e=>this.consoleHandlers.handleConsoleGetExceptions(e);handleConsoleInjectDispatch=e=>{switch(String(e.type??``)){case`xhr`:return this.consoleHandlers.handleConsoleInjectXhrInterceptor(e);case`fetch`:return this.consoleHandlers.handleConsoleInjectFetchInterceptor(e);case`function`:return this.consoleHandlers.handleConsoleInjectFunctionTracer(e);default:return this.consoleHandlers.handleConsoleInjectScriptMonitor(e)}};handleConsoleBuffersDispatch=e=>String(e.action??``)===`reset`?this.consoleHandlers.handleConsoleResetInjectedInterceptors(e):this.consoleHandlers.handleConsoleClearInjectedBuffers(e);handleConsoleInjectScriptMonitor=e=>this.consoleHandlers.handleConsoleInjectScriptMonitor(e);handleConsoleInjectXhrInterceptor=e=>this.consoleHandlers.handleConsoleInjectXhrInterceptor(e);handleConsoleInjectFetchInterceptor=e=>this.consoleHandlers.handleConsoleInjectFetchInterceptor(e);handleConsoleClearInjectedBuffers=e=>this.consoleHandlers.handleConsoleClearInjectedBuffers(e);handleConsoleResetInjectedInterceptors=e=>this.consoleHandlers.handleConsoleResetInjectedInterceptors(e);handleConsoleInjectFunctionTracer=e=>this.consoleHandlers.handleConsoleInjectFunctionTracer(e);handleNetworkExtractAuth=e=>this.replay.handleNetworkExtractAuth(e);handleNetworkExportHar=e=>this.replay.handleNetworkExportHar(e);handleNetworkReplayRequest=e=>this.replay.handleNetworkReplayRequest(e);handleNetworkInterceptResponse=e=>this.intercept.handleNetworkInterceptResponse(e);handleNetworkInterceptList=e=>this.intercept.handleNetworkInterceptList(e);handleNetworkInterceptDisable=e=>this.intercept.handleNetworkInterceptDisable(e);handleNetworkInterceptDispatch=e=>{let t=String(e.action??``);switch(t){case`add`:return this.intercept.handleNetworkInterceptResponse(e);case`list`:return this.intercept.handleNetworkInterceptList(e);case`disable`:return this.intercept.handleNetworkInterceptDisable(e);default:return Promise.resolve({content:[{type:`text`,text:`Invalid action: "${t}". Expected one of: add, list, disable`}],isError:!0})}};handleNetworkTraceroute=e=>this.raw.handleNetworkTraceroute(e);handleNetworkIcmpProbe=e=>this.raw.handleNetworkIcmpProbe(e);handleDnsResolve=e=>this.raw.handleDnsResolve(e);handleDnsReverse=e=>this.raw.handleDnsReverse(e);handleDnsProbe=e=>this.raw.handleDnsProbe(e);handleDnsCnameChain=e=>this.raw.handleDnsCnameChain(e);handleDnsBulkResolve=e=>this.raw.handleDnsBulkResolve(e);handleHttpRequestBuild=e=>this.raw.handleHttpRequestBuild(e);handleHttpPlainRequest=e=>this.raw.handleHttpPlainRequest(e);handleHttp2Probe=e=>this.raw.handleHttp2Probe(e);handleHttp2FrameBuild=e=>this.raw.handleHttp2FrameBuild(e);handleNetworkRttMeasure=e=>this.raw.handleNetworkRttMeasure(e);handleNetworkLatencyStats=e=>this.raw.handleNetworkLatencyStats(e);handleNetworkTlsFingerprint=e=>this.tlsBot.handleNetworkTlsFingerprint(e);handleNetworkBotDetectAnalyze=e=>this.tlsBot.handleNetworkBotDetectAnalyze(e)};export{Rn as AdvancedToolHandlers};
@@ -1,2 +0,0 @@
1
- import{t as e}from"./search-defaults-lYBVn_3L.mjs";import{homedir as t}from"node:os";import{basename as n,dirname as r,extname as i,isAbsolute as a,join as o,normalize as s,relative as c,resolve as l,sep as u}from"node:path";import{z as d}from"zod";import{fileURLToPath as f}from"node:url";import{mkdir as p}from"node:fs/promises";import{config as m}from"dotenv";const h=f(new URL(`../..`,import.meta.url)),g=f(new URL(`../../.env`,import.meta.url));let _=!1;const v={puppeteer:{headless:!1,timeout:3e4},mcp:{name:`jshookmcp`,version:`0.1.8`},cache:{enabled:!1,dir:`.cache`,ttl:3600},paths:{screenshotDir:`screenshots`,captchaScreenshotDir:`screenshots/captcha`,debuggerSessionsDir:`debugger-sessions`,extensionRegistryDir:`artifacts/extension-registry`,tlsKeyLogDir:`artifacts/tmp`,registryCacheDir:`.jshookmcp/cache`},performance:{maxConcurrentAnalysis:3,maxCodeSizeMB:10}};function y(){if(_)return;_=!0;let e=m({path:g,quiet:!0}),t=e.error?.code;e.error&&t!==`ENOENT`?(console.error(`[Config] Warning: Failed to load .env file from configured path`),console.error(`[Config] Error: ${e.error.message}`),console.error(`[Config] Will use environment variables or defaults`)):!e.error&&process.env.DEBUG===`true`&&console.info(`[Config] .env file loaded (debug mode)`)}const b=e=>d.string().optional().transform(t=>t?parseInt(t,10):e).pipe(d.number().int().finite()),x=e=>d.string().optional().transform(t=>t===void 0?e:t===`true`);function S(e,t){return s(a(e)?e:l(t,e))}const C=d.object({PUPPETEER_HEADLESS:x(v.puppeteer.headless),PUPPETEER_TIMEOUT:b(v.puppeteer.timeout).pipe(d.number().min(1e3).max(3e5)),PUPPETEER_EXECUTABLE_PATH:d.string().optional(),CHROME_PATH:d.string().optional(),BROWSER_EXECUTABLE_PATH:d.string().optional(),MCP_SERVER_NAME:d.string().optional().default(v.mcp.name),MCP_SERVER_VERSION:d.string().optional().default(v.mcp.version),ENABLE_CACHE:x(v.cache.enabled),CACHE_DIR:d.string().optional().default(v.cache.dir),CACHE_TTL:b(v.cache.ttl).pipe(d.number().min(0)),MCP_SCREENSHOT_DIR:d.string().optional().default(v.paths.screenshotDir),CAPTCHA_SCREENSHOT_DIR:d.string().optional().default(v.paths.captchaScreenshotDir),MCP_DEBUGGER_SESSIONS_DIR:d.string().optional().default(v.paths.debuggerSessionsDir),MCP_EXTENSION_REGISTRY_DIR:d.string().optional().default(v.paths.extensionRegistryDir),MCP_TLS_KEYLOG_DIR:d.string().optional().default(v.paths.tlsKeyLogDir),MCP_REGISTRY_CACHE_DIR:d.string().optional().default(v.paths.registryCacheDir),MAX_CONCURRENT_ANALYSIS:b(v.performance.maxConcurrentAnalysis).pipe(d.number().min(1).max(32)),MAX_CODE_SIZE_MB:b(v.performance.maxCodeSizeMB).pipe(d.number().min(1).max(500))});function w(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T(e){let t=process.env[e];if(t)try{let e=JSON.parse(t);return Array.isArray(e)?e:void 0}catch{return}}function E(){let e=T(`SEARCH_QUERY_CATEGORY_PROFILES_JSON`);if(e!==void 0)return e.flatMap(e=>{if(!w(e)||typeof e.pattern!=`string`||!Array.isArray(e.domainBoosts))return[];let t=e.domainBoosts.flatMap(e=>!w(e)||typeof e.domain!=`string`||typeof e.weight!=`number`?[]:[{domain:e.domain,weight:e.weight}]);return[{pattern:e.pattern,flags:typeof e.flags==`string`?e.flags:void 0,domainBoosts:t}]})}function D(){let e=T(`SEARCH_CJK_QUERY_ALIASES_JSON`);if(e!==void 0)return e.flatMap(e=>{if(!w(e)||typeof e.pattern!=`string`||!Array.isArray(e.tokens))return[];let t=e.tokens.filter(e=>typeof e==`string`);return[{pattern:e.pattern,flags:typeof e.flags==`string`?e.flags:void 0,tokens:t}]})}function O(){let e=T(`SEARCH_INTENT_TOOL_BOOST_RULES_JSON`);if(e!==void 0)return e.flatMap(e=>{if(!w(e)||typeof e.pattern!=`string`||!Array.isArray(e.boosts))return[];let t=e.boosts.flatMap(e=>!w(e)||typeof e.tool!=`string`||typeof e.bonus!=`number`?[]:[{tool:e.tool,bonus:e.bonus}]);return[{pattern:e.pattern,flags:typeof e.flags==`string`?e.flags:void 0,boosts:t}]})}function k(e){return{queryCategoryProfiles:e.queryCategoryProfiles.map(e=>({pattern:e.pattern,flags:e.flags,domainBoosts:e.domainBoosts.map(e=>({domain:e.domain,weight:e.weight}))})),cjkQueryAliases:e.cjkQueryAliases.map(e=>({pattern:e.pattern,flags:e.flags,tokens:[...e.tokens]})),intentToolBoostRules:e.intentToolBoostRules.map(e=>({pattern:e.pattern,flags:e.flags,boosts:e.boosts.map(e=>({tool:e.tool,bonus:e.bonus}))}))}}function A(){let t=k(e);return{queryCategoryProfiles:E()??t.queryCategoryProfiles,cjkQueryAliases:D()??t.cjkQueryAliases,intentToolBoostRules:O()??t.intentToolBoostRules}}function j(e,t){return typeof e==`boolean`?e:typeof e==`string`?e===`true`:t}function M(e,t){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number.parseInt(e,10);if(Number.isFinite(t))return t}return t}function N(){y();let e=C.safeParse(process.env);if(!e.success){let t=e.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);console.error(`[Config] Validation errors:\n${t.join(`
2
- `)}`),console.error(`[Config] Falling back to safe defaults for invalid fields`)}let n=e.success?e.data:process.env,r=n.CACHE_DIR||v.cache.dir,i=n.PUPPETEER_EXECUTABLE_PATH||n.CHROME_PATH||n.BROWSER_EXECUTABLE_PATH,a=r.startsWith(`/`)||r.match(/^[A-Za-z]:/)?r:o(h,r),s=A(),c={screenshotDir:S(n.MCP_SCREENSHOT_DIR||v.paths.screenshotDir,h),captchaScreenshotDir:S(n.CAPTCHA_SCREENSHOT_DIR||v.paths.captchaScreenshotDir,h),debuggerSessionsDir:S(n.MCP_DEBUGGER_SESSIONS_DIR||v.paths.debuggerSessionsDir,process.cwd()),extensionRegistryDir:S(n.MCP_EXTENSION_REGISTRY_DIR||v.paths.extensionRegistryDir,h),tlsKeyLogDir:S(n.MCP_TLS_KEYLOG_DIR||v.paths.tlsKeyLogDir,h),registryCacheDir:S(n.MCP_REGISTRY_CACHE_DIR||v.paths.registryCacheDir,t())};return{puppeteer:{headless:j(n.PUPPETEER_HEADLESS,v.puppeteer.headless),timeout:M(n.PUPPETEER_TIMEOUT,v.puppeteer.timeout),executablePath:i?.trim()||void 0},mcp:{name:n.MCP_SERVER_NAME||v.mcp.name,version:n.MCP_SERVER_VERSION||v.mcp.version},cache:{enabled:j(n.ENABLE_CACHE,v.cache.enabled),dir:a,ttl:M(n.CACHE_TTL,v.cache.ttl)},paths:c,performance:{maxConcurrentAnalysis:M(n.MAX_CONCURRENT_ANALYSIS,v.performance.maxConcurrentAnalysis),maxCodeSizeMB:M(n.MAX_CODE_SIZE_MB,v.performance.maxCodeSizeMB)},search:s}}function P(e){let t=[];e.performance.maxConcurrentAnalysis<1&&t.push(`maxConcurrentAnalysis must be at least 1`),e.performance.maxCodeSizeMB<1&&t.push(`maxCodeSizeMB must be at least 1`),e.puppeteer.timeout<1e3&&t.push(`puppeteer.timeout must be at least 1000ms`),e.cache.ttl<0&&t.push(`cache.ttl must be non-negative`);for(let n of e.search.queryCategoryProfiles)try{new RegExp(n.pattern,n.flags)}catch{t.push(`search.queryCategoryProfiles contains invalid regex: ${n.pattern}`)}for(let n of e.search.cjkQueryAliases)try{new RegExp(n.pattern,n.flags)}catch{t.push(`search.cjkQueryAliases contains invalid regex: ${n.pattern}`)}for(let n of e.search.intentToolBoostRules)try{new RegExp(n.pattern,n.flags)}catch{t.push(`search.intentToolBoostRules contains invalid regex: ${n.pattern}`)}return{valid:t.length===0,errors:t}}const F=f(import.meta.url),I=F.includes(`/src/utils/`)||F.includes(`\\src\\utils\\`)?f(new URL(`../..`,import.meta.url)):f(new URL(`..`,import.meta.url));function L(e=process.env){let t=e.MCP_PROJECT_ROOT?.trim();return t?s(R(t)?t:l(I,t)):I}function R(e){return a(e)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function z(e,t){let n=c(e,t);return!(!n||n===`..`||n.startsWith(`..${u}`)||a(n))}function B(e,t=H()){let n=R(e)?s(e):l(t,e);return z(t,n)?n:l(t,`screenshots`,`external`,s(e).split(/[\\/]/).pop()||`output.bin`)}function V(e,t){return i(e)?e:`${e}.${t.replace(/^\./,``)}`}function H(){return L()}function U(e){let t=H(),n=e.trim();if(!n)throw Error(`path must be a non-empty relative path within the project root`);if(R(n))throw Error(`path must be relative to the project root`);let r=s(l(t,n));if(!z(t,r))throw Error(`path must stay within the project root`);return r}function W(e,t=`screenshots`){let n=H(),r=e?.trim();if(!r)return l(n,t);let i=B(r,n);return z(n,i)?i:l(n,t)}function G(){return N().paths.debuggerSessionsDir}function K(){return N().paths.extensionRegistryDir}function q(){return l(N().cache.dir,`code`)}function J(){return N().paths.tlsKeyLogDir}async function Y(e){let t=H(),i=e.type===`jpeg`?`jpg`:`png`,a=e.fallbackDir||`screenshots/manual`,o=e.fallbackName||`page`,s=W(N().paths.screenshotDir,a),u=e.requestedPath?.trim(),d,f=!1;if(!u)d=l(s,`${o}-${Date.now()}.${i}`),f=!0;else{let e=V(u,i);R(e)?(d=l(s,n(e)),f=!0):(d=l(t,e),z(t,d)||(d=l(s,n(d)),f=!0))}await p(r(d),{recursive:!0});let m=z(t,d)?c(t,d).replace(/\\/g,`/`):d.replace(/\\/g,`/`);return{absolutePath:d,displayPath:m,pathRewritten:f}}export{J as a,Y as c,P as d,H as i,N as l,G as n,W as o,K as r,U as s,q as t,h as u};
@@ -1,93 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{ri as t}from"./constants-BYj8Xek8.mjs";import{a as n,n as r}from"./response-C7rKQst4.mjs";import{i}from"./modules-BPBcSaM-.mjs";import{i as a}from"./artifacts-CkodUM4j.mjs";import{n as o}from"./ResponseBuilder-BfWP-uaT.mjs";import{n as s}from"./capabilities-CyXuKUl1.mjs";import{t as c}from"./ToolRegistry-C5oB8KP8.mjs";import"./definitions-B_83XfNQ.mjs";import{homedir as l}from"node:os";import{basename as u,dirname as d,extname as f,join as p,normalize as m,relative as h,resolve as g,sep as _}from"node:path";import{copyFile as v,mkdir as y,readFile as b,readdir as x,stat as S,writeFile as C}from"node:fs/promises";import{execFile as w,spawn as T}from"node:child_process";import{promisify as E}from"node:util";function D(e,t,i={}){return r({...n(t),tool:e,...i})}function O(e){return`attached`}function k(e,t,n=!1){let r=e[t];if(typeof r==`string`){let e=r.trim();if(e.length>0)return e}if(n)throw Error(`${t} must be a non-empty string`)}function A(e,t,n){let r=e[t];if(typeof r==`boolean`)return r;if(typeof r==`number`){if(r===1)return!0;if(r===0)return!1}if(typeof r==`string`){let e=r.trim().toLowerCase();if([`true`,`1`,`yes`,`on`].includes(e))return!0;if([`false`,`0`,`no`,`off`].includes(e))return!1}return n}function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function M(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)if(typeof n==`string`){let e=n.trim();e.length>0&&t.push(e)}return t}function N(e){let t=h(process.cwd(),e).replace(/\\/g,`/`);return t.length===0?`.`:t.startsWith(`..`)?e.replace(/\\/g,`/`):t}async function P(e){try{return await S(e),!0}catch{return!1}}function ee(){let e=process.env.USERPROFILE??l(),t=process.env.APPDATA??p(e,`AppData`,`Roaming`),n=[p(e,`Documents`),p(t)],r=[`Applet`,`XPlugin`,`MiniApp`],i=[];for(let e of n)for(let t of r)i.push(g(e,t));return Array.from(new Set(i))}async function F(t,n){let r=[g(t)];for(;r.length>0;){let t=r.pop();if(!t)continue;let i;try{i=await x(t,{withFileTypes:!0})}catch(n){e.debug(`walkDirectory skip unreadable directory`,{currentDir:t,error:n instanceof Error?n.message:String(n)});continue}for(let a of i){let i=p(t,String(a.name));if(a.isDirectory()){r.push(i);continue}if(a.isFile())try{await n(i,await S(i))}catch(t){e.warn(`walkDirectory skip unreadable file`,{absolutePath:i,error:t instanceof Error?t.message:String(t)})}}}}async function I(e,t,n){if(n){let e=g(n);return await y(e,{recursive:!0}),{absolutePath:e,displayPath:N(e)}}let{absolutePath:r,displayPath:i}=await a({category:`tmp`,toolName:e,target:t,ext:`tmpdir`}),o=r.replace(/\.tmpdir$/i,``);return await y(o,{recursive:!0}),{absolutePath:o,displayPath:i.replace(/\.tmpdir$/i,``)}}function L(e){return m(e.replace(/\\/g,`/`)).replace(/\\/g,`/`).split(`/`).filter(e=>e.length>0&&e!==`.`&&e!==`..`).join(`/`)}function R(e,t){let n=L(t),r=u(t)||`unnamed.bin`,i=g(e,n.length>0?n:r),a=g(e);if(i!==a&&!i.startsWith(`${a}${_}`))throw Error(`Path traversal blocked: ${t}`);return i}async function z(e){try{let t=await b(e,`utf-8`),n=JSON.parse(t);return j(n)?n:null}catch{return null}}function B(e){let t=e.replace(/\\/g,`/`);for(let e of[/\/([a-zA-Z]{2,4}[a-zA-Z0-9]{6,})\//,/\/Applet\/([^/]+)\//i]){let n=t.match(e);if(n?.[1])return n[1]}let n=u(e,f(e)).match(/([a-zA-Z]{2,4}[a-zA-Z0-9]{6,})/);return n?.[1]?n[1]:null}function te(e){if(e.length<18)throw Error(`Invalid miniapp package: file too small`);let t=e.readUInt8(0);if(t!==190)throw Error(`Invalid miniapp package magic: expected 0xBE, got 0x${t.toString(16)}`);let n=e.readUInt32BE(1),r=e.readUInt32BE(5),i=e.readUInt32BE(9),a=e.readUInt8(13),o=14+r;if(o>e.length)throw Error(`Invalid miniapp package: index section out of range`);let s=14;if(s+4>o)throw Error(`Invalid miniapp package: missing file count in index`);let c=e.readUInt32BE(s);s+=4;let l=[];for(let t=0;t<c;t+=1){if(s+4>o)throw Error(`Invalid miniapp package index at entry ${t}: missing nameLen`);let n=e.readUInt32BE(s);if(s+=4,n<=0||s+n>o)throw Error(`Invalid miniapp package index at entry ${t}: invalid nameLen`);let r=e.subarray(s,s+n).toString(`utf-8`);if(s+=n,s+8>o)throw Error(`Invalid miniapp package index at entry ${t}: missing offset/size`);let i=e.readUInt32BE(s);s+=4;let a=e.readUInt32BE(s);s+=4,l.push({name:r,offset:i,size:a})}return{magic:t,info:n,indexInfoLength:r,dataLength:i,lastIdent:a,dataOffset:o,entries:l}}async function ne(e,t,n){let r=(await e.probeAll())[`miniapp.unpacker`];if(!r?.available)return{used:!1,stderr:r?.reason??`外部解包工具 is unavailable`};let i=[[`unpack`,t,`-o`,n],[`unpack`,`-o`,n,t],[`-o`,n,t],[t,n]],a=`外部解包工具 failed for all argument patterns`;for(let r of i){let i=await e.run({tool:`miniapp.unpacker`,args:r,timeoutMs:18e4,cwd:d(t),expectedOutputPaths:[n],allowDirectoryOutputs:!0,outputLabel:`miniapp unpack output`});if(i.ok)return{used:!0,command:`unveilr ${r.join(` `)}`};a=i.stderr?.trim()||`exitCode=${String(i.exitCode)}`}return{used:!1,stderr:a}}var re=class{runner;collector;constructor(e,t){this.runner=e,this.collector=t}async handleMiniappPkgScan(e){try{let t=k(e,`searchPath`),n=t?[g(t)]:ee(),i=[],a=[];for(let e of n)try{(await S(e)).isDirectory()?i.push(e):a.push(e)}catch{a.push(e)}let o=[];for(let e of i)await F(e,async(e,t)=>{if(f(e).toLowerCase()===`.pkg`){try{let t=await import(`node:fs/promises`).then(t=>t.open(e,`r`));try{let e=Buffer.alloc(1);if(await t.read(e,0,1,0),e[0]!==190)return}finally{await t.close()}}catch{return}o.push({path:e.replace(/\\/g,`/`),size:Number(t.size),appId:B(e),lastModified:t.mtime.toISOString()})}});return o.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime()),r({success:!0,searchedRoots:i.map(e=>e.replace(/\\/g,`/`)),skippedRoots:a.map(e=>e.replace(/\\/g,`/`)),count:o.length,files:o,collectorState:O(this.collector)})}catch(e){return D(`miniapp_pkg_scan`,e)}}async handleMiniappPkgUnpack(t){try{let n=k(t,`inputPath`,!0),i=k(t,`outputDir`);if(!n)throw Error(`inputPath is required`);let a=g(n);if(!(await S(a)).isFile())throw Error(`inputPath must be a file`);let o=await I(`miniapp-unpack`,B(a)??u(a,f(a)),i);await y(o.absolutePath,{recursive:!0});let s=await ne(this.runner,a,o.absolutePath);if(s.used){let t=0;if(await F(o.absolutePath,async(e,n)=>{t+=1}),t>0)return r({success:!0,usedExternalCli:!0,cliCommand:s.command??null,outputDir:o.displayPath,extractedFiles:t,appId:B(a),collectorState:O(this.collector)});e.warn(`External unpack tool reported success but produced no output; falling back to parser`,{inputPath:a,outputDir:o.absolutePath})}let c=await b(a),l=te(c),p=[],m=0,h=0;for(let[e,t]of l.entries.entries()){let n=t.name.trim().length>0?t.name:`file-${e}.bin`;try{let e=t.offset,r=e+t.size;if(e<0||r>c.length){let n=l.dataOffset+t.offset,i=n+t.size;if(n>=0&&i<=c.length)e=n,r=i;else throw Error(`entry offset out of range`)}let i=c.subarray(e,r),a=R(o.absolutePath,n);await y(d(a),{recursive:!0}),await C(a,i),m+=1,h+=i.length}catch(e){p.push({path:n,reason:e instanceof Error?e.message:String(e)})}}return r({success:m>0,usedExternalCli:!1,cliError:s.stderr??null,outputDir:o.displayPath,appId:B(a),header:{magic:l.magic,info:l.info,indexInfoLength:l.indexInfoLength,dataLength:l.dataLength,lastIdent:l.lastIdent},fileCount:l.entries.length,extractedFiles:m,totalBytesExtracted:h,failedFiles:p,collectorState:O(this.collector)})}catch(e){return D(`miniapp_pkg_unpack`,e)}}async handleMiniappPkgAnalyze(e){try{let t=k(e,`unpackedDir`,!0);if(!t)throw Error(`unpackedDir is required`);let n=g(t);if(!(await S(n)).isDirectory())throw Error(`unpackedDir must be a directory`);let i=new Set,a=new Set,o=[],s=0,c,l,d;await F(n,async(e,t)=>{s+=Number(t.size);let r=h(n,e).replace(/\\/g,`/`),i=u(e).toLowerCase(),p=f(e).toLowerCase();i===`app.json`&&!c?c=e:i===`app-config.json`&&!l?l=e:i===`page-frame.html`&&!d&&(d=e),p===`.js`&&o.push(r),r.includes(`/components/`)&&[`.js`,`.wxml`,`.json`,`.wxss`].includes(p)&&a.add(r)});let p=[],m=null;if(c){let e=await z(c);if(e){for(let t of M(e.pages))i.add(t);let t=e.subPackages??e.subpackages;if(Array.isArray(t))for(let e of t){if(!j(e))continue;let t=typeof e.root==`string`?e.root.trim():``,n=M(e.pages);p.push({root:t,pages:n});for(let e of n)t.length>0?i.add(`${t}/${e}`):i.add(e)}let n=e.usingComponents;if(j(n))for(let e of Object.values(n))typeof e==`string`&&e.trim()&&a.add(e.trim());let r=typeof e.appId==`string`?e.appId:typeof e.appid==`string`?e.appid:null;r&&r.trim().length>0&&(m=r.trim())}}if(l){let e=await z(l);if(e){let t=typeof e.appId==`string`?e.appId:typeof e.appid==`string`?e.appid:null;t&&t.trim().length>0&&!m&&(m=t.trim());for(let t of M(e.pages))i.add(t)}}return m||=B(n),r({success:!0,unpackedDir:n.replace(/\\/g,`/`),pages:Array.from(i).toSorted(),subPackages:p,components:Array.from(a).toSorted(),jsFiles:o.toSorted(),totalSize:s,appId:m,discovered:{appJsonPath:c?N(c):null,appConfigPath:l?N(l):null,pageFramePath:d?N(d):null},collectorState:O(this.collector)})}catch(e){return D(`miniapp_pkg_analyze`,e)}}};function ie(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===0;)--t;return t===e.length?e:e.slice(0,t)}function ae(e){if(!j(e.files))return[];let t=[],n=(e,r)=>{for(let[i,a]of Object.entries(e)){if(!j(a))continue;let e=r.length>0?`${r}/${i}`:i;if(j(a.files)){n(a.files,e);continue}let o=a.size,s=a.offset,c=a.unpacked===!0,l=typeof o==`number`&&Number.isFinite(o)&&o>=0?o:0,u=0;if(typeof s==`number`||typeof s==`string`){let e=Number(s);Number.isFinite(e)&&e>=0&&(u=e)}t.push({path:L(e),size:l,offset:u,unpacked:c})}};return n(e.files,``),t}function oe(e,t,n){let r=e.filter(e=>!e.unpacked).slice(0,32);for(let e of r){let r=t+e.offset,i=r+e.size;if(r<0||i<r||i>n)return!1}return!0}function V(e){if(e.length<16)throw Error(`Invalid ASAR: file too small`);let t=e.readUInt32LE(0),n=e.readUInt32LE(4),r=e.readUInt32LE(8),i=e.readUInt32LE(12),a=Array.from(new Set([r,n,t-8,t])).filter(t=>t>0&&16+t<=e.length),o=null,s=0;for(let t of a){let n=ie(e.subarray(16,16+t).toString(`utf-8`)).trim();if(n.length!==0)try{let e=JSON.parse(n);if(j(e)){o=e,s=t;break}}catch{let e=n.lastIndexOf(`}`);if(e>0)try{let r=n.substring(0,e+1),i=JSON.parse(r);if(j(i)){o=i,s=t;break}}catch{}}}if(!o)throw Error(`Invalid ASAR: cannot parse header JSON`);let c=ae(j(o.files)?o:{files:o}),l=Array.from(new Set([16+s+i,8+t,16+r+i,16+n+i])).filter(t=>t>=0&&t<=e.length),u=l[0]??16+s;for(let t of l)if(oe(c,t,e.length)){u=t;break}return{files:c,dataOffset:u,headerSize:t,headerStringSize:n,headerContentSize:r,padding:i}}function se(e,t,n){let r=L(n);if(r.length===0)return;let i=t.files.find(e=>e.path===r)??t.files.find(e=>e.path.endsWith(`/${r}`));if(!i||i.unpacked)return;let a=t.dataOffset+i.offset,o=a+i.size;if(!(a<0||o>e.length||o<a))return e.subarray(a,o)}function H(e,t,n){let r=se(e,t,n);return r?r.toString(`utf-8`):void 0}function ce(e){let t=new Set,n=/preload\s*:\s*(?:path\.(?:join|resolve)\([^)]*?['"`]([^'"`]+)['"`][^)]*\)|['"`]([^'"`]+)['"`])/g,r=n.exec(e);for(;r;){let i=r[1]??r[2];i&&t.add(i.trim()),r=n.exec(e)}let i=e.match(/devTools\s*:\s*(true|false)/),a=null;return i?.[1]&&(a=i[1]===`true`),/\.openDevTools\s*\(/.test(e)&&(a=!0),{preloadScripts:Array.from(t),devToolsEnabled:a}}async function le(e){let t=new Set;return await F(e,async(e,n)=>{let r=u(e).toLowerCase();f(e).toLowerCase()===`.js`&&r.includes(`preload`)&&t.add(N(e))}),Array.from(t).toSorted().slice(0,100)}var ue=class{collector;constructor(e){this.collector=e}async handleAsarExtract(e){try{let t=k(e,`inputPath`,!0),n=k(e,`outputDir`),i=A(e,`listOnly`,!1);if(!t)throw Error(`inputPath is required`);let a=g(t);if(!(await S(a)).isFile())throw Error(`inputPath must be a file`);let o=await b(a),s=V(o),c=s.files.map(e=>({path:e.path,size:e.size,offset:e.offset})),l=c.reduce((e,t)=>e+t.size,0);if(i)return r({success:!0,files:c,totalFiles:c.length,totalSize:l,dataOffset:s.dataOffset,header:{headerSize:s.headerSize,headerStringSize:s.headerStringSize,headerContentSize:s.headerContentSize,padding:s.padding},collectorState:O(this.collector)});let p=await I(`asar-extract`,u(a,f(a)),n),m=0,h=[];for(let e of s.files){if(e.unpacked){h.push({path:e.path,reason:`Entry is marked as unpacked and not stored inside app.asar`});continue}let t=s.dataOffset+e.offset,n=t+e.size;if(t<0||n>o.length||n<t){h.push({path:e.path,reason:`Entry data range is out of bounds`});continue}try{let r=o.subarray(t,n),i=R(p.absolutePath,e.path);await y(d(i),{recursive:!0}),await C(i,r),m+=1}catch(t){h.push({path:e.path,reason:t instanceof Error?t.message:String(t)})}}return r({success:m>0,files:c,totalFiles:c.length,totalSize:l,extractedFiles:m,failedFiles:h,outputDir:p.displayPath,dataOffset:s.dataOffset,header:{headerSize:s.headerSize,headerStringSize:s.headerStringSize,headerContentSize:s.headerContentSize,padding:s.padding},collectorState:O(this.collector)})}catch(e){return D(`asar_extract`,e)}}async handleElectronInspectApp(t){try{let n=k(t,`appPath`,!0);if(!n)throw Error(`appPath is required`);let i=g(n),a=(await S(i)).isDirectory()?i:d(i),o=[p(a,`resources`,`app.asar`),p(a,`Contents`,`Resources`,`app.asar`),p(a,`app.asar`)],s=null;for(let e of o)if(await P(e)&&(await S(e)).isFile()){s=e;break}let c=null,l=null;if(s)try{c=await b(s),l=V(c)}catch(t){e.warn(`electron_inspect_app failed to parse asar`,{asarPath:s,error:t instanceof Error?t.message:String(t)}),c=null,l=null}let m=null,h=``,_=`none`;if(l&&c){let t=l.files.find(e=>e.path===`package.json`||e.path.endsWith(`/package.json`));if(t){let n=H(c,l,t.path);if(n)try{let e=JSON.parse(n);j(e)&&(m=e,h=t.path,_=`asar`)}catch(n){e.warn(`electron_inspect_app invalid package.json in asar`,{packagePath:t.path,error:n instanceof Error?n.message:String(n)})}}}if(!m){let e=[p(a,`package.json`),p(a,`app`,`package.json`),p(a,`resources`,`app`,`package.json`),p(a,`Contents`,`Resources`,`app`,`package.json`)];for(let t of e){let e=await z(t);if(e){m=e,h=t,_=`filesystem`;break}}}if(!m)return r({success:!1,tool:`electron_inspect_app`,error:`Cannot locate package.json in app directory or app.asar`,appPath:i.replace(/\\/g,`/`),scanRoot:a.replace(/\\/g,`/`),asarPath:s?s.replace(/\\/g,`/`):null,collectorState:O(this.collector)});let v=typeof m.main==`string`&&m.main.trim().length>0?m.main.trim():`index.js`,y=typeof m.version==`string`?m.version:null,x=m.dependencies,C=j(x)?Object.keys(x).toSorted():[],w=``,T=``;if(_===`asar`&&l&&c){let e=h.length>0?d(h):``,t=Array.from(new Set([L(p(e,v)),L(v),L(u(v))])).filter(e=>e.length>0);for(let e of t){let t=H(c,l,e);if(typeof t==`string`){w=t,T=e;break}}if(w.length===0){let e=l.files.find(e=>u(e.path)===u(v));if(e){let t=H(c,l,e.path);typeof t==`string`&&(w=t,T=e.path)}}}else if(_===`filesystem`){let t=g(d(h),v);if(await P(t)&&(await S(t)).isFile())try{w=await b(t,`utf-8`),T=t}catch(n){e.warn(`electron_inspect_app failed to read main script`,{absoluteMainPath:t,error:n instanceof Error?n.message:String(n)})}}let E=w.length>0?ce(w):{preloadScripts:[],devToolsEnabled:null},D=new Set(E.preloadScripts);if(D.size===0&&l)for(let e of l.files){let t=e.path.toLowerCase();t.includes(`preload`)&&f(t)===`.js`&&D.add(e.path)}if(D.size===0){let e=await le(a);for(let t of e)D.add(t)}let A=E.devToolsEnabled===null?!0:E.devToolsEnabled;return r({success:!0,appPath:i.replace(/\\/g,`/`),scanRoot:a.replace(/\\/g,`/`),mainEntry:v,version:y,preloadScripts:Array.from(D).toSorted(),dependencies:C,devToolsEnabled:A,packageSource:_,packagePath:_===`filesystem`?N(h):h,mainScriptPath:T.length>0?_===`filesystem`?N(T):T:null,asarPath:s?N(s):null,browserWindowDetected:w.length>0?w.includes(`BrowserWindow`):!1,collectorState:O(this.collector)})}catch(e){return D(`electron_inspect_app`,e)}}async handleAsarSearch(e){try{let t=k(e,`inputPath`,!0),n=k(e,`pattern`,!0);if(!t)throw Error(`inputPath is required`);if(!n)throw Error(`pattern is required`);let i=k(e,`fileGlob`)||`*.js`,a=typeof e.maxResults==`number`&&e.maxResults>0?e.maxResults:100,o=g(t);if(!await P(o))return r({success:!1,tool:`asar_search`,error:`File does not exist: ${t}`});let s=await b(o),c=V(s),l=i.startsWith(`*.`)?i.slice(1):null,u=c.files.filter(e=>e.unpacked||e.size<=0?!1:l?f(e.path).toLowerCase()===l.toLowerCase():!0),d;try{d=new RegExp(n,`gi`)}catch{return r({success:!1,tool:`asar_search`,error:`Invalid regex pattern: ${n}`})}let p=[],m=0,h=0;for(let e of u){if(m>=a)break;let t=c.dataOffset+e.offset,n=t+e.size;if(t<0||n>s.length||n<t||e.size>512e3)continue;let r=s.subarray(t,n).toString(`utf-8`);h++,d.lastIndex=0;let i=r.split(`
2
- `),o=[];for(let e=0;e<i.length&&!(m>=a);e++){let t=i[e];t&&(d.lastIndex=0,d.test(t)&&(o.push({lineNumber:e+1,text:t.slice(0,200)}),m++))}o.length>0&&p.push({filePath:e.path,matchCount:o.length,matchLines:o})}return r({success:!0,tool:`asar_search`,matches:p,totalMatches:m,filesScanned:h,pattern:n})}catch(e){return D(`asar_search`,e)}}};async function de(e){return o(async()=>{let t=k(e,`dirPath`,!0);if(!t)throw Error(`dirPath is required`);let n=typeof e.maxFiles==`number`&&e.maxFiles>0?e.maxFiles:20,r=(typeof e.maxFileSizeKB==`number`&&e.maxFileSizeKB>0?e.maxFileSizeKB:1024)*1024;if(!await P(t))return{success:!1,error:`Directory does not exist: ${t}`};if(!(await S(t)).isDirectory())return{success:!1,error:`Path is not a directory: ${t}`};let i;try{i=await x(t)}catch{return{success:!1,error:`Cannot read directory: ${t}`}}let a=i.filter(e=>e.endsWith(`.json`)).slice(0,n),o=[],s=[];for(let e of a){let n=p(t,e);try{let t=await S(n);if(!t.isFile()){s.push({name:e,reason:`not a file`});continue}if(t.size>r){s.push({name:e,reason:`exceeds maxFileSizeKB`});continue}let i=await b(n,`utf-8`),a=JSON.parse(i);o.push({name:e,sizeBytes:t.size,content:a})}catch{s.push({name:e,reason:`read or parse error`})}}return{files:o,skipped:s,totalScanned:a.length,directory:t}})}const U=`dL7pKGdnNz796PbbjQWNKmHXBZIA`,W=[`RunAsNode`,`EnableCookieEncryption`,`EnableNodeOptionsEnvironmentVariable`,`EnableNodeCliInspectArguments`,`EnableEmbeddedAsarIntegrityValidation`,`OnlyLoadAppFromAsar`,`LoadBrowserProcessSpecificV8Snapshot`,`GrantFileProtocolExtraPrivileges`],G={48:`DISABLE`,49:`ENABLE`,114:`REMOVED`},fe={RunAsNode:`ENABLE`,EnableNodeOptionsEnvironmentVariable:`ENABLE`,EnableNodeCliInspectArguments:`ENABLE`,OnlyLoadAppFromAsar:`DISABLE`};function K(e,t){let n=t+Buffer.from(U,`ascii`).length,r={};for(let t=0;t<W.length;t++){let i=W[t];if(!i)continue;let a=n+t;if(a>=e.length){r[i]=`UNKNOWN`;continue}let o=e[a];if(o===void 0){r[i]=`UNKNOWN`;continue}r[i]=G[o]??`UNKNOWN`}return r}async function pe(e){return o(async()=>{let t=k(e,`exePath`,!0);if(!t)throw Error(`exePath is required`);if(!await P(t))return{success:!1,error:`File does not exist: ${t}`};let n=await b(t),r=Buffer.from(U,`ascii`),i=n.indexOf(r);return i===-1?{exePath:t,fuseWireFound:!1,fuses:{},note:`No fuse sentinel found. This may not be an Electron binary, or fuses are not configured.`}:{exePath:t,fuseWireFound:!0,fuses:K(n,i)}})}async function me(e){return o(async()=>{let t=k(e,`exePath`,!0);if(!t)throw Error(`exePath is required`);if(!await P(t))return{success:!1,error:`File does not exist: ${t}`};let n=k(e,`profile`)??`debug`,r=e.createBackup!==!1,i;if(n===`debug`)i={...fe};else if(n===`custom`){let t=e.fuses;if(!t||Object.keys(t).length===0)throw Error('profile="custom" requires a `fuses` object mapping fuse names to ENABLE/DISABLE');i={};for(let[e,n]of Object.entries(t)){if(!W.includes(e))throw Error(`Unknown fuse: ${e}. Valid: ${W.join(`, `)}`);if(n!==`ENABLE`&&n!==`DISABLE`)throw Error(`Invalid fuse value for ${e}: ${n}. Must be ENABLE or DISABLE`);i[e]=n}}else throw Error(`Unknown profile: ${n}. Use "debug" or "custom"`);let a=await b(t),o=Buffer.from(U,`ascii`),s=a.indexOf(o);if(s===-1)return{success:!1,error:`No fuse sentinel found. This may not be an Electron binary.`,exePath:t};let c=K(a,s),l=s+o.length,u=[];for(let[e,t]of Object.entries(i)){let n=W.indexOf(e);if(n===-1)continue;let r=l+n;if(r>=a.length)continue;let i=a[r];if(i===114){u.push({fuse:e,before:`REMOVED`,after:`REMOVED (cannot patch)`});continue}let o=t===`ENABLE`?49:48,s=G[i??0]??`UNKNOWN`;i!==o&&(a[r]=o,u.push({fuse:e,before:s,after:t}))}if(u.length===0)return{exePath:t,message:`All target fuses are already in the desired state. No changes needed.`,fuses:c};let d=null;r&&(d=`${t}.bak`,await v(t,d)),await C(t,a);let f=K(a,s);return{exePath:t,backupPath:d,profile:n,changes:u,fusesBefore:c,fusesAfter:f,note:d?`Backup created at ${d}. Restore with: copy "${d}" "${t}"`:`No backup created (createBackup=false).`}})}const q=E(w),he=Buffer.from([192,222]),ge=Buffer.from(`BYTN`),_e=new Set([`.jsc`,`.bin`]);function ve(e,t){let n=f(t).toLowerCase();if(e.length>=4&&e.subarray(0,4).equals(ge))return`bytenode`;if(e.length>=2&&e.subarray(0,2).equals(he))return`v8-raw`;if(_e.has(n))return`jsc-extension`;let r=[Buffer.from(`Ldar`),Buffer.from(`Star`),Buffer.from(`LdaSmi`),Buffer.from(`CallRuntime`)];for(let t of r)if(e.indexOf(t)!==-1)return`v8-heuristic`;return null}async function ye(e){try{let{stdout:n,stderr:r}=await q(`python`,[`-m`,`view8`,e],{timeout:t,maxBuffer:10*1024*1024});return n&&n.trim().length>0?{ok:!0,output:n}:{ok:!1,error:r||`Empty output from view8`}}catch{try{let{stdout:n}=await q(`python3`,[`-m`,`view8`,e],{timeout:t,maxBuffer:10*1024*1024});return n&&n.trim().length>0?{ok:!0,output:n}:{ok:!1,error:`Empty output from view8`}}catch{return{ok:!1,error:`view8 not available. Install with: pip install view8`}}}}async function J(e){try{return await q(e,[`-c`,`import view8; print(getattr(view8, "__file__", "view8"))`],{timeout:t,maxBuffer:1024*1024}),{available:!0,interpreter:e}}catch(t){return{available:!1,interpreter:e,reason:t instanceof Error?t.message:String(t)}}}async function be(){let e=await J(`python`);if(e.available)return e;let t=await J(`python3`);return t.available?t:{available:!1,reason:e.reason&&t.reason?`${e.reason}; ${t.reason}`:e.reason??t.reason??`view8 is not available`}}function xe(e){let t=[],n=[],r=new Set,i=2e3,a=``;for(let n=0;n<e.length;n++){let o=e[n];o>=32&&o<=126?a+=String.fromCharCode(o):(a.length>=4&&a.length<=i&&Y(a)&&!r.has(a)&&(r.add(a),t.push(a)),a=``)}for(let n=0;n<e.length-3;n++)if(e[n+1]===0&&e[n]>=32&&e[n]<=126){let a=``,o=n;for(;o<e.length-1&&e[o]>=32&&e[o]<=126&&e[o+1]===0;)a+=String.fromCharCode(e[o]),o+=2;a.length>=4&&a.length<=i&&Y(a)&&!r.has(a)&&(r.add(a),t.push(a))}return{strings:t,numbers:n}}function Y(e){return new Set(e).size<=2||(e.match(/[^a-zA-Z0-9_\-.\s/\\:;=+*&|!?,'"(){}[\]<>@#$%^~`]/g)??[]).length/e.length>.3?!1:[/[a-zA-Z_$][a-zA-Z0-9_$]*/,/function\s/,/return\s/,/const\s/,/let\s/,/var\s/,/require\(/,/module\.exports/,/import\s/,/\.prototype\./,/\.call\(/,/\.apply\(/,/async\s/,/await\s/,/Promise/,/https?:\/\//,/[a-zA-Z]+Error/].some(t=>t.test(e))}async function Se(e){return o(async()=>{let t=k(e,`filePath`,!0);if(!t)throw Error(`filePath is required — path to a .jsc or V8 bytecode file`);if(!await P(t))return{success:!1,error:`File does not exist: ${t}`};let n=await S(t);if(n.size>50*1024*1024)return{success:!1,error:`File too large (${(n.size/1024/1024).toFixed(1)}MB). Maximum: 50MB.`};let r=await b(t),i=ve(r,t);if(!i)return{success:!1,filePath:t,fileSize:n.size,error:`Not a recognized V8 bytecode format. Expected .jsc, bytenode, or V8 serialized bytecode.`,hint:`Ensure the file is a V8 compiled bytecode file (created by bytenode or v8.serialize).`};let a={success:!1,tool:`v8_bytecode_decompile`,filePath:t,fileSize:n.size,detectedFormat:i,strategy:`pending`},o=await ye(t);if(o.ok&&o.output)return a.success=!0,a.strategy=`view8`,a.pseudocode=o.output.length>5e4?o.output.slice(0,5e4)+`
3
-
4
- ... [truncated, total `+o.output.length+` chars]`:o.output,a;let{strings:s}=xe(r);return s.length>0?(a.success=!0,a.strategy=`constant-pool-extraction`,a.strings=s.slice(0,500),a.note=[`view8 unavailable (${o.error}). Used built-in constant pool extraction.`,`Found ${s.length} code-relevant strings. These include function names, identifiers, URLs, and string literals from the original source.`,`For full decompilation, install view8: pip install view8`].join(` `)):(a.success=!1,a.strategy=`none`,a.error=`Could not decompile. view8: ${o.error}. Built-in extraction found no code strings.`,a.note=`The bytecode may be heavily optimized or use an unsupported V8 version.`),a})}const X=new Map;async function Ce(e){try{let t=await b(e),n=Buffer.from(`dL7pKGdnNz796PbbjQWNKmHXBZIA`,`ascii`),r=t.indexOf(n);if(r===-1)return{fuseFound:!1,runAsNode:!1,inspectArgs:!1,nodeOptions:!1};let i=r+n.length;return{fuseFound:!0,runAsNode:t[i]===49,nodeOptions:t[i+2]===49,inspectArgs:t[i+3]===49}}catch{return{fuseFound:!1,runAsNode:!1,inspectArgs:!1,nodeOptions:!1}}}async function Z(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){try{let t=await fetch(`http://127.0.0.1:${e}/json/version`,{signal:AbortSignal.timeout(2e3)});if(t.ok)return{ok:!0,info:await t.text()}}catch{}await new Promise(e=>setTimeout(e,500))}return{ok:!1,error:`CDP port ${e} did not respond within ${t}ms`}}async function we(e){return o(async()=>{let t=k(e,`exePath`,!0);if(!t)throw Error(`exePath is required — path to the Electron .exe`);if(!await P(t))return{success:!1,error:`File does not exist: ${t}`};let n=t.split(/[\\/]/).pop()?.toLowerCase()??``;if(![/^electron/i,/\.app$/i,/chrome/i,/chromium/i].some(e=>e.test(n)))return{success:!1,error:`exePath does not appear to be an Electron binary: ${n}. Only Electron/Chromium executables are allowed.`};let r=e.mainPort??9229,i=e.rendererPort??9222,a=e.args??[],o=[`--require`,`--loader`,`--import`,`-e`,`--eval`,`-p`,`--print`],s=a.filter(e=>!o.some(t=>e===t||e.startsWith(`${t}=`))),c=e.skipFuseCheck===!0,l=e.waitMs??8e3,u=[];if(!c){let e=await Ce(t);e.fuseFound&&(e.inspectArgs||u.push(`EnableNodeCliInspectArguments is DISABLED — main process --inspect may be blocked. Use electron_patch_fuses first.`),e.nodeOptions||u.push(`EnableNodeOptionsEnvironmentVariable is DISABLED — NODE_OPTIONS injection blocked.`),e.runAsNode||u.push(`RunAsNode is DISABLED — ELECTRON_RUN_AS_NODE=1 will not work.`))}let d=T(t,[`--inspect=${r}`,`--remote-debugging-port=${i}`,...s],{stdio:`ignore`,detached:!0,env:{...process.env}});if(d.unref(),!d.pid)return{success:!1,error:`Failed to spawn process — no PID returned.`};let f=`electron-${d.pid}`;X.set(f,{child:d,pid:d.pid,ports:{main:r,renderer:i}});let[p,m]=await Promise.all([Z(r,l),Z(i,l)]);return{sessionId:f,pid:d.pid,ports:{main:{port:r,available:p.ok,info:p.ok?`Ready`:p.error},renderer:{port:i,available:m.ok,info:m.ok?`Ready`:m.error}},fuseWarnings:u.length>0?u:void 0,usage:{main:`Use electron_attach(port=${r}) to debug the main process (Node.js)`,renderer:`Use electron_attach(port=${i}) to debug the renderer (Chromium)`,combined:`Both sessions can be used simultaneously for cross-process analysis`}}})}async function Te(e){return o(async()=>{let t=k(e,`sessionId`);if(t){let e=X.get(t);if(!e)return{success:!1,error:`No session found: ${t}`,activeSessions:Array.from(X.keys())};let[n,r]=await Promise.all([Z(e.ports.main,2e3),Z(e.ports.renderer,2e3)]);return{sessionId:t,pid:e.pid,main:{port:e.ports.main,alive:n.ok},renderer:{port:e.ports.renderer,alive:r.ok}}}return{sessions:Array.from(X.entries()).map(([e,t])=>({sessionId:e,pid:t.pid,ports:t.ports}))}})}const Q=new Map;function Ee(){return typeof globalThis.WebSocket==`function`?{available:!0}:{available:!1,reason:`Global WebSocket is not available in this Node runtime.`,fix:`Use Node.js 21+ or provide a WebSocket-compatible runtime.`}}async function $(e,t){let n=e.match(/ws:\/\/([\d.]+:\d+)\//);if(!n?.[1])return{ok:!1,error:`Invalid wsDebuggerUrl: ${e}`};let r=n[1];try{let e=(await(await fetch(`http://${r}/json`,{signal:AbortSignal.timeout(5e3)})).json()).find(e=>e.type===`page`);if(!e)return{ok:!1,error:`No page target found`};let n=e.webSocketDebuggerUrl;return n?await De(n,t):{ok:!1,error:`Page target has no WebSocket debugger URL`}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function De(e,t){return new Promise(n=>{try{let r=Ee();if(!r.available){n({ok:!1,error:`${r.reason} ${r.fix??``}`.trim()});return}let i=globalThis.WebSocket,a=new i(e),o=setTimeout(()=>{try{a.close()}catch{}n({ok:!1,error:`CDP WebSocket timeout (10s)`})},1e4);a.addEventListener(`open`,()=>{a.send(JSON.stringify({id:1,method:`Runtime.evaluate`,params:{expression:t,returnByValue:!0,awaitPromise:!1}}))}),a.addEventListener(`message`,e=>{clearTimeout(o);try{let t=JSON.parse(String(e.data));t.result?.exceptionDetails?n({ok:!1,error:t.result.exceptionDetails.text}):n({ok:!0,result:String(t.result?.result?.value??``)})}catch(e){n({ok:!1,error:`Parse error: ${e}`})}try{a.close()}catch{}}),a.addEventListener(`error`,e=>{clearTimeout(o),n({ok:!1,error:`WebSocket error: ${e}`})})}catch(e){n({ok:!1,error:e instanceof Error?e.message:String(e)})}})}async function Oe(e){return o(async()=>{let t=k(e,`action`)??`guide`;if(t===`start`){let t=e.port??9222,n=`ipc-sniff-${t}-${Date.now()}`,r;try{r=(await(await fetch(`http://127.0.0.1:${t}/json/version`,{signal:AbortSignal.timeout(5e3)})).json()).webSocketDebuggerUrl??`ws://127.0.0.1:${t}/devtools/browser`}catch{return{success:!1,error:`Cannot connect to CDP at port ${t}. Ensure Electron is launched with --remote-debugging-port=${t}.`,hint:`Use electron_launch_debug to start the app with CDP enabled.`}}let i=await $(r,`
5
- (function() {
6
- if (window.__ipcSnifferInstalled) return 'already_installed';
7
-
8
- const captured = [];
9
- window.__ipcSnifferCaptured = captured;
10
- window.__ipcSnifferInstalled = true;
11
-
12
- // Try to access ipcRenderer from contextBridge-exposed API or require
13
- let ipcRenderer = null;
14
-
15
- // Method 1: Direct require (works if nodeIntegration is enabled)
16
- try {
17
- ipcRenderer = require('electron').ipcRenderer;
18
- } catch(e) {}
19
-
20
- // Method 2: window.electron (common contextBridge pattern)
21
- if (!ipcRenderer && window.electron && window.electron.ipcRenderer) {
22
- ipcRenderer = window.electron.ipcRenderer;
23
- }
24
-
25
- if (!ipcRenderer) {
26
- return 'ipcRenderer_not_accessible';
27
- }
28
-
29
- // Hook invoke
30
- const origInvoke = ipcRenderer.invoke.bind(ipcRenderer);
31
- ipcRenderer.invoke = function(channel, ...args) {
32
- captured.push({
33
- timestamp: Date.now(),
34
- method: 'invoke',
35
- channel: channel,
36
- args: args.map(a => {
37
- try { return JSON.parse(JSON.stringify(a)); }
38
- catch { return String(a); }
39
- })
40
- });
41
- return origInvoke(channel, ...args);
42
- };
43
-
44
- // Hook send
45
- const origSend = ipcRenderer.send.bind(ipcRenderer);
46
- ipcRenderer.send = function(channel, ...args) {
47
- captured.push({
48
- timestamp: Date.now(),
49
- method: 'send',
50
- channel: channel,
51
- args: args.map(a => {
52
- try { return JSON.parse(JSON.stringify(a)); }
53
- catch { return String(a); }
54
- })
55
- });
56
- return origSend(channel, ...args);
57
- };
58
-
59
- // Hook sendSync
60
- if (ipcRenderer.sendSync) {
61
- const origSendSync = ipcRenderer.sendSync.bind(ipcRenderer);
62
- ipcRenderer.sendSync = function(channel, ...args) {
63
- captured.push({
64
- timestamp: Date.now(),
65
- method: 'sendSync',
66
- channel: channel,
67
- args: args.map(a => {
68
- try { return JSON.parse(JSON.stringify(a)); }
69
- catch { return String(a); }
70
- })
71
- });
72
- return origSendSync(channel, ...args);
73
- };
74
- }
75
-
76
- return 'hooks_installed';
77
- })();
78
- `);if(!i.ok)return{success:!1,error:`Failed to inject IPC hooks: ${i.error}`,hint:`The renderer may have contextIsolation enabled. Try injecting via main process CDP instead.`};let a={id:n,port:t,wsUrl:r,messages:[],startedAt:Date.now(),active:!0};return Q.set(n,a),{action:`start`,sessionId:n,port:t,hookStatus:i.result,usage:{dump:`electron_ipc_sniff(action="dump", sessionId="${n}")`,stop:`electron_ipc_sniff(action="stop", sessionId="${n}")`},note:i.result===`ipcRenderer_not_accessible`?`ipcRenderer not accessible — contextIsolation may be enabled. IPC hooking requires nodeIntegration or a custom preload.`:`IPC hooks installed. Interact with the app, then use dump to retrieve captured messages.`}}if(t===`dump`){let t=k(e,`sessionId`),n=e.port,r=e.clear!==!1,i;if(t)i=Q.get(t);else if(n)i=Array.from(Q.values()).find(e=>e.port===n);else{let e=Array.from(Q.values());i=e[e.length-1]}if(!i)return{success:!1,error:`No active IPC sniff session found.`,activeSessions:Array.from(Q.keys()),hint:`Start a session first: electron_ipc_sniff(action="start", port=9222)`};let a=await $(i.wsUrl,`
79
- (function() {
80
- const captured = window.__ipcSnifferCaptured || [];
81
- const result = JSON.stringify(captured);
82
- return result;
83
- })();
84
- `);if(!a.ok)return{success:!1,error:`Failed to dump IPC messages: ${a.error}`};let o=[];try{o=JSON.parse(a.result??`[]`)}catch{o=[]}r&&o.length>0&&await $(i.wsUrl,`
85
- (function() {
86
- if (window.__ipcSnifferCaptured) {
87
- const count = window.__ipcSnifferCaptured.length;
88
- window.__ipcSnifferCaptured.length = 0;
89
- return String(count);
90
- }
91
- return '0';
92
- })();
93
- `);let s={};for(let e of o)s[e.channel]=(s[e.channel]??0)+1;return{action:`dump`,sessionId:i.id,messageCount:o.length,channelSummary:s,messages:o.slice(0,200),cleared:r,note:o.length>200?`Showing first 200 of ${o.length} messages. Use dump repeatedly for ongoing capture.`:void 0}}if(t===`stop`){let t=k(e,`sessionId`);if(!t)return{success:!1,error:`sessionId is required for stop.`,activeSessions:Array.from(Q.keys())};let n=Q.get(t);return n?(n.active=!1,Q.delete(t),{action:`stop`,sessionId:t,message:`IPC sniff session stopped.`,uptime:Math.round((Date.now()-n.startedAt)/1e3)}):{success:!1,error:`Session not found: ${t}`}}if(t===`list`){let e=Array.from(Q.entries()).map(([e,t])=>({sessionId:e,port:t.port,active:t.active,uptime:Math.round((Date.now()-t.startedAt)/1e3)}));return{action:`list`,sessions:e,count:e.length}}return{guide:{what:`Electron IPC sniffer — intercepts ipcRenderer.invoke/send/sendSync messages via CDP injection.`,workflow:[`1. Launch Electron with: electron_launch_debug(exePath="...")`,`2. Start sniffing: electron_ipc_sniff(action="start", port=9222)`,`3. Interact with the app to trigger IPC messages`,`4. Dump captured: electron_ipc_sniff(action="dump", sessionId="...")`,`5. Stop when done: electron_ipc_sniff(action="stop", sessionId="...")`],actions:[`start`,`dump`,`stop`,`list`,`guide`],limitations:[`Requires renderer CDP port (--remote-debugging-port)`,`contextIsolation=true may block direct ipcRenderer access`,`Main process IPC (ipcMain) is captured indirectly through renderer-side hooks`]}}})}async function ke(e){let t=(await e.probeAll())[`miniapp.unpacker`],n=await be()??{available:!1,reason:`view8 probe returned no result`},i=Ee()??{available:!1,reason:`IPC runtime probe returned no result`};return r(s(`platform_capabilities`,[{capability:`miniapp_unpacker`,status:t?.available?`available`:`unavailable`,reason:t?.reason,fix:t?.available?void 0:`Install unveilr to enable the fast external unpack path.`,details:{tools:[`miniapp_pkg_unpack`],fallback:`Built-in Node.js parser remains available.`,...t?.path?{path:t.path}:{},...t?.version?{version:t.version}:{}}},{capability:`view8`,status:n.available?`available`:`unavailable`,reason:n.reason,fix:n.available?void 0:`Install view8 with pip install view8 to enable full bytecode decompilation.`,details:{tools:[`v8_bytecode_decompile`],fallback:`Built-in constant-pool extraction remains available.`,...n.interpreter?{interpreter:n.interpreter}:{}}},{capability:`electron_ipc_sniff_runtime`,status:i.available?`available`:`unavailable`,reason:i.reason,fix:i.fix,details:{tools:[`electron_ipc_sniff`],note:`A renderer CDP port is still required at call time.`}}]))}var Ae=class{miniapp;electron;runner;constructor(e){let t=new c;this.runner=new i(t),this.miniapp=new re(this.runner,e),this.electron=new ue(e)}handlePlatformCapabilities(){return ke(this.runner)}handleMiniappPkgScan(e){return this.miniapp.handleMiniappPkgScan(e)}handleMiniappPkgUnpack(e){return this.miniapp.handleMiniappPkgUnpack(e)}handleMiniappPkgAnalyze(e){return this.miniapp.handleMiniappPkgAnalyze(e)}handleAsarExtract(e){return this.electron.handleAsarExtract(e)}handleElectronInspectApp(e){return this.electron.handleElectronInspectApp(e)}handleElectronScanUserdata(e){return de(e)}handleAsarSearch(e){return this.electron.handleAsarSearch(e)}handleElectronCheckFuses(e){return pe(e)}handleElectronPatchFuses(e){return me(e)}handleV8BytecodeDecompile(e){return Se(e)}handleElectronLaunchDebug(e){return we(e)}handleElectronDebugStatus(e){return Te(e)}handleElectronIPCSniff(e){return Oe(e)}};export{Ae as PlatformToolHandlers};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{createRequire as t}from"node:module";import{dirname as n,join as r}from"node:path";let i=!1;function a(){let e=n(t(import.meta.url).resolve(`playwright-core/package.json`));return{playwrightServerPath:r(e,`lib/server/playwright.js`),crBrowserPath:r(e,`lib/server/chromium/crBrowser.js`)}}function o(){if(i)return;let n=t(import.meta.url),{playwrightServerPath:r,crBrowserPath:o}=a(),{createPlaywright:s}=n(r);s({sdkLanguage:`javascript`,isInternalPlaywright:!0});let{CRBrowserContext:c}=n(o);if(c.prototype.__jshookElectronCompatPatched){i=!0;return}let l=c.prototype.initialize;c.prototype.initialize=async function(...t){try{return await l.apply(this,t)}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes(`Browser.setDownloadBehavior`)&&n.includes(`Browser context management is not supported`)){e.warn(`[playwright-cdp-fallback] Swallowed Browser.setDownloadBehavior for legacy Electron CDP endpoint.`);return}throw t}},Object.defineProperty(c.prototype,`__jshookElectronCompatPatched`,{value:!0,configurable:!1,enumerable:!1,writable:!1}),i=!0}function s(e){return e}function c(e){return e===`networkidle0`||e===`networkidle2`?`networkidle`:e}function l(e){let t=e.contexts()[0];if(!t)throw Error(`Connected Playwright CDP browser exposes no default context. Cannot create or resolve pages.`);return t}function u(t,n){let r=n.get(t);if(r)return r;let i=new Proxy({async goto(e,n){return await t.goto(e,{...n,waitUntil:c(n?.waitUntil)})},async reload(e){return await t.reload({...e,waitUntil:c(e?.waitUntil)})},async waitForNavigation(e){let n=c(e?.waitUntil);return typeof t.waitForNavigation==`function`?await t.waitForNavigation({...e,waitUntil:n}):await t.waitForLoadState(n??`load`,{timeout:e?.timeout})},async select(e,...n){return await t.selectOption(e,n)},async evaluateOnNewDocument(e,...n){return await t.addInitScript(e,...n)},async createCDPSession(){let e=t.context();if(typeof e.newCDPSession!=`function`)throw Error(`Playwright BrowserContext does not expose newCDPSession() for the attached page.`);return await e.newCDPSession(t)},async setUserAgent(n){let r=t.context();if(typeof r.newCDPSession!=`function`){e.debug(`[playwright-cdp-fallback] Cannot apply UA override: newCDPSession unavailable.`);return}await(await r.newCDPSession(t)).send(`Network.setUserAgentOverride`,{userAgent:n}),e.debug(`[playwright-cdp-fallback] Applied user agent override via CDP session.`)}},{get(e,n,r){if(Reflect.has(e,n)){let t=Reflect.get(e,n,r);return typeof t==`function`?t.bind(e):t}let i=Reflect.get(t,n);return typeof i==`function`?i.bind(t):i}});return n.set(t,i),i}function d(e,t){return{type:()=>`page`,url:()=>e.url(),page:async()=>u(e,t)}}function f(e){let t=new WeakMap;return new Proxy({targets(){return e.contexts().flatMap(e=>e.pages()).map(e=>d(e,t))},async pages(){return e.contexts().flatMap(e=>e.pages()).map(e=>u(e,t))},async newPage(){return u(await l(e).newPage(),t)},async disconnect(){await e.close()},async close(){await e.close()}},{get(t,n,r){if(Reflect.has(t,n)){let e=Reflect.get(t,n,r);return typeof e==`function`?e.bind(t):e}let i=Reflect.get(e,n);return typeof i==`function`?i.bind(e):i}})}async function p(e,t){o();let{chromium:n}=await import(`playwright-core`);return f(await n.connectOverCDP(s(e),{timeout:t}))}export{p as t};
@@ -1,2 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{Kt as t,it as n}from"./constants-BYj8Xek8.mjs";import{o as r,r as i}from"./parse-args-Bw413PlW.mjs";import{t as a}from"./playwright-cdp-fallback-DqFdx9-s.mjs";import{t as o}from"./renderer-pid-9tJnZ_9N.mjs";import{n as s,t as c}from"./native-j8l473zn.mjs";import"./definitions-D4g-MS10.mjs";var l=class{buffer;head=0;count=0;capacity;constructor(e=t){this.capacity=Number.isInteger(e)&&e>0?e:t,this.buffer=Array.from({length:this.capacity})}record(e){let t={...e,timestamp:new Date().toISOString(),user:process.env.USERNAME||process.env.USER||`unknown`};if(this.count<this.capacity){let e=(this.head+this.count)%this.capacity;this.buffer[e]=t,this.count+=1;return}this.buffer[this.head]=t,this.head=(this.head+1)%this.capacity}exportJson(){let e=[];for(let t=0;t<this.count;t+=1){let n=(this.head+t)%this.capacity,r=this.buffer[n];r&&e.push(r)}return JSON.stringify(e,null,2)}clear(){this.buffer=[],this.head=0,this.count=0}size(){return this.count}};const u=new Set([`hex`,`int32`,`int64`,`float`,`double`,`string`]);function d(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Error(`Invalid PID: ${JSON.stringify(e)}`);return t}function f(e,t){if(typeof e!=`string`||e.length===0)throw Error(`${t} must be a non-empty string`);return e}function p(e,t){let n=Number(e);if(!Number.isFinite(n)||n<=0)throw Error(`${t} must be a positive number`);return n}function m(e){return typeof e==`string`&&u.has(e)?e:`hex`}function h(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function g(e){return typeof e==`string`&&e.length>0?e:void 0}function _(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function v(e,t){if(t===`hex`){let t=e.replace(/\s+/g,``);return Math.ceil(t.length/2)}return Buffer.from(e,`base64`).length}var y=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=f(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=d(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=d(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=d(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=f(t.executablePath,`executablePath`),n=i(t,`debugPort`,9222),a=r(t,`args`),o=await this.processManager.launchWithDebug(e,n,a);return o?{content:[{type:`text`,text:JSON.stringify({success:!0,process:{pid:o.pid,name:o.name,path:o.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=d(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}}}},b=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=f(t.address,`address`),i=p(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:h(t.pid)??null,address:g(t.address)??null,size:_(t.size)??null,startedAt:n,error:r})}}async handleMemoryWrite(t){let n=Date.now();try{let e=await this.resolvePid(t.pid),r=f(t.address,`address`),i=f(t.data,`data`),a=this.normalizeEncoding(t.encoding,`encoding`)??`hex`,o=v(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=g(t.data),a=this.normalizeEncoding(t.encoding,`encoding`)??`hex`;return this.auditedExceptionResponse({operation:`memory_write`,pid:h(t.pid)??null,address:g(t.address)??null,size:i?v(i,a):null,startedAt:n,error:r})}}async handleMemoryScan(t){let n=Date.now();try{let e=await this.resolvePid(t.pid),r=f(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:h(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=f(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=f(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=f(t.address,`address`),r=p(t.size,`size`),i=f(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 o(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)=>f(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=this.normalizeEncoding(n.encoding,`patches[${t}].encoding`);return{address:f(n.address,`patches[${t}].address`),data:f(n.data,`patches[${t}].data`),...r?{encoding:r}:{}}})}normalizeEncoding(e,t){if(e!==void 0){if(e===`hex`||e===`base64`)return e;throw Error(`${t} must be "hex" or "base64"`)}}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 x=`Injection tools are disabled by configuration. Set ENABLE_INJECTION_TOOLS=true before starting the server to enable DLL and shellcode injection.`;function S(){return{success:!1,error:x,howToEnable:`Set ENABLE_INJECTION_TOOLS=true before starting the server.`,securityNotice:`Injection tools can destabilize target processes; review impact before use.`}}function C(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function w(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)}function T(e){return typeof e==`string`&&e.length>0?e:null}function E(e,t){if(t===`hex`){let t=e.replace(/\s+/g,``);return Math.ceil(t.length/2)}return Buffer.from(e,`base64`).length}const D=Number(process.env.JSHOOK_ELECTRON_ATTACH_CONNECT_TIMEOUT_MS)||5e3;async function O(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 ${D}ms while connecting to Electron browser endpoint ${e}.`))},D);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 a(e,D)}catch(n){throw Error(`Failed to connect to Electron browser endpoint ${e} via both rebrowser-puppeteer and Playwright compatibility fallback. Primary error: ${w(t)}. Fallback error: ${w(n)}.`,{cause:n})}}}var k=class{memoryManager;processMgmt;constructor(e,t){this.memoryManager=e.memoryManager,this.processMgmt=t}async handleInjectDll(t){let r=Date.now();if(!n)return this.processMgmt.recordMemoryAudit({operation:`inject_dll`,pid:C(t.pid),address:T(t.dllPath),size:null,result:`failure`,error:x,durationMs:Date.now()-r}),{content:[{type:`text`,text:JSON.stringify(S(),null,2)}]};try{let e=d(t.pid),n=f(t.dllPath,`dllPath`),i=await this.memoryManager.injectDll(e,n);return this.processMgmt.recordMemoryAudit({operation:`inject_dll`,pid:e,address:n,size:null,result:i.success?`success`:`failure`,error:i.error,durationMs:Date.now()-r}),{content:[{type:`text`,text:JSON.stringify(i,null,2)}]}}catch(n){e.error(`DLL injection failed:`,n);let i=n instanceof Error?n.message:String(n);return this.processMgmt.recordMemoryAudit({operation:`inject_dll`,pid:C(t.pid),address:T(t.dllPath),size:null,result:`failure`,error:i,durationMs:Date.now()-r}),{content:[{type:`text`,text:JSON.stringify({success:!1,error:i},null,2)}]}}}async handleInjectShellcode(t){let r=Date.now();if(!n){let e=T(t.shellcode),n=t.encoding||`hex`;return this.processMgmt.recordMemoryAudit({operation:`inject_shellcode`,pid:C(t.pid),address:null,size:e?E(e,n):null,result:`failure`,error:x,durationMs:Date.now()-r}),{content:[{type:`text`,text:JSON.stringify(S(),null,2)}]}}try{let e=d(t.pid),n=f(t.shellcode,`shellcode`),i=t.encoding||`hex`,a=E(n,i),o=await this.memoryManager.injectShellcode(e,n,i);return this.processMgmt.recordMemoryAudit({operation:`inject_shellcode`,pid:e,address:null,size:a,result:o.success?`success`:`failure`,error:o.error,durationMs:Date.now()-r}),{content:[{type:`text`,text:JSON.stringify(o,null,2)}]}}catch(n){e.error(`Shellcode injection failed:`,n);let i=n instanceof Error?n.message:String(n),a=T(t.shellcode),o=t.encoding||`hex`;return this.processMgmt.recordMemoryAudit({operation:`inject_shellcode`,pid:C(t.pid),address:null,size:a?E(a,o):null,result:`failure`,error:i,durationMs:Date.now()-r}),{content:[{type:`text`,text:JSON.stringify({success:!1,error:i},null,2)}]}}}async handleCheckDebugPort(t){try{let e=d(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=d(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 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=t.wsEndpoint??``,a=t.evaluate??``,o=t.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=s[0];if(!c?.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(`
2
- `)}]};let l=await this.resolveBrowserWsEndpoint(t,i,c);if(!l)throw Error(`Could not determine browser WebSocket endpoint`);let u=await O(l),d,f;try{let e=await u.pages(),t=e.find(e=>e.url().includes(c.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:Function(`return (`+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?d=n.result:f=`Evaluation failed: ${n?.error?.name||`Error`}: ${n?.error?.message||`Unknown error`}`}finally{await u.disconnect()}return f?{content:[{type:`text`,text:JSON.stringify({success:!1,error:f,target:{title:c.title,url:c.url}},null,2)}]}:(e.info(`electron_attach: evaluated in ${c.title}`),{content:[{type:`text`,text:JSON.stringify({success:!0,target:{title:c.title,url:c.url},result:d},null,2)}]})}catch(t){return e.error(`electron_attach failed:`,t),{content:[{type:`text`,text:JSON.stringify({success:!1,error:w(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=w(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`)}};function A(e){let t=new c,n=new s,r=t.getPlatform();return{processManager:t,memoryManager:n,auditTrail:new l,platform:r,ctx:e}}var j=class{processMgmt;memoryOps;deps;buildMemoryDiagnostics;safeBuildMemoryDiagnostics;recordMemoryAudit;constructor(t){this.deps=A(t),e.info(`ProcessToolHandlers initialized for platform: ${this.deps.platform}`),this.processMgmt=new y(this.deps),this.memoryOps=new b(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 handleProcessWindows(e){return this.processMgmt.handleProcessWindows(e)}async handleProcessCheckDebugPort(e){return this.processMgmt.handleProcessCheckDebugPort(e)}async handleProcessLaunchDebug(e){return this.processMgmt.handleProcessLaunchDebug(e)}async handleMemoryRead(e){return this.memoryOps.handleMemoryRead(e)}async handleMemoryWrite(e){return this.memoryOps.handleMemoryWrite(e)}async handleMemoryScan(e){return this.memoryOps.handleMemoryScan(e)}async handleMemoryAuditExport(e){return this.memoryOps.handleMemoryAuditExport(e)}async handleMemoryCheckProtection(e){return this.memoryOps.handleMemoryCheckProtection(e)}async handleMemoryScanFiltered(e){return this.memoryOps.handleMemoryScanFiltered(e)}async handleMemoryBatchWrite(e){return this.memoryOps.handleMemoryBatchWrite(e)}async handleMemoryDumpRegion(e){return this.memoryOps.handleMemoryDumpRegion(e)}async handleMemoryListRegions(e){return this.memoryOps.handleMemoryListRegions(e)}},M=class extends j{injection;constructor(e){super(e),this.injection=new k(this.deps,this.processMgmt)}async handleInjectDll(e){return this.injection.handleInjectDll(e)}async handleInjectShellcode(e){return this.injection.handleInjectShellcode(e)}async handleCheckDebugPort(e){return this.injection.handleCheckDebugPort(e)}async handleEnumerateModules(e){return this.injection.handleEnumerateModules(e)}async handleElectronAttach(e){return this.injection.handleElectronAttach(e)}};export{M as ProcessToolHandlers};
@@ -1,2 +0,0 @@
1
- import{t as e}from"./logger-sBC6IdRT.mjs";import{a as t,r as n,s as r,t as i}from"./parse-args-Bw413PlW.mjs";import{t as a}from"./ResponseBuilder-BfWP-uaT.mjs";import"./definitions-BWxBke3r.mjs";import{createRequire as o}from"node:module";import{createPrivateKey as s,randomUUID as c,webcrypto as l}from"node:crypto";import u from"node:path";import{access as d,mkdir as f,readFile as p,writeFile as m}from"node:fs/promises";const h={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`,publicExponent:new Uint8Array([1,0,1])},g={commonName:`CN`,organizationName:`O`,organizationalUnitName:`OU`,countryName:`C`,localityName:`L`,stateOrProvinceName:`ST`,domainComponent:`DC`,serialNumber:`2.5.4.5`},_=Symbol.for(`jshookmcp.mockttpCaCompatPatched`);let v=null;function y(e,t){return`-----BEGIN ${t}-----\n${(Buffer.from(e).toString(`base64`).match(/.{1,64}/g)||[]).join(`
2
- `)}\n-----END ${t}-----\n`}function b(e,t,n){let r=[];for(let e of n){let n=t[e];if(!n)continue;let i=g[e]||e;r.push({[i]:[n]})}for(let[e,i]of Object.entries(t)){if(!i||n.includes(e))continue;let t=g[e]||e;r.push({[t]:[i]})}return new e.x509.Name(r).toString()}function x(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 S(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 C(e){if(`key`in e&&`cert`in e)return{keyPem:e.key.toString(),certPem:e.cert.toString()};let[t,n]=await Promise.all([p(e.keyPath,`utf8`),p(e.certPath,`utf8`)]);return{keyPem:t,certPem:n}}async function w(e){let t=s(e).export({type:`pkcs8`,format:`der`});return await l.subtle.importKey(`pkcs8`,t,{name:h.name,hash:h.hash},!0,[`sign`])}function T(){let e=new Map;return t=>{let n=e.get(t);return n||(n=l.subtle.generateKey({...h,modulusLength:t},!0,[`sign`,`verify`]),e.set(t,n)),n}}async function E(e,t){let{keyPem:n,certPem:r}=await C(e),i=await w(n),a=new t.x509.X509Certificate(r),o=T(),s=Math.max(1024,e.keyLength??2048);return{generateCertificate:async n=>{let r=x(n),u=await o(s),d=b(t,{countryName:e.countryName??`XX`,localityName:e.localityName,organizationName:e.organizationName,commonName:r.startsWith(`*.`)?void 0:r},[`countryName`,`organizationName`,`localityName`,`commonName`]),f=new Date;f.setDate(f.getDate()-1);let p=new Date(f.getTime()+1080*60*60*1e3),m=[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)],g=await t.x509.X509CertificateGenerator.create({serialNumber:`A${c().replaceAll(`-`,``)}`,subject:d,issuer:a.subject,notBefore:f,notAfter:p,signingAlgorithm:{name:h.name,hash:h.hash},publicKey:u.publicKey,signingKey:i,extensions:m});return{key:y(await l.subtle.exportKey(`pkcs8`,u.privateKey),`PRIVATE KEY`),cert:g.toString(`pem`),ca:a.toString(`pem`),expiresAt:p}}}}async function D(){return v||=(async()=>{let e=o(o(import.meta.url).resolve(`mockttp`)),t=e(`./util/certificates`);if(t[_])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(!S(t))throw t;return await E(e,r)}},t[_]=!0})(),await v}const O={success:e=>a.ok().merge(e).json(),error:e=>a.fail(e).mcpError().json()};async function k(e){try{return await d(e),!0}catch{return!1}}function A(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)}var j=class{server=null;caPathDir;currentPort=null;captureBuffer=[];mockttpModule=null;caReady=!1;constructor(){let e=process.env.HOME||process.env.USERPROFILE||`/tmp`;this.caPathDir=u.join(e,`.jshookmcp`,`ca`)}appendCapture(e){this.captureBuffer.push(e),this.captureBuffer.length>5e3&&this.captureBuffer.shift()}async ensureCa(t){let n=u.join(this.caPathDir,`ca.key`),r=u.join(this.caPathDir,`ca.pem`);this.caReady||=(await f(this.caPathDir,{recursive:!0}),!0);let i=await k(n),a=await k(r);if(!i||!a){e.info(`[proxy] generating new CA certificates`);let i=await t.generateCACertificate();try{i.key=s(i.key).export({type:`pkcs8`,format:`pem`}).toString()}catch{}await m(n,i.key,{mode:384}),await m(r,i.cert)}return{key:await p(n,`utf8`),cert:await p(r,`utf8`),certPath:r}}async handleProxyStart(e){let t=n(e,`port`)||8080,r=i(e,`useHttps`)??!0;if(this.server)return O.error(`Proxy is already running on port ${this.currentPort}`);try{let e=this.mockttpModule??await import(`mockttp`);this.mockttpModule=e;let n=null,i;if(r){await D();let{key:t,cert:r,certPath:a}=await this.ensureCa(e);n=a,i=e.getLocal({https:{key:t,cert:r},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:t.headers,timestamp:Date.now()})}),a.on(`response`,e=>{let t=e;this.appendCapture({type:`response`,id:t.id,status:t.statusCode,headers:t.headers,timestamp:Date.now()})}),await i.start(t),this.server=i,this.currentPort=t,O.success({message:`Proxy started.`,port:this.currentPort,caCertPath:n})}catch(e){this.server=null;let t=e instanceof Error?e.message:String(e);return O.error(`Failed to start proxy: ${t}`)}}async handleProxyStop(e){return this.server?(await this.server.stop(),this.server=null,this.currentPort=null,O.success({message:`Proxy stopped successfully`})):O.error(`Proxy is not running.`)}async handleProxyStatus(e){return O.success({running:!!this.server,port:this.currentPort,caDir:this.caPathDir,caCertPath:u.join(this.caPathDir,`ca.pem`)})}async handleProxyExportCa(e){let t=u.join(this.caPathDir,`ca.pem`);if(!await k(t))return O.error(`CA certificate not found. Start the proxy with HTTPS enabled first.`);let n=await p(t,`utf8`);return O.success({path:t,content:n})}async handleProxyAddRule(e){if(!this.server)return O.error(`Proxy must be running to add rules.`);let i=r(e,`action`),a=(t(e,`method`)||`GET`).toUpperCase(),o=t(e,`urlPattern`)||`.*`;try{let r=A(o),s=this.server,c;c=a===`GET`?s.forGet(r):a===`POST`?s.forPost(r):a===`PUT`?s.forPut(r):a===`DELETE`?s.forDelete(r):s.forAnyRequest();let l;if(i===`forward`)l=await c.thenPassThrough();else if(i===`block`)l=await c.thenCloseConnection();else if(i===`mock_response`){let r=n(e,`mockStatus`)||200,i=t(e,`mockBody`)||``;l=await c.thenReply(r,i)}else return O.error(`Unknown action: ${i}`);return O.success({message:`Rule added successfully`,endpointId:l.id})}catch(e){let t=e instanceof Error?e.message:String(e);return O.error(`Failed to add rule: ${t}`)}}async handleProxyGetRequests(e){let n=t(e,`urlFilter`),r=this.captureBuffer;return n&&(r=r.filter(e=>e.url!==void 0&&e.url.includes(n))),O.success({count:r.length,logs:r.slice(-100)})}async handleProxyClearLogs(e){return this.captureBuffer=[],O.success({message:`Captured proxy logs cleared.`})}async handleProxySetupAdbDevice(e){let n=this.currentPort;if(!n)return O.error(`Proxy must be running locally to setup ADB device reverse tethering.`);let r=u.join(this.caPathDir,`ca.pem`);if(!await k(r))return O.error(`CA certificate not found. Start the proxy with HTTPS enabled first.`);let{exec:i}=await import(`node:child_process`),{promisify:o}=await import(`node:util`),s=o(i),c=t(e,`deviceSerial`),l=c?`-s ${c}`:``;try{try{await s(`adb version`)}catch(e){let t=e instanceof Error?e.message:String(e);return a.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 s(`adb ${l} get-state`),await s(`adb ${l} push "${r}" /data/local/tmp/ca.pem`),await s(`adb ${l} reverse tcp:${n} tcp:${n}`),await s(`adb ${l} shell settings put global http_proxy 127.0.0.1:${n}`);let e=`ADB Configuration Applied Automatically:\n- Verified device connection.\n- Pushed CA to /data/local/tmp/ca.pem\n- Reversed forwarded tcp:${n} -> tcp:${n}\n- Set global http_proxy to 127.0.0.1:${n}\n\nNote: For HTTPS decryption, you still need to manually install the CA cert from /data/local/tmp/ca.pem in Android Settings (due to security restrictions) unless device is rooted.`;return O.success({message:`ADB device successfully configured.`,deviceId:c||`default`,instructions:e})}catch(e){let t=e instanceof Error?e.message:String(e);return O.error(`Failed to configure ADB device: ${t}`)}}};export{j as ProxyHandlers};
@@ -1 +0,0 @@
1
- import{Ar as e,Ir as t,Mr as n,jr as r}from"./constants-BYj8Xek8.mjs";const i={queryCategoryProfiles:[{pattern:`(?:security|vuln|xss|injection|csrf|exploit|attack|prototype\\s*pollution|漏洞|安全|注入|攻击)`,flags:`i`,domainBoosts:[{domain:`hooks`,weight:1.35},{domain:`antidebug`,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:`skia-capture`,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:n,vectorModelId:t,vectorCosineWeight:e,vectorDynamicWeight:r};export{i as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./response-C7rKQst4.mjs";import{t}from"./ToolError-DWU_z7gp.mjs";import{a as n,i as r,r as i,s as a,t as o}from"./parse-args-Bw413PlW.mjs";import"./definitions-BftdXgXI.mjs";import{randomUUID as s}from"node:crypto";function c(e){return e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)}function l(e,t){return t?RegExp(`^${t.split(`*`).map(e=>c(e)).join(`.*`)}$`).test(e):!0}var u=class{state=new Map;history=new Map;watches=new Map;maxHistoryPerKey=100;maxWatches=200;watchIdleTtlMs=30*6e4;mutationSeq=0;lastPersistedSeq=0;persistNotifier;pruneExpiredWatches(){let e=Date.now(),t=0;for(let[n,r]of this.watches)r.expiresAt<e&&(this.watches.delete(n),t++);if(this.watches.size>this.maxWatches){let e=[...this.watches.entries()].toSorted((e,t)=>e[1].lastChecked-t[1].lastChecked),n=this.watches.size-this.maxWatches;for(let r=0;r<n;r++){let n=e[r];n&&(this.watches.delete(n[0]),t++)}}return t}setPersistNotifier(e){this.persistNotifier=e}markDirty(){this.mutationSeq++,this.persistNotifier?.()}recordChange(e,t){this.markDirty();let n=this.history.get(e);n||(n=[],this.history.set(e,n)),n.push(t),n.length>this.maxHistoryPerKey&&n.splice(0,n.length-this.maxHistoryPerKey)}deleteEntry(e){let t=this.state.get(e);t&&(this.state.delete(e),this.recordChange(e,{id:s().slice(0,8),key:t.key,namespace:t.namespace,action:`delete`,oldValue:t.value,timestamp:Date.now()}))}isExpired(e){return!!(e.expiresAt&&Date.now()>e.expiresAt)}cleanupExpired(){let e=Date.now(),t=0;for(let[n,r]of this.state.entries())r.expiresAt&&e>r.expiresAt&&(this.state.delete(n),this.recordChange(n,{id:s().slice(0,8),key:r.key,namespace:r.namespace,action:`expire`,oldValue:r.value,timestamp:e}),t++);return t}getSnapshotSeq(){return this.mutationSeq}getLastPersistedSeq(){return this.lastPersistedSeq}markPersisted(){this.lastPersistedSeq=this.mutationSeq}isPersistDirty(){return this.mutationSeq!==this.lastPersistedSeq}exportSnapshot(){return{schemaVersion:1,savedAt:new Date().toISOString(),entries:[...this.state.entries()],history:[...this.history.entries()]}}restoreSnapshot(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion!==1)return;let n=Date.now();if(this.state.clear(),this.history.clear(),t.entries)for(let[e,r]of t.entries)r.expiresAt&&n>r.expiresAt||this.state.set(e,r);if(t.history)for(let[e,n]of t.history)this.history.set(e,n);this.mutationSeq=this.state.size,this.lastPersistedSeq=this.mutationSeq}},d=class{store;constructor(e){this.store=e}async handleSet(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=e.value,o=n(e,`namespace`,`default`),c=i(e,`ttlSeconds`),l=`${o}:${t}`,u=Date.now(),d=this.store.state.get(l),f=d?.version??0,p=d?.value,m={key:t,value:r,namespace:o,createdAt:d?.createdAt??u,updatedAt:u,ttlSeconds:c,expiresAt:c?u+c*1e3:void 0,version:f+1};return this.store.state.set(l,m),this.store.recordChange(l,{id:s().slice(0,8),key:t,namespace:o,action:`set`,oldValue:p,newValue:r,timestamp:u}),{success:!0,key:t,namespace:o,version:m.version,expiresAt:m.expiresAt?new Date(m.expiresAt).toISOString():void 0}}async handleGet(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=n(e,`namespace`,`default`),i=`${r}:${t}`,o=this.store.state.get(i);return o?this.store.isExpired(o)?(this.store.deleteEntry(i),{found:!1,key:t,namespace:r,expired:!0}):{found:!0,key:t,namespace:r,value:o.value,version:o.version,createdAt:new Date(o.createdAt).toISOString(),updatedAt:new Date(o.updatedAt).toISOString(),ttlSeconds:o.ttlSeconds,expiresAt:o.expiresAt?new Date(o.expiresAt).toISOString():void 0}:{found:!1,key:t,namespace:r}}async handleDelete(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=n(e,`namespace`,`default`),i=`${r}:${t}`;return this.store.state.get(i)?(this.store.deleteEntry(i),{deleted:!0,key:t,namespace:r}):{deleted:!1,key:t,namespace:r,reason:`not_found`}}async handleList(e){let t=n(e,`namespace`),r=o(e,`includeValues`,!1),i=[],a=[];for(let e of this.store.state.values())if(!(t&&e.namespace!==t)){if(this.store.isExpired(e)){a.push(`${e.namespace}:${e.key}`);continue}i.push({key:e.key,namespace:e.namespace,version:e.version,updatedAt:new Date(e.updatedAt).toISOString(),...r?{value:e.value}:{}})}for(let e of a)this.store.deleteEntry(e);return i.sort((e,t)=>e.namespace===t.namespace?e.key.localeCompare(t.key):e.namespace.localeCompare(t.namespace)),{entries:i,total:i.length,namespaces:[...new Set(i.map(e=>e.namespace))]}}async handleClear(e){let t=n(e,`namespace`),r=n(e,`keyPattern`),i=[];for(let[e,n]of this.store.state.entries())t&&n.namespace!==t||l(n.key,r)&&i.push(e);for(let e of i)this.store.deleteEntry(e);return{cleared:i.length,namespace:t??`all`,pattern:r}}async handleStats(){let e=Date.now(),t={},n=0;for(let[,r]of this.store.state.entries()){if(r.expiresAt&&e>r.expiresAt){n++;continue}t[r.namespace]=(t[r.namespace]??0)+1}let r=0;for(let e of this.store.history.values())r+=e.length;return{totalEntries:Object.values(t).reduce((e,t)=>e+t,0),entriesByNamespace:t,expiredEntries:n,totalWatches:this.store.watches.size,historySize:r}}},f=class{store;constructor(e){this.store=e}async handleWatch(e){let t=a(e,`key`);if(!t)throw Error(`key must be a non-empty string`);let r=n(e,`namespace`,`default`),o=i(e,`pollIntervalMs`,1e3);this.store.pruneExpiredWatches();let c=`watch_${s().slice(0,8)}`,u=t.includes(`*`),d=Date.now(),f={id:c,key:t,namespace:r,pattern:u,pollIntervalMs:o,lastChecked:d,lastVersion:{},createdAt:d,expiresAt:d+this.store.watchIdleTtlMs},p=`${r}:`;for(let[e,n]of this.store.state.entries())e.startsWith(p)&&(u?l(n.key,t)&&(f.lastVersion[n.key]=n.version):n.key===t&&(f.lastVersion[n.key]=n.version));return this.store.watches.set(c,f),{watchId:c,key:t,namespace:r,pattern:u,pollIntervalMs:o,initialKeys:Object.keys(f.lastVersion)}}async handleUnwatch(e){let t=a(e,`watchId`),n=this.store.watches.get(t);return n?(this.store.watches.delete(t),{removed:!0,watchId:t,wasWatching:n.key}):{removed:!1,watchId:t,reason:`not_found`}}async handlePoll(e){let t=a(e,`watchId`),n=this.store.watches.get(t);if(!n)throw Error(`Watch "${t}" not found`);let r=Date.now(),i=[],o=`${n.namespace}:`;if(n.pattern){for(let[e,t]of this.store.state.entries())if(e.startsWith(o)&&l(t.key,n.key)){let e=n.lastVersion[t.key];e===void 0?i.push({key:t.key,namespace:t.namespace,action:`created`}):t.version>e&&i.push({key:t.key,namespace:t.namespace,action:`changed`}),n.lastVersion[t.key]=t.version}for(let e of Object.keys(n.lastVersion))!this.store.state.has(`${n.namespace}:${e}`)&&l(e,n.key)&&(i.push({key:e,namespace:n.namespace,action:`deleted`}),delete n.lastVersion[e])}else{let e=`${n.namespace}:${n.key}`,t=this.store.state.get(e),r=n.lastVersion[n.key];!t&&r!==void 0?(i.push({key:n.key,namespace:n.namespace,action:`deleted`}),delete n.lastVersion[n.key]):t&&(r===void 0?i.push({key:t.key,namespace:t.namespace,action:`created`}):t.version>r&&i.push({key:t.key,namespace:t.namespace,action:`changed`}),n.lastVersion[n.key]=t.version)}return n.lastChecked=r,n.expiresAt=r+this.store.watchIdleTtlMs,{watchId:t,changes:i,hasChanges:i.length>0,checkedAt:new Date(r).toISOString()}}},p=class{store;constructor(e){this.store=e}async handleHistory(e){let t=a(e,`key`),r=n(e,`namespace`,`default`),o=i(e,`limit`,50),s=`${r}:${t}`,c=this.store.history.get(s)??[],l=[...c].toSorted((e,t)=>t.timestamp-e.timestamp).slice(0,o);return{key:t,namespace:r,history:l.map(e=>({...e,timestamp:new Date(e.timestamp).toISOString()})),total:c.length,returned:l.length}}async handleExport(e){let t=n(e,`namespace`),r=n(e,`keyPattern`),i=Date.now(),a={};for(let[e,n]of this.store.state.entries())t&&n.namespace!==t||l(n.key,r)&&(n.expiresAt&&i>n.expiresAt||(a[n.key]=n.value));return{data:a,count:Object.keys(a).length,namespace:t??`all`,exportedAt:new Date(i).toISOString()}}async handleImport(e){let t=r(e,`data`),i=n(e,`namespace`,`default`),a=o(e,`overwrite`,!1);if(!t)throw Error(`data must be an object`);let c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){let t=`${i}:${e}`,r=this.store.state.get(t);if(r&&!a){l.push(e);continue}r&&a&&u.push(e);let o=Date.now(),d={key:e,value:n,namespace:i,createdAt:r?.createdAt??o,updatedAt:o,version:(r?.version??0)+1};this.store.state.set(t,d),this.store.recordChange(t,{id:s().slice(0,8),key:e,namespace:i,action:`set`,oldValue:r?.value,newValue:n,timestamp:o,source:`import`}),c.push(e)}return{imported:c.length,skipped:l.length,overwritten:u.length,total:Object.keys(t).length,keys:c}}},m=class{store;storeHandlers;watchHandlers;ioHandlers;constructor(){this.store=new u,this.storeHandlers=new d(this.store),this.watchHandlers=new f(this.store),this.ioHandlers=new p(this.store)}setPersistNotifier(e){this.store.setPersistNotifier(e)}handleSet(e){return this.storeHandlers.handleSet(e)}handleGet(e){return this.storeHandlers.handleGet(e)}handleDelete(e){return this.storeHandlers.handleDelete(e)}handleList(e){return this.storeHandlers.handleList(e)}handleWatchDispatch(e){let t=String(e.action??``);return t===`stop`?this.watchHandlers.handleUnwatch(e):t===`poll`?this.watchHandlers.handlePoll(e):this.watchHandlers.handleWatch(e)}handleIODispatch(e){return String(e.action??``)===`import`?this.ioHandlers.handleImport(e):this.ioHandlers.handleExport(e)}handleWatch(e){return this.watchHandlers.handleWatch(e)}handleUnwatch(e){return this.watchHandlers.handleUnwatch(e)}handlePoll(e){return this.watchHandlers.handlePoll(e)}handleHistory(e){return this.ioHandlers.handleHistory(e)}handleExport(e){return this.ioHandlers.handleExport(e)}handleImport(e){return this.ioHandlers.handleImport(e)}handleClear(e){return this.storeHandlers.handleClear(e)}handleDispatch(n){let r=String(n.action??``);switch(r){case`set`:return this.storeHandlers.handleSet(n);case`get`:return this.storeHandlers.handleGet(n);case`delete`:return this.storeHandlers.handleDelete(n);case`list`:return this.storeHandlers.handleList(n);case`history`:return this.ioHandlers.handleHistory(n);case`clear`:return this.storeHandlers.handleClear(n);default:return Promise.resolve(e(new t(`VALIDATION`,`Invalid action: "${r}". Expected one of: set, get, delete, list, history, clear`,{toolName:`state_board`})))}}handleStats(){return this.storeHandlers.handleStats()}cleanupExpired(){return this.store.cleanupExpired()}getStore(){return this.store}};export{m as SharedStateBoardHandlers};