@jshookmcp/jshook 0.2.9 → 0.3.1

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 (316) hide show
  1. package/README.md +25 -50
  2. package/README.zh.md +25 -48
  3. package/dist/AntiCheatDetector-CGVGNfy5.mjs +1 -0
  4. package/dist/CacheAdapters-CdAxBmVW.mjs +1 -0
  5. package/dist/CodeInjector-BlgyqTOk.mjs +1 -0
  6. package/dist/ConsoleMonitor-Dkqc0HNi.mjs +490 -0
  7. package/dist/DOMInspector-BYY_EJ0C.mjs +95 -0
  8. package/dist/DarwinAPI-DC4HGGLl.mjs +1 -0
  9. package/dist/DetailedDataManager-BniBJlVv.mjs +1 -0
  10. package/dist/EventBus-DgciURGg.mjs +1 -0
  11. package/dist/EvidenceGraphBridge-BIfgB7HP.mjs +1 -0
  12. package/dist/ExtensionManager-erMpqcLk.mjs +1 -0
  13. package/dist/FingerprintManager-N7BZqjxP.mjs +1 -0
  14. package/dist/HardwareBreakpoint-OcJqNFVc.mjs +1 -0
  15. package/dist/HeapAnalyzer-CqAxZzeS.mjs +1 -0
  16. package/dist/{HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs → HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs} +66 -174
  17. package/dist/InstrumentationSession-DxXs0sCp.mjs +1 -0
  18. package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +1 -0
  19. package/dist/MemoryController-BaqstM5w.mjs +2 -0
  20. package/dist/MemoryScanSession-CaxAjZJf.mjs +1 -0
  21. package/dist/MemoryScanner-BLYnMJy6.mjs +1 -0
  22. package/dist/NativeMemoryManager.impl-CI554XbY.mjs +1 -0
  23. package/dist/NativeMemoryManager.utils-DM4NC3FE.mjs +1 -0
  24. package/dist/PEAnalyzer-DJyaJTQJ.mjs +1 -0
  25. package/dist/PageController-D9jVkH0i.mjs +1 -0
  26. package/dist/PointerChainEngine-5nF9eNlu.mjs +1 -0
  27. package/dist/PrerequisiteError-Bl3dK8XA.mjs +1 -0
  28. package/dist/ProcessRegistry-Hf12LlR9.mjs +1 -0
  29. package/dist/ResponseBuilder-B2lu4KEl.mjs +1 -0
  30. package/dist/ReverseEvidenceGraph-B931HeoW.mjs +2 -0
  31. package/dist/ScriptManager-fgqiALgj.mjs +7 -0
  32. package/dist/Speedhack-l6s8L2Qw.mjs +1 -0
  33. package/dist/StealthVerifier-Dhbj4B4P.mjs +1 -0
  34. package/dist/StructureAnalyzer-A-WamfYE.mjs +2 -0
  35. package/dist/ToolCatalog-D_IKl1Hu.mjs +1 -0
  36. package/dist/ToolError-DWU_z7gp.mjs +1 -0
  37. package/dist/ToolProbe-xsfALmN3.mjs +1 -0
  38. package/dist/ToolRegistry-B0Zs-phN.mjs +1 -0
  39. package/dist/ToolRouter.policy-CFHoN_Lw.mjs +4 -0
  40. package/dist/TraceRecorder-Dd8jLXpi.mjs +272 -0
  41. package/dist/VersionDetector-DMoUWyNm.mjs +9 -0
  42. package/dist/Win32API-Bhi5xFBe.mjs +1 -0
  43. package/dist/Win32Debug-CQteFL4F.mjs +1 -0
  44. package/dist/WorkflowEngine-CxEp2WXH.mjs +1 -0
  45. package/dist/analysis-BuR-NgX8.mjs +5 -0
  46. package/dist/{antidebug-CqDTB_uk.mjs → antidebug-BOTZH6-0.mjs} +8 -259
  47. package/dist/artifactRetention-NBdncOEW.mjs +1 -0
  48. package/dist/artifacts-B5xQuEa_.mjs +1 -0
  49. package/dist/authorization-schema-B40obG1A.mjs +1 -0
  50. package/dist/betterSqlite3-CGaxz4AX.mjs +1 -0
  51. package/dist/binary-instrument-Cf9qqLlM.mjs +7 -0
  52. package/dist/bind-helpers-BlAOQrFQ.mjs +1 -0
  53. package/dist/boringssl-inspector-BST5vtKx.mjs +2 -0
  54. package/dist/browser-C4Le3xqA.mjs +11 -0
  55. package/dist/capabilities-DbYCv-HF.mjs +1 -0
  56. package/dist/chunk-C_pMuVsO.mjs +1 -0
  57. package/dist/collector-CKO8RPK8.mjs +1 -0
  58. package/dist/concurrency-CcK46d0h.mjs +1 -0
  59. package/dist/constants-Cp6hBrrx.mjs +1 -0
  60. package/dist/coordination-BbijHEHH.mjs +1 -0
  61. package/dist/debugger-CRJq_krh.mjs +1 -0
  62. package/dist/definitions-BGobEDQa.mjs +1 -0
  63. package/dist/definitions-BGwNSkVm.mjs +1 -0
  64. package/dist/definitions-BbxOUiP-.mjs +1 -0
  65. package/dist/definitions-CCP9gphV.mjs +1 -0
  66. package/dist/definitions-CIO9O-Sw.mjs +1 -0
  67. package/dist/definitions-CYFbewnd.mjs +1 -0
  68. package/dist/definitions-CdWEuIkI.mjs +1 -0
  69. package/dist/definitions-CoQFbggH.mjs +1 -0
  70. package/dist/definitions-CuJRsJ6N.mjs +1 -0
  71. package/dist/definitions-DI9YXsJk.mjs +1 -0
  72. package/dist/definitions-DJklW2sS.mjs +1 -0
  73. package/dist/definitions-DZ8uKusP.mjs +1 -0
  74. package/dist/definitions-Dds_zrWx.mjs +1 -0
  75. package/dist/definitions-Dgrg7f3D.mjs +1 -0
  76. package/dist/definitions-DtE0XLrT.mjs +1 -0
  77. package/dist/definitions-LaYTuwQd.mjs +26 -0
  78. package/dist/definitions-NoVp_9Pm.mjs +1 -0
  79. package/dist/definitions-OvGsfxdt.mjs +1 -0
  80. package/dist/definitions-jXPaVy4P.mjs +1 -0
  81. package/dist/encoding-DGcr6Aj_.mjs +2 -0
  82. package/dist/ensure-browser-core-Buls24LQ.mjs +1 -0
  83. package/dist/evidence-graph-bridge-B0yhGPcs.mjs +1 -0
  84. package/dist/factory-Cx_1LorX.mjs +1 -0
  85. package/dist/flat-target-session-CO5g78k3.mjs +1 -0
  86. package/dist/formatAddress-C7j2fDlM.mjs +1 -0
  87. package/dist/graphql-HLf3MS8H.mjs +62 -0
  88. package/dist/handlers-BLMa4X7l.mjs +54 -0
  89. package/dist/handlers-BP12ZsWc.mjs +4 -0
  90. package/dist/handlers-BZoPla6E.mjs +1 -0
  91. package/dist/handlers-BggKiVx9.mjs +2 -0
  92. package/dist/handlers-D3iev8g1.mjs +1 -0
  93. package/dist/handlers-D49r1-1P.mjs +1 -0
  94. package/dist/handlers-DCE45Ww8.mjs +2 -0
  95. package/dist/handlers-DW5AbYs5.mjs +5 -0
  96. package/dist/handlers-De5u62Ga2.mjs +1 -0
  97. package/dist/handlers-DmQzIc44.mjs +31 -0
  98. package/dist/handlers-DnJRGp7t.mjs +302 -0
  99. package/dist/handlers-Dv_runVv.mjs +2 -0
  100. package/dist/handlers-S9Ws0IGy.mjs +2 -0
  101. package/dist/{handlers-Bl8zkwz1.mjs → handlers-pVNpaw4A.mjs} +144 -841
  102. package/dist/handlers.impl-CD2_kOcC.mjs +1 -0
  103. package/dist/hooks-DDKppogd.mjs +600 -0
  104. package/dist/index.mjs +12 -5225
  105. package/dist/logger-sBC6IdRT.mjs +1 -0
  106. package/dist/maintenance-CutEO84j.mjs +1 -0
  107. package/dist/manifest-BFGxlDRh.mjs +123 -0
  108. package/dist/manifest-BPuE6oH2.mjs +1 -0
  109. package/dist/manifest-BXry5N09.mjs +1 -0
  110. package/dist/manifest-BeP_zJGb2.mjs +1 -0
  111. package/dist/manifest-C0g67k6U.mjs +1 -0
  112. package/dist/manifest-C1nZkTkO.mjs +1 -0
  113. package/dist/manifest-C7qV1z7F.mjs +1 -0
  114. package/dist/manifest-CDeUZGUZ.mjs +1 -0
  115. package/dist/manifest-CDiCtaQT.mjs +1 -0
  116. package/dist/manifest-CFn0359q2.mjs +1 -0
  117. package/dist/manifest-CGq4NpqH2.mjs +1 -0
  118. package/dist/manifest-CJMGt7Qy.mjs +1 -0
  119. package/dist/manifest-CRIJq4Hs.mjs +1 -0
  120. package/dist/manifest-C_hEIjSx.mjs +1 -0
  121. package/dist/manifest-CeQmtQOY.mjs +1 -0
  122. package/dist/manifest-Cq0j7GZt.mjs +1 -0
  123. package/dist/manifest-CtPmHAdn.mjs +1 -0
  124. package/dist/manifest-Cx2IVMUY.mjs +1 -0
  125. package/dist/manifest-D16xPXro.mjs +1 -0
  126. package/dist/manifest-D44TaRJU.mjs +1 -0
  127. package/dist/manifest-D610kxZr.mjs +2 -0
  128. package/dist/manifest-DC-SMF6b.mjs +1 -0
  129. package/dist/manifest-DD3rtxvV.mjs +1 -0
  130. package/dist/manifest-DKUorv5M.mjs +1 -0
  131. package/dist/manifest-DMJlcsTR.mjs +1 -0
  132. package/dist/manifest-DWUUWBz0.mjs +1 -0
  133. package/dist/manifest-De-6Wf2R.mjs +1 -0
  134. package/dist/manifest-Dgh0uDW-.mjs +1 -0
  135. package/dist/manifest-Dm0o3i2U.mjs +1 -0
  136. package/dist/manifest-DsVh7Y4U.mjs +1 -0
  137. package/dist/manifest-DtEFSRaq.mjs +1 -0
  138. package/dist/manifest-H-EpAyZQ.mjs +1 -0
  139. package/dist/manifest-ais9Afrw.mjs +1 -0
  140. package/dist/manifest-tmb54wmA.mjs +1 -0
  141. package/dist/manifest-yu2xiQqe.mjs +1 -0
  142. package/dist/manifest-zrbrpKCC.mjs +1 -0
  143. package/dist/matchesWildcardPattern-BGqLSmEs.mjs +1 -0
  144. package/dist/modules-p-PUNv9r.mjs +332 -0
  145. package/dist/mojo-ipc-VGlv3Qyp.mjs +9 -0
  146. package/dist/network-BjZ1Y-GB.mjs +7 -0
  147. package/dist/outputPaths-BonGThuc.mjs +2 -0
  148. package/dist/parse-args-Cuk7-xUt.mjs +1 -0
  149. package/dist/platform-C446Lf97.mjs +93 -0
  150. package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +1 -0
  151. package/dist/process-C9f2A5zk.mjs +962 -0
  152. package/dist/proxy-CvRepxgV.mjs +1 -0
  153. package/dist/registry-DUHIPE-v.mjs +1 -0
  154. package/dist/response-C7rKQst4.mjs +1 -0
  155. package/dist/search-defaults-D2bY-rzH.mjs +1 -0
  156. package/dist/server/plugin-api.mjs +1 -293
  157. package/dist/shared-state-board-Cyg-xh_k.mjs +1 -0
  158. package/dist/sourcemap-D6Q1UuAp.mjs +1 -0
  159. package/dist/ssrf-policy-T96MR3r6.mjs +1 -0
  160. package/dist/streaming-CTX58tbb.mjs +1 -0
  161. package/dist/tool-builder-CI9914Tf.mjs +1 -0
  162. package/dist/transform-Cv9P2vVD.mjs +103 -0
  163. package/dist/types-CuyefmGT.mjs +1 -0
  164. package/dist/types-DtThH00r.mjs +1 -0
  165. package/dist/wasm-DaJa8J0V.mjs +174 -0
  166. package/dist/webcrack-CsLLJIs9.mjs +46 -0
  167. package/dist/workflow-CYIXtrWD.mjs +101 -0
  168. package/package.json +12 -7
  169. package/dist/AntiCheatDetector-BNk-EoBt.mjs +0 -244
  170. package/dist/CacheAdapters-CDe5WPSV.mjs +0 -80
  171. package/dist/CodeInjector-Cq8q01kp.mjs +0 -150
  172. package/dist/ConsoleMonitor-CPVQW1Y-.mjs +0 -2201
  173. package/dist/DarwinAPI-BNPxu0RH.mjs +0 -363
  174. package/dist/DetailedDataManager-BQQcxh64.mjs +0 -217
  175. package/dist/EventBus-DgPmwpeu.mjs +0 -141
  176. package/dist/EvidenceGraphBridge-SFesNera.mjs +0 -153
  177. package/dist/ExtensionManager-CWYgw0YW.mjs +0 -714
  178. package/dist/FingerprintManager-gzWtkKuf.mjs +0 -96
  179. package/dist/HardwareBreakpoint-B9gZCdFP.mjs +0 -239
  180. package/dist/HeapAnalyzer-BLDH0dCv.mjs +0 -284
  181. package/dist/InstrumentationSession-CvPC7Jwy.mjs +0 -244
  182. package/dist/MemoryController-CbVdCIJF.mjs +0 -167
  183. package/dist/MemoryScanSession-BsDZbLYm.mjs +0 -278
  184. package/dist/MemoryScanner-Bcpml6II.mjs +0 -425
  185. package/dist/NativeMemoryManager.impl-dZtA1ZGn.mjs +0 -482
  186. package/dist/NativeMemoryManager.utils-B-FjA2mJ.mjs +0 -165
  187. package/dist/PEAnalyzer-D1lzJ_VG.mjs +0 -385
  188. package/dist/PageController-Bqm2kZ_X.mjs +0 -417
  189. package/dist/PointerChainEngine-BOhyVsjx.mjs +0 -322
  190. package/dist/PrerequisiteError-Dl33Svkz.mjs +0 -20
  191. package/dist/ResponseBuilder-D3iFYx2N.mjs +0 -143
  192. package/dist/ReverseEvidenceGraph-Dlsk94LC.mjs +0 -269
  193. package/dist/ScriptManager-aHHq0X7U.mjs +0 -3000
  194. package/dist/Speedhack-CqdIFlQl.mjs +0 -156
  195. package/dist/StealthVerifier-Bo4T3bz8.mjs +0 -135
  196. package/dist/StructureAnalyzer-DhFaPvRO.mjs +0 -426
  197. package/dist/ToolCatalog-C0JGZoOm.mjs +0 -582
  198. package/dist/ToolError-jh9whhMd.mjs +0 -15
  199. package/dist/ToolProbe-oC7aPrkv.mjs +0 -45
  200. package/dist/ToolRegistry-BjaF4oNz.mjs +0 -131
  201. package/dist/ToolRouter.policy-BWV67ZK-.mjs +0 -304
  202. package/dist/TraceRecorder-DgxyVbdQ.mjs +0 -519
  203. package/dist/VersionDetector-CwVLVdDM.mjs +0 -104
  204. package/dist/Win32API-CePkipZY.mjs +0 -340
  205. package/dist/Win32Debug-BvKs-gxc.mjs +0 -274
  206. package/dist/WorkflowEngine-CuvkZtWu.mjs +0 -598
  207. package/dist/analysis-CL9uACt9.mjs +0 -463
  208. package/dist/artifactRetention-CFEprwPw.mjs +0 -591
  209. package/dist/artifacts-Bk2-_uPq.mjs +0 -59
  210. package/dist/betterSqlite3-0pqusHHH.mjs +0 -74
  211. package/dist/binary-instrument-CXfpx6fT.mjs +0 -979
  212. package/dist/bind-helpers-xFfRF-qm.mjs +0 -22
  213. package/dist/boringssl-inspector-BH2D3VKc.mjs +0 -180
  214. package/dist/browser-BpOr5PEx.mjs +0 -4082
  215. package/dist/chunk-CjcI7cDX.mjs +0 -15
  216. package/dist/concurrency-Bt0yv1kJ.mjs +0 -41
  217. package/dist/constants-B0OANIBL.mjs +0 -519
  218. package/dist/coordination-qUbyF8KU.mjs +0 -259
  219. package/dist/debugger-gnKxRSN0.mjs +0 -1271
  220. package/dist/definitions-6M-eejaT.mjs +0 -53
  221. package/dist/definitions-B18eyf0B.mjs +0 -18
  222. package/dist/definitions-B3QdlrHv.mjs +0 -34
  223. package/dist/definitions-B4rAvHNZ.mjs +0 -63
  224. package/dist/definitions-BB_4jnmy.mjs +0 -37
  225. package/dist/definitions-BMfYXoNC.mjs +0 -43
  226. package/dist/definitions-Beid2EB3.mjs +0 -27
  227. package/dist/definitions-C1UvM5Iy.mjs +0 -126
  228. package/dist/definitions-CXEI7QC72.mjs +0 -216
  229. package/dist/definitions-C_4r7Fo-2.mjs +0 -14
  230. package/dist/definitions-CkFDALoa.mjs +0 -26
  231. package/dist/definitions-Cke7zEb8.mjs +0 -94
  232. package/dist/definitions-ClJLzsJQ.mjs +0 -25
  233. package/dist/definitions-Cq-zroAU.mjs +0 -28
  234. package/dist/definitions-Cy3Sl6gV.mjs +0 -34
  235. package/dist/definitions-D3VsGcvz.mjs +0 -47
  236. package/dist/definitions-DVGfrn7y.mjs +0 -96
  237. package/dist/definitions-LKpC3-nL.mjs +0 -9
  238. package/dist/definitions-bAhHQJq9.mjs +0 -359
  239. package/dist/encoding-Bvz5jLRv.mjs +0 -1065
  240. package/dist/evidence-graph-bridge-C_fv9PuC.mjs +0 -135
  241. package/dist/factory-DxlGh9Xf.mjs +0 -575
  242. package/dist/formatAddress-DVkj9kpI.mjs +0 -17
  243. package/dist/graphql-DYWzJ29s.mjs +0 -1026
  244. package/dist/handlers-9sAbfIg-.mjs +0 -2552
  245. package/dist/handlers-C67ktuRN.mjs +0 -710
  246. package/dist/handlers-C87g8oCe.mjs +0 -276
  247. package/dist/handlers-CTsDAO6p.mjs +0 -681
  248. package/dist/handlers-Cgyg6c0U.mjs +0 -645
  249. package/dist/handlers-D6j6yka7.mjs +0 -2124
  250. package/dist/handlers-DdFzXLvF.mjs +0 -446
  251. package/dist/handlers-DeLOCd5m.mjs +0 -799
  252. package/dist/handlers-DlCJN4Td.mjs +0 -757
  253. package/dist/handlers-DxGIq15_2.mjs +0 -917
  254. package/dist/handlers-U6L4xhuF.mjs +0 -585
  255. package/dist/handlers-tB9Mp9ZK.mjs +0 -84
  256. package/dist/handlers-tiy7EIBp.mjs +0 -572
  257. package/dist/handlers.impl-DS0d9fUw.mjs +0 -761
  258. package/dist/hooks-CzCWByww.mjs +0 -898
  259. package/dist/logger-Dh_xb7_2.mjs +0 -93
  260. package/dist/maintenance-P7ePRXQC.mjs +0 -830
  261. package/dist/manifest-2ToTpjv8.mjs +0 -106
  262. package/dist/manifest-3g71z6Bg.mjs +0 -79
  263. package/dist/manifest-82baTv4U.mjs +0 -45
  264. package/dist/manifest-B3QVVeBS.mjs +0 -82
  265. package/dist/manifest-BB2J8IMJ.mjs +0 -149
  266. package/dist/manifest-BKbgbSiY.mjs +0 -60
  267. package/dist/manifest-Bcf-TJzH.mjs +0 -848
  268. package/dist/manifest-BmtZzQiQ2.mjs +0 -45
  269. package/dist/manifest-Bnd7kqEY.mjs +0 -55
  270. package/dist/manifest-BqQX6OQC2.mjs +0 -65
  271. package/dist/manifest-BqrQ4Tpj.mjs +0 -81
  272. package/dist/manifest-Br4RPFt5.mjs +0 -370
  273. package/dist/manifest-C5qDjysN.mjs +0 -107
  274. package/dist/manifest-C9RT5nk32.mjs +0 -34
  275. package/dist/manifest-CAhOuvSl.mjs +0 -204
  276. package/dist/manifest-CBYWCUBJ.mjs +0 -51
  277. package/dist/manifest-CFADCRa1.mjs +0 -37
  278. package/dist/manifest-CQVhavRF.mjs +0 -114
  279. package/dist/manifest-CT7zZBV1.mjs +0 -48
  280. package/dist/manifest-CV12bcrF.mjs +0 -121
  281. package/dist/manifest-CXsRWjjI.mjs +0 -224
  282. package/dist/manifest-CZLUCfG02.mjs +0 -95
  283. package/dist/manifest-D6phHKFd.mjs +0 -131
  284. package/dist/manifest-DCyjf4n2.mjs +0 -294
  285. package/dist/manifest-DHsnKgP6.mjs +0 -60
  286. package/dist/manifest-Df_dliIe.mjs +0 -55
  287. package/dist/manifest-Dh8WBmEW.mjs +0 -129
  288. package/dist/manifest-DhKRAT8_.mjs +0 -92
  289. package/dist/manifest-DlpTj4ic2.mjs +0 -193
  290. package/dist/manifest-DrbmZcFl2.mjs +0 -253
  291. package/dist/manifest-DuwHjUa5.mjs +0 -70
  292. package/dist/manifest-DzwvxPJX.mjs +0 -38
  293. package/dist/manifest-NXctwWQq.mjs +0 -68
  294. package/dist/manifest-Sc_0JQ13.mjs +0 -418
  295. package/dist/manifest-gZ4s_UtG.mjs +0 -96
  296. package/dist/manifest-qSleDqdO.mjs +0 -1023
  297. package/dist/modules-C184v-S9.mjs +0 -11365
  298. package/dist/mojo-ipc-B_H61Afw.mjs +0 -525
  299. package/dist/network-671Cw6hV.mjs +0 -3346
  300. package/dist/outputPaths-B1uGmrWZ.mjs +0 -1145
  301. package/dist/parse-args-BlRjqlkL.mjs +0 -39
  302. package/dist/platform-WmNn8Sxb.mjs +0 -2070
  303. package/dist/process-QcbIy5Zq.mjs +0 -1401
  304. package/dist/proxy-DqNs0bAd.mjs +0 -170
  305. package/dist/registry-D-6e18lB.mjs +0 -34
  306. package/dist/response-BQVP-xUn.mjs +0 -28
  307. package/dist/shared-state-board-DV-dpHFJ.mjs +0 -586
  308. package/dist/sourcemap-Dq8ez8vS.mjs +0 -650
  309. package/dist/ssrf-policy-ZaUfvhq7.mjs +0 -166
  310. package/dist/streaming-BUQ0VJsg.mjs +0 -725
  311. package/dist/tool-builder-DCbIC5Eo.mjs +0 -186
  312. package/dist/transform-CiYJfNX0.mjs +0 -1007
  313. package/dist/types-Bx92KJfT.mjs +0 -4
  314. package/dist/types-CPhOReNX.mjs +0 -37
  315. package/dist/wasm-DQTnHDs4.mjs +0 -531
  316. package/dist/workflow-f3xJOcjx.mjs +0 -725
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-CI9914Tf.mjs";import{t}from"./authorization-schema-B40obG1A.mjs";const n=[e(`network_extract_auth`,e=>e.desc(`Extract authentication data from captured network requests.`).number(`minConfidence`,`Minimum confidence threshold 0-1`,{default:.4,minimum:0,maximum:1})),e(`network_export_har`,e=>e.desc(`Export captured network traffic as HAR.`).string(`outputPath`,`File path to write the HAR file. If omitted, returns HAR as JSON.`).boolean(`includeBodies`,`Include response bodies in the HAR (may be slow for large captures). Default: false`,{default:!1}).openWorld()),e(`network_replay_request`,e=>e.desc(`Replay a captured network request with optional changes.`).string(`requestId`,`Request ID from network_get_requests to replay`).object(`headerPatch`,{additionalProperties:{type:`string`}},`Headers to add or override (key-value pairs)`).object(`sessionProfile`,{cookies:{type:`array`,items:{type:`object`,properties:{name:{type:`string`},value:{type:`string`},domain:{type:`string`},path:{type:`string`},expires:{type:`number`},httpOnly:{type:`boolean`},secure:{type:`boolean`},sameSite:{type:`string`,enum:[`Strict`,`Lax`,`None`]}},required:[`name`,`value`]}},userAgent:{type:`string`},acceptLanguage:{type:`string`},referer:{type:`string`},clientHints:{type:`object`,properties:{"sec-ch-ua":{type:`string`},"sec-ch-ua-mobile":{type:`string`},"sec-ch-ua-platform":{type:`string`},"sec-ch-ua-full-version-list":{type:`string`}}},platform:{type:`string`},origin:{type:`string`},collectedAt:{type:`number`},ttlSec:{type:`number`}},`Inject browser cookies, User-Agent and Accept-Language from a captured session into the replay.`).string(`bodyPatch`,`Replace the entire request body with this string`).string(`methodOverride`,`Override the HTTP method`).string(`urlOverride`,`Override the request URL`).object(`authorization`,t,`Request-scoped authorization policy for private-network or insecure-HTTP replay. Use exact hosts/CIDRs instead of process-wide bypasses.`).string(`authorizationCapability`,`Base64url-encoded JSON capability for request-scoped authorization. Payload fields mirror authorization and must include requestId.`).number(`timeoutMs`,`Request timeout in milliseconds`,{default:3e4,minimum:1e3,maximum:12e4}).boolean(`dryRun`,`Preview the request without sending it`,{default:!0}).requiredOpenWorld(`requestId`)),e(`network_intercept`,e=>e.desc(`Manage network interception rules.`).enum(`action`,[`add`,`list`,`disable`],`Intercept operation`).string(`urlPattern`,`URL pattern to match`).enum(`urlPatternType`,[`glob`,`regex`],`How to interpret urlPattern`,{default:`glob`}).enum(`interceptAction`,[`continue`,`abort`,`fulfill`],`Match action`,{default:`fulfill`}).enum(`stage`,[`Request`,`Response`],`Intercept stage. Response (default) intercepts after server responds.`,{default:`Response`}).number(`responseCode`,`HTTP status code to return`,{default:200,minimum:100,maximum:599}).object(`responseHeaders`,{additionalProperties:{type:`string`}},`Custom response headers as key-value pairs.`).string(`responseBody`,`Custom response body string.`).array(`rules`,{type:`object`,properties:{urlPattern:{type:`string`},urlPatternType:{type:`string`,enum:[`glob`,`regex`]},interceptAction:{type:`string`,enum:[`continue`,`abort`,`fulfill`]},stage:{type:`string`,enum:[`Request`,`Response`]},responseCode:{type:`number`},responseHeaders:{type:`object`,additionalProperties:{type:`string`}},responseBody:{type:`string`}},required:[`urlPattern`]},`Rule objects to add`).string(`ruleId`,`Rule ID to remove`).boolean(`all`,`Remove all rules`,{default:!1}).required(`action`)),e(`network_tls_fingerprint`,e=>e.desc(`Compute TLS/HTTP fingerprint hashes for bot detection.`).enum(`mode`,[`analyze_request`,`compute_tls`,`compute_http`],`Fingerprint mode`).string(`requestId`,`Request ID to analyze`).array(`tlsVersions`,{type:`string`},`TLS version codes in order`).array(`ciphers`,{type:`string`},`Cipher suite codes in order`).array(`extensions`,{type:`string`},`Extension type codes in order`).array(`signatureAlgorithms`,{type:`string`},`Signature algorithm codes in order`).enum(`protocol`,[`tls`,`quic`,`dtls`],`Transport protocol type`,{default:`tls`}).boolean(`sni`,`Whether SNI (Server Name Indication) extension is present`,{default:!0}).string(`alpn`,`ALPN value`).array(`httpHeaders`,{type:`string`},`HTTP header names in order`).string(`userAgent`,`User-Agent value`).string(`httpMethod`,`HTTP method`,{default:`GET`}).string(`httpVersion`,`HTTP version`,{default:`1.1`}).string(`cookieHeader`,`Cookie header value`).string(`acceptLanguage`,`Accept-Language header value`).boolean(`includeAnalysis`,`Include detailed fingerprint breakdown`,{default:!0}).required(`mode`)),e(`network_bot_detect_analyze`,e=>e.desc(`Analyze captured requests for bot-detection signals.`).number(`limit`,`Maximum requests to analyze`,{default:50,minimum:1,maximum:500}).boolean(`includeDetails`,`Include per-request analysis details`,{default:!1}).query())],r=[e(`network_enable`,e=>e.desc(`Enable network request monitoring.`).boolean(`enableExceptions`,`Also capture uncaught exceptions`,{default:!0})),e(`network_disable`,e=>e.desc(`Disable network request monitoring`).destructive()),e(`network_get_status`,e=>e.desc(`Get network monitoring status.`).query()),e(`network_monitor`,e=>e.desc(`Manage network request monitoring.`).enum(`action`,[`enable`,`disable`,`status`],`Action to perform`).boolean(`enableExceptions`,`Only for enable action: Also capture uncaught exceptions`,{default:!0}).required(`action`)),e(`network_get_requests`,e=>e.desc(`Get captured network requests.`).string(`url`,`Filter by URL substring`).string(`urlRegex`,`Filter by URL regex pattern`).string(`method`,`Filter by HTTP method (GET, POST, PUT, DELETE)`).number(`sinceTimestamp`,`Only return requests after this epoch timestamp (milliseconds). Useful for incremental polling.`).string(`sinceRequestId`,`Only return requests after this requestId (exclusive). Useful for incremental retrieval.`).number(`tail`,`Return the last N requests after filtering`).number(`limit`,`Maximum number of results per page`,{default:100,minimum:1,maximum:1e3}).number(`offset`,`Skip results for pagination`,{default:0,minimum:0}).boolean(`autoEnable`,`Auto-enable network monitoring when currently disabled`,{default:!0}).boolean(`enableExceptions`,`When autoEnable=true, also enable uncaught exception monitoring`,{default:!0}).array(`fields`,{type:`string`},`Only include these fields per request (e.g. ["url","method","status"]). Reduces response size drastically.`).boolean(`deduplicateUrls`,`Deduplicate URLs by stripping query params and normalizing path segments (UUIDs/IDs → {id}). Returns unique endpoint patterns with counts instead of individual requests.`,{default:!1})),e(`network_get_response_body`,e=>e.desc(`Get the response body for a captured request.`).string(`requestId`,`Request ID (from network_get_requests)`).number(`maxSize`,`Maximum response size in bytes`,{default:1e5,minimum:1024,maximum:2e7}).boolean(`returnSummary`,`Return only size and preview instead of full body`,{default:!1}).number(`retries`,`Retry count when response body is not yet available`,{default:3,minimum:0,maximum:10}).number(`retryIntervalMs`,`Retry interval in milliseconds`,{default:500,minimum:100,maximum:1e4}).boolean(`autoEnable`,`Auto-enable network monitoring when currently disabled`,{default:!1}).boolean(`enableExceptions`,`When autoEnable=true, also enable uncaught exception monitoring`,{default:!0}).required(`requestId`)),e(`network_get_stats`,e=>e.desc(`Get network statistics.`).query()),e(`performance_get_metrics`,e=>e.desc(`Get page performance metrics.`).boolean(`includeTimeline`,`Include detailed timeline events`,{default:!1}).query()),e(`performance_coverage`,e=>e.desc(`Start or stop code coverage recording.`).enum(`action`,[`start`,`stop`],`Coverage action`).required(`action`)),e(`performance_take_heap_snapshot`,e=>e.desc(`Take a V8 heap memory snapshot`)),e(`performance_trace`,e=>e.desc(`Start or stop a Chrome performance trace.`).enum(`action`,[`start`,`stop`],`Trace action`).array(`categories`,{type:`string`},`Trace categories to capture`).boolean(`screenshots`,`Capture screenshots during tracing`,{default:!1}).string(`artifactPath`,`Custom output path`).required(`action`)),e(`profiler_cpu`,e=>e.desc(`Start or stop CPU profiling.`).enum(`action`,[`start`,`stop`],`Profiler action`).string(`artifactPath`,`Custom output path`).required(`action`)),e(`profiler_heap_sampling`,e=>e.desc(`Start or stop heap allocation sampling.`).enum(`action`,[`start`,`stop`],`Sampling action`).number(`samplingInterval`,`Sampling interval in bytes`,{default:32768,minimum:256,maximum:1048576}).string(`artifactPath`,`Custom output path`).number(`topN`,`Number of top allocators to return`,{default:20,minimum:1,maximum:100}).required(`action`))],i=[e(`console_get_exceptions`,e=>e.desc(`Get captured uncaught exceptions from the page`).string(`url`,`Filter by URL substring`).number(`limit`,`Maximum number of exceptions to return`,{default:50,minimum:1,maximum:1e3}).readOnly()),e(`console_inject`,e=>e.desc(`Inject an in-page script, XHR, fetch, or function monitor.`).enum(`type`,[`script`,`xhr`,`fetch`,`function`],`Injection type`).string(`functionName`,`Global function path to trace`).boolean(`persistent`,`Keep the injection across page navigations`,{default:!1}).required(`type`).openWorld()),e(`console_inject_fetch_interceptor`,e=>e.desc(`Inject a fetch interceptor.`).boolean(`persistent`,`Keep the injection across page navigations`,{default:!1}).openWorld()),e(`console_inject_xhr_interceptor`,e=>e.desc(`Inject an XMLHttpRequest interceptor.`).boolean(`persistent`,`Keep the injection across page navigations`,{default:!1}).openWorld()),e(`console_buffers`,e=>e.desc(`Manage injected interceptor state.`).enum(`action`,[`clear`,`reset`],`Buffer action: clear buffers or reset interceptors`).required(`action`))],a=[e(`network_traceroute`,e=>e.desc(`Run an ICMP traceroute.`).string(`target`,`Target hostname or IP address to trace route to`).number(`maxHops`,`Maximum number of hops`,{default:30,minimum:1,maximum:64}).number(`timeout`,`Per-hop timeout in milliseconds`,{default:5e3,minimum:100,maximum:3e4}).number(`packetSize`,`ICMP echo request payload size in bytes`,{default:32,minimum:8,maximum:65500}).required(`target`).query()),e(`network_icmp_probe`,e=>e.desc(`Run an ICMP echo probe.`).string(`target`,`Target hostname or IP address to probe`).number(`ttl`,`Time-to-live value`,{default:128,minimum:1,maximum:255}).number(`packetSize`,`ICMP echo request payload size in bytes`,{default:32,minimum:8,maximum:65500}).number(`timeout`,`Timeout in milliseconds`,{default:5e3,minimum:100,maximum:3e4}).required(`target`).query())],o=[e(`http_request_build`,e=>e.desc(`Build a raw HTTP/1.x request payload.`).string(`method`,`HTTP method token`).string(`target`,`Request target, such as /path, *, or an absolute-form URL`).string(`host`,`Optional Host header value to inject when addHostHeader is enabled`).object(`headers`,{additionalProperties:{type:`string`}},`Optional HTTP headers to include in the request`).string(`body`,`Optional UTF-8 request body`).enum(`httpVersion`,[`1.0`,`1.1`],`HTTP protocol version to emit`,{default:`1.1`}).boolean(`addHostHeader`,`Auto-add the Host header when host is provided`,{default:!0}).boolean(`addContentLength`,`Auto-add Content-Length when a body is present and Transfer-Encoding is absent`,{default:!0}).boolean(`addConnectionClose`,`Auto-add Connection: close when absent`,{default:!0}).requiredOpenWorld(`method`,`target`)),e(`http_plain_request`,e=>e.desc(`Send a raw HTTP request over plain TCP.`).string(`host`,`Target hostname or IP literal`).number(`port`,`TCP port to connect to. Default: 80`,{default:80,minimum:1,maximum:65535}).string(`requestText`,`Raw HTTP request text to send as UTF-8 bytes`).object(`authorization`,t,`Request-scoped authorization policy for private-network or insecure-HTTP targets. Use exact hosts/CIDRs instead of process-wide bypasses.`).number(`timeoutMs`,`Socket timeout in milliseconds`,{default:3e4,minimum:1e3,maximum:12e4}).number(`maxResponseBytes`,`Maximum number of raw response bytes to capture before truncating the exchange`,{default:512e3,minimum:1024,maximum:10485760}).requiredOpenWorld(`host`,`requestText`)),e(`http2_probe`,e=>e.desc(`Probe an HTTP/2 endpoint.`).string(`url`,`Absolute http:// or https:// URL to probe`).string(`method`,`HTTP method token to send. Default: GET`).object(`headers`,{additionalProperties:{type:`string`}},`Optional request headers to include. Header names are normalized to lowercase for HTTP/2.`).string(`body`,`Optional UTF-8 request body to send with the probe`).array(`alpnProtocols`,{type:`string`},`ALPN protocols to offer`).object(`authorization`,t,`Request-scoped authorization policy for private-network or insecure-HTTP targets. Use exact hosts/CIDRs instead of process-wide bypasses.`).number(`timeoutMs`,`Probe timeout in milliseconds`,{default:3e4,minimum:1e3,maximum:12e4}).number(`maxBodyBytes`,`Maximum number of response body bytes to capture for the snippet before truncating`,{default:32768,minimum:1024,maximum:1048576}).requiredOpenWorld(`url`)),e(`http2_frame_build`,e=>e.desc(`Build a raw HTTP/2 frame.`).string(`frameType`,`HTTP/2 frame type: DATA, SETTINGS, PING, WINDOW_UPDATE, RST_STREAM, GOAWAY, or RAW`).number(`streamId`,`Stream identifier (0 for connection-level frames). Default: 0`,{default:0,minimum:0,maximum:2147483647}).number(`flags`,`Raw flags byte (0-255). Overrides type-specific defaults when set.`,{minimum:0,maximum:255}).number(`frameTypeCode`,`Explicit frame type code for RAW frames (0-255). Required when frameType is RAW.`,{minimum:0,maximum:255}).string(`payloadHex`,`Frame payload as a hex string. Mutually exclusive with payloadText.`).string(`payloadText`,`Frame payload as a text string. Mutually exclusive with payloadHex.`).string(`payloadEncoding`,`Encoding for payloadText: utf8 or ascii. Default: utf8`).array(`settings`,{type:`object`,properties:{id:{type:`number`},value:{type:`number`}},required:[`id`,`value`]},`Array of {id, value} entries for SETTINGS frames`).boolean(`ack`,`Set the ACK flag on SETTINGS or PING frames`).string(`pingOpaqueDataHex`,`Exactly 8 bytes of opaque data for PING frames (hex string)`).number(`windowSizeIncrement`,`Window size increment for WINDOW_UPDATE frames (1 to 2^31-1)`).number(`errorCode`,`Error code for RST_STREAM or GOAWAY frames (0 to 2^32-1)`).number(`lastStreamId`,`Last stream ID for GOAWAY frames (0 to 2^31-1)`).string(`debugDataText`,`Optional debug data for GOAWAY frames`).string(`debugDataEncoding`,`Encoding for debugDataText: utf8 or ascii. Default: utf8`).requiredOpenWorld(`frameType`)),e(`dns_resolve`,e=>e.desc(`Resolve a hostname to DNS records using the system resolver.`).string(`hostname`,`Hostname to resolve (e.g. google.com)`).string(`rrType`,`DNS record type: A, AAAA, MX, TXT, NS, CNAME, SOA, PTR, SRV, or ANY`,{default:`A`}).requiredOpenWorld(`hostname`)),e(`dns_reverse`,e=>e.desc(`Reverse DNS lookup — find hostnames for an IP address.`).string(`ip`,`IP address to reverse lookup (e.g. 8.8.8.8)`).requiredOpenWorld(`ip`)),e(`dns_probe`,e=>e.desc(`Run a DNS query and return structured status instead of throwing.`).string(`hostname`,`Hostname to query`).string(`rrType`,`DNS record type: A, AAAA, MX, TXT, NS, CNAME, SOA, PTR, SRV, or ANY`,{default:`A`}).requiredOpenWorld(`hostname`)),e(`dns_cname_chain`,e=>e.desc(`Trace the full CNAME chain for a hostname.`).string(`hostname`,`Hostname to trace CNAME chain for`).number(`maxDepth`,`Maximum chain depth to follow. Default: 10`,{default:10,minimum:1,maximum:30}).requiredOpenWorld(`hostname`)),e(`dns_bulk_resolve`,e=>e.desc(`Resolve many hostnames concurrently with per-host status.`).array(`hostnames`,{type:`string`},`List of hostnames to resolve (max 1000)`).string(`rrType`,`DNS record type: A, AAAA, MX, TXT, NS, CNAME, SOA, PTR, SRV, or ANY`,{default:`A`}).number(`concurrency`,`Maximum number of concurrent DNS queries. Default: 10`,{default:10,minimum:1,maximum:50}).requiredOpenWorld(`hostnames`)),e(`network_rtt_measure`,e=>e.desc(`Measure round-trip time to a target URL.`).string(`url`,`Target URL to measure RTT to`).string(`probeType`,`Probe type: tcp, tls, or http. Default: tcp`,{default:`tcp`}).number(`iterations`,`Number of probe iterations (1-50). Default: 5`,{default:5,minimum:1,maximum:50}).number(`timeoutMs`,`Per-probe timeout in milliseconds (100-30000). Default: 5000`,{default:5e3,minimum:100,maximum:3e4}).object(`authorization`,{additionalProperties:{type:`string`}},`Authorization policy for network access`).requiredOpenWorld(`url`)),e(`network_latency_stats`,e=>e.desc(`Measure repeated latency and compute percentile stats.`).string(`url`,`Target URL to measure`).enum(`probeType`,[`tcp`,`tls`,`http`],`Probe type`,{default:`http`}).number(`iterations`,`Number of probes`,{default:20,minimum:5,maximum:100}).number(`concurrency`,`Max concurrent probes`,{default:5,minimum:1,maximum:20}).number(`timeoutMs`,`Per-probe timeout ms`,{default:5e3,minimum:100,maximum:3e4}).object(`authorization`,{additionalProperties:{type:`string`}},`Authorization policy for network access`).requiredOpenWorld(`url`))],s=[...r,...i,...o,...n,...a];export{s as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-CI9914Tf.mjs";const t={type:`object`,additionalProperties:!1,properties:{allowPrivateNetwork:{type:`boolean`,description:`Allow access to private/reserved targets only when the request also matches allowedHosts or allowedCidrs.`},allowInsecureHttp:{type:`boolean`,description:`Allow non-loopback HTTP targets only when the request also matches allowedHosts or allowedCidrs.`},allowedHosts:{type:`array`,items:{type:`string`},description:`Exact hostname or host:port allowlist for the primary target (for example ["labs.example.com", "localhost:8080"]).`},allowedCidrs:{type:`array`,items:{type:`string`},description:`CIDR allowlist applied after DNS resolution (for example ["10.10.0.0/16", "192.168.1.10/32"]).`},allowedRedirectHosts:{type:`array`,items:{type:`string`},description:`Optional hostname or host:port allowlist for redirect hops. When omitted, redirects inherit allowedHosts/allowedCidrs.`}},description:`Request-level network authorization policy. Use this instead of process-wide bypasses when you need to reach a real lab target, private address, or plain HTTP service.`},n=[e(`js_bundle_search`,e=>e.desc(`Fetch a remote JS bundle and search it with named regex patterns, with caching and noise filtering.`).string(`url`,`Remote URL of the JavaScript bundle to analyze`).array(`patterns`,{type:`object`,properties:{name:{type:`string`,description:`Human-readable label for this pattern`},regex:{type:`string`,description:`JavaScript regex string`},contextBefore:{type:`number`,description:`Characters of context before match (default: 80)`},contextAfter:{type:`number`,description:`Characters of context after match (default: 80)`}},required:[`name`,`regex`]},`Named regex patterns to search for`).boolean(`cacheBundle`,`Cache the bundle for 5 minutes to avoid re-downloads`,{default:!0}).boolean(`stripNoise`,`Skip matches inside SVG path data or base64 blobs`,{default:!0}).number(`maxMatches`,`Maximum matches to return per pattern`,{default:10,minimum:1,maximum:1e3}).prop(`networkPolicy`,t).requiredOpenWorld(`url`,`patterns`)),e(`page_script_register`,e=>e.desc(`Register a named reusable JS snippet in the Script Library. Execute with page_script_run.`).string(`name`,`Unique script name (e.g. "my_extractor")`).string(`code`,'JavaScript expression/IIFE to register. Use `typeof __params__ !== "undefined" ? __params__ : {}` to safely access runtime parameters.').string(`description`,`Optional human-readable description of the script`).required(`name`,`code`)),e(`page_script_run`,e=>e.desc(`Execute a named script from the Script Library with optional runtime params (__params__).`).string(`name`,`Script name to run (built-in or registered)`).prop(`params`,{type:`object`,additionalProperties:!0,description:`Optional parameters injected as __params__ (must be JSON-serializable)`}).requiredOpenWorld(`name`)),e(`api_probe_batch`,e=>e.desc(`Batch-probe API endpoints in browser context with auto token injection and HTML skip.`).string(`baseUrl`,`Base URL prefix (e.g. "https://chat.qwen.ai") — trailing slash will be stripped`).array(`paths`,{type:`string`},`Paths to probe (e.g. ["/api/v1/users", "/api/v1/chats"])`).enum(`method`,[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`],`HTTP method for all probes`,{default:`GET`}).object(`headers`,{additionalProperties:{type:`string`}},`Additional HTTP headers to include in all requests`).string(`bodyTemplate`,`JSON body string to send for POST/PUT/PATCH requests (optional)`).array(`includeBodyStatuses`,{type:`number`},`Status codes for which to include response body snippet (default: [200, 201, 204])`).number(`maxBodySnippetLength`,`Max characters per response body snippet`,{default:500,minimum:0,maximum:1e4}).boolean(`autoInjectAuth`,`Auto-inject Bearer token from localStorage (token / active_token / access_token).`,{default:!0}).prop(`networkPolicy`,t).requiredOpenWorld(`baseUrl`,`paths`)),e(`list_extension_workflows`,e=>e.desc(`List runtime-loaded extension workflows from plugins/ or workflows/ directories.`).query()),e(`run_extension_workflow`,e=>e.desc(`Execute an extension workflow by workflowId with optional config and timeout overrides.`).string(`workflowId`,`Registered extension workflow id to execute`).string(`profile`,`Optional profile label exposed to the workflow execution context`).prop(`config`,{type:`object`,additionalProperties:!0,description:`Optional config overrides read through ctx.getConfig(path, fallback)`}).prop(`nodeInputOverrides`,{type:`object`,additionalProperties:{type:`object`,additionalProperties:!0},description:`Optional shallow input overrides keyed by workflow node id`}).number(`timeoutMs`,`Optional override for total workflow timeout in milliseconds`).requiredOpenWorld(`workflowId`))];export{n as t};
@@ -0,0 +1,26 @@
1
+ import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`debugger_lifecycle`,e=>e.desc(`Enable or disable the CDP debugger session.`).enum(`action`,[`enable`,`disable`],`Action to perform`).required(`action`).idempotent()),e(`debugger_pause`,e=>e.desc(`Pause execution at the next statement.`)),e(`debugger_resume`,e=>e.desc(`Resume execution.`)),e(`debugger_step`,e=>e.desc(`Step execution: into (enter next call), over (skip next call), out (exit current function).`).enum(`direction`,[`into`,`over`,`out`],`Step direction`).required(`direction`)),e(`breakpoint`,e=>e.desc(`Manage breakpoints: code (line/script), XHR (URL pattern), event listener, event category, and exception breakpoints.
2
+
3
+ Actions:
4
+ - set: Create a breakpoint. Type determines required params.
5
+ - remove: Remove a breakpoint by ID.
6
+ - list: List active breakpoints of the given type.
7
+
8
+ Types & params:
9
+ - code: lineNumber (required), scriptId?, columnNumber?, condition?
10
+ - xhr: urlPattern (required for set)
11
+ - event: eventName (required for set), targetName?
12
+ - event_category: category (required for set)
13
+ - exception: state (required for set)`).enum(`action`,[`set`,`remove`,`list`],`Breakpoint operation`).enum(`type`,[`code`,`xhr`,`event`,`event_category`,`exception`],`Breakpoint type (default: code)`,{default:`code`}).string(`url`,`Script URL (type=code, alternative to scriptId)`).string(`scriptId`,`Script ID (type=code)`).number(`lineNumber`,`Line number 0-based (type=code, action=set)`).number(`columnNumber`,`Column number 0-based (type=code)`).string(`condition`,`Conditional expression (type=code)`).string(`urlPattern`,`URL pattern with wildcards (type=xhr, action=set)`).string(`eventName`,`Event name e.g. "click" (type=event, action=set)`).string(`targetName`,`Target name e.g. "WebSocket" (type=event)`).enum(`category`,[`mouse`,`keyboard`,`timer`,`websocket`],`Event category (type=event_category)`).enum(`state`,[`none`,`uncaught`,`all`],`Exception pause state (type=exception)`).string(`breakpointId`,`Breakpoint ID (action=remove)`).required(`action`).idempotent()),e(`get_call_stack`,e=>e.desc(`Get the current call stack.`).query()),e(`debugger_evaluate`,e=>e.desc(`Evaluate a JavaScript expression. context="frame" evaluates in the current call frame (requires paused state); context="global" evaluates in the global context (no pause required).`).enum(`context`,[`frame`,`global`],`Evaluation context`,{default:`frame`}).string(`expression`,`JavaScript expression to evaluate`).string(`callFrameId`,`Call frame ID (for context=frame; from get_call_stack, defaults to current frame)`).requiredOpenWorld(`expression`)),e(`debugger_wait_for_paused`,e=>e.desc(`Wait for debugger pause after setting breakpoints.`).number(`timeout`,`Timeout in milliseconds (default: 30000)`,{default:3e4,minimum:1e3,maximum:12e4}).query()),e(`debugger_get_paused_state`,e=>e.desc(`Get current paused state and reason.`).query()),e(`get_object_properties`,e=>e.desc(`Get properties of an object by objectId.`).string(`objectId`,`Object ID (from get_scope_variables)`).required(`objectId`).query()),e(`get_scope_variables_enhanced`,e=>e.desc(`Enhanced scope variable inspection with deep object traversal.`).string(`callFrameId`,`Call frame ID (from get_call_stack, defaults to current frame)`).boolean(`includeObjectProperties`,`Expand object properties recursively (default: false)`,{default:!1}).number(`maxDepth`,`Maximum traversal depth for nested objects (default: 1)`,{default:1,minimum:1,maximum:10}).boolean(`skipErrors`,`Skip properties that throw errors during access (default: true)`,{default:!0}).query()),e(`debugger_session`,e=>e.desc(`Manage debugger sessions. Actions: save (persist current session to file), load (restore session from file/JSON), export (export session as JSON string), list (list saved sessions in ./debugger-sessions/).`).enum(`action`,[`save`,`load`,`export`,`list`],`Session operation`).string(`filePath`,`File path for save/load actions`).string(`sessionData`,`Session JSON string for load action (alternative to filePath)`).object(`metadata`,{},`Optional metadata for save/export actions`).required(`action`))],n=[e(`watch`,e=>e.desc(`Manage watch expressions for monitoring variable values during debugging.
14
+
15
+ Actions:
16
+ - add: Add a watch expression (requires expression)
17
+ - remove: Remove by watchId
18
+ - list: List all watches
19
+ - evaluate_all: Evaluate all enabled watches (optional callFrameId)
20
+ - clear_all: Clear all watches`).enum(`action`,[`add`,`remove`,`list`,`evaluate_all`,`clear_all`],`Watch operation`).string(`expression`,`JavaScript expression to watch (action=add)`).string(`name`,`Friendly name for the watch (action=add)`).string(`watchId`,`Watch expression ID (action=remove)`).string(`callFrameId`,`Call frame ID (action=evaluate_all)`).required(`action`)),e(`blackbox_add`,e=>e.desc(`Blackbox scripts (skip during debugging)
21
+
22
+ Usage:
23
+ - Skip third-party library c...`).string(`urlPattern`,`URL pattern to blackbox (supports wildcards *)`).required(`urlPattern`).idempotent()),e(`blackbox_add_common`,e=>e.desc(`Blackbox all common libraries (one-click)
24
+
25
+ Includes:
26
+ - jquery, react, vue, an...`).idempotent()),e(`blackbox_list`,e=>e.desc(`List script blackbox patterns.`).query())],r=[...t,...n];export{r as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`binary_detect_format`,e=>e.desc(`Detect binary payload format and encoding signals.`).enum(`source`,[`base64`,`hex`,`file`,`raw`],`How to interpret input payload`).string(`data`,`Input payload for base64/hex/raw sources`).string(`filePath`,`File path when source=file`).string(`requestId`,`Captured requestId when a response body is available`).required(`source`).query()),e(`binary_decode`,e=>e.desc(`Decode binary payloads into hex, utf8, or json output.`).string(`data`,`Input encoded payload`).enum(`encoding`,[`base64`,`hex`,`url`,`protobuf`,`msgpack`],`Declared input encoding`).enum(`outputFormat`,[`hex`,`utf8`,`json`],`Target output format`,{default:`hex`}).required(`data`,`encoding`).query()),e(`binary_encode`,e=>e.desc(`Encode utf8/hex/json input into base64/hex/url output.`).string(`data`,`Input payload`).enum(`inputFormat`,[`utf8`,`hex`,`json`],`How to parse input`).enum(`outputEncoding`,[`base64`,`hex`,`url`],`Desired output encoding`).required(`data`,`inputFormat`,`outputEncoding`).query()),e(`binary_entropy_analysis`,e=>e.desc(`Compute entropy and byte frequency for a payload.`).enum(`source`,[`base64`,`hex`,`raw`,`file`],`How to interpret input payload`).string(`data`,`Input payload for base64/hex/raw sources`).string(`filePath`,`File path when source=file`).number(`blockSize`,`Block size for per-block entropy`,{default:256,minimum:16,maximum:8192}).required(`source`).query()),e(`protobuf_decode_raw`,e=>e.desc(`Decode protobuf bytes without a schema.`).string(`data`,`Base64-encoded protobuf payload`).number(`maxDepth`,`Maximum recursive decode depth`,{default:5,minimum:1,maximum:20}).required(`data`).query())];export{t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`process_windows`,e=>e.desc(`Get all window handles for a process.`).number(`pid`,`Process ID to get windows for`).required(`pid`)),e(`process_check_debug_port`,e=>e.desc(`Check if a process has a debug port enabled for CDP attachment.`).number(`pid`,`Process ID to check`).required(`pid`)),e(`process_launch_debug`,e=>e.desc(`Launch an executable with remote debugging port enabled.`).string(`executablePath`,`Full path to the executable to launch`).number(`debugPort`,`Debug port to use`,{default:9222,minimum:1,maximum:65535}).array(`args`,{type:`string`},`Additional command line arguments`).required(`executablePath`)),e(`memory_read`,e=>e.desc(`Read memory from a process at a specific address. Requires elevated privileges.`).number(`pid`,`Target process ID`).string(`address`,`Memory address to read (hex string like "0x12345678")`).number(`size`,`Number of bytes to read`).required(`pid`,`address`,`size`)),e(`memory_write`,e=>e.desc(`Write data to process memory at a given address.`).number(`pid`,`Target process ID`).string(`address`,`Memory address to write to (hex string like "0x12345678")`).string(`data`,`Data to write (hex string or base64)`).enum(`encoding`,[`hex`,`base64`],`Encoding of the data parameter`,{default:`hex`}).required(`pid`,`address`,`data`)),e(`memory_scan`,e=>e.desc(`Scan process memory for a pattern or value. Requires elevated privileges.`).number(`pid`,`Target process ID`).string(`pattern`,`Pattern to search for (hex bytes like "48 8B 05" or value)`).enum(`patternType`,[`hex`,`int32`,`int64`,`float`,`double`,`string`],`Type of pattern to search`,{default:`hex`}).boolean(`suspendTarget`,`Suspend the target process during scan for a consistent memory snapshot (default: false)`,{default:!1}).required(`pid`,`pattern`)),e(`memory_check_protection`,e=>e.desc(`Check memory protection flags at a specific address.`).number(`pid`,`Target process ID`).string(`address`,`Memory address to check (hex string like "0x12345678")`).required(`pid`,`address`)),e(`memory_scan_filtered`,e=>e.desc(`Refine a previous memory scan with filtered addresses.`).number(`pid`,`Target process ID`).string(`pattern`,`Pattern to search for`).array(`addresses`,{type:`string`},`List of addresses to scan within (from previous scan)`).enum(`patternType`,[`hex`,`int32`,`int64`,`float`,`double`,`string`],`Type of pattern to search`,{default:`hex`}).required(`pid`,`pattern`,`addresses`)),e(`memory_batch_write`,e=>e.desc(`Write multiple memory patches at once.`).number(`pid`,`Target process ID`).array(`patches`,{type:`object`,properties:{address:{type:`string`,description:`Memory address (hex)`},data:{type:`string`,description:`Data to write`},encoding:{type:`string`,enum:[`hex`,`base64`],default:`hex`}},required:[`address`,`data`]},`Array of patches to apply`).required(`pid`,`patches`)),e(`memory_dump_region`,e=>e.desc(`Dump a process memory region to a binary file for offline analysis.`).number(`pid`,`Target process ID`).string(`address`,`Start address (hex)`).number(`size`,`Number of bytes to dump`).string(`outputPath`,`Output file path`).required(`pid`,`address`,`size`,`outputPath`)),e(`memory_list_regions`,e=>e.desc(`List all memory regions in a process with protection flags.`).number(`pid`,`Target process ID`).required(`pid`)),e(`memory_audit_export`,e=>e.desc(`Export the in-memory audit trail for memory operations as JSON.`)),e(`inject_dll`,e=>e.desc(`Inject a DLL into a target process.`).number(`pid`,`Target process ID`).string(`dllPath`,`Full path to the DLL file to inject`).required(`pid`,`dllPath`)),e(`inject_shellcode`,e=>e.desc(`Allocate and execute raw shellcode in a target process.`).number(`pid`,`Target process ID`).string(`shellcode`,`Shellcode bytes (hex string or base64)`).enum(`encoding`,[`hex`,`base64`],`Encoding of shellcode`,{default:`hex`}).required(`pid`,`shellcode`)),e(`check_debug_port`,e=>e.desc(`Check if a process is being debugged using NtQueryInformationProcess (ProcessDebugPort).`).number(`pid`,`Target process ID`).required(`pid`)),e(`enumerate_modules`,e=>e.desc(`List all loaded modules (DLLs) in a process with their base addresses.`).number(`pid`,`Target process ID`).required(`pid`)),e(`electron_attach`,e=>e.desc(`Attach to an Electron CDP port and optionally evaluate in a matching page.`).number(`port`,`CDP port to connect to`,{minimum:1,maximum:65535}).string(`pageUrl`,`Optional URL substring used to pick the target page`).string(`evaluate`,`Optional JavaScript expression to evaluate in the selected page`).string(`wsEndpoint`,`Optional browser WebSocket endpoint override`))];export{t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./tool-builder-CI9914Tf.mjs";const t=[e(`create_task_handoff`,e=>e.desc(`Create an in-session task handoff.`).string(`description`,`Task description`).array(`constraints`,{type:`string`},`Constraints for the specialist`).string(`targetDomain`,`Suggested domain for the specialist`).string(`decision`,`Key design decision made in this phase`).array(`risks`,{type:`string`},`Identified risks for the specialist`).array(`nextSteps`,{type:`string`},`Concrete next actions for the specialist`).required(`description`)),e(`complete_task_handoff`,e=>e.desc(`Mark a task handoff as completed.`).string(`taskId`,`Task ID from create_task_handoff`).string(`summary`,`Concise summary of what was accomplished`).array(`keyFindings`,{type:`string`},`Key discoveries or results`).array(`artifacts`,{type:`string`},`Paths to generated artifact files`).required(`taskId`,`summary`)),e(`get_task_context`,e=>e.desc(`Read task handoff context.`).string(`taskId`,`Optional task ID to read a single handoff`).query()),e(`append_session_insight`,e=>e.desc(`Record an insight for the current session.`).string(`category`,`Insight category`).string(`content`,`The insight content`).number(`confidence`,`Confidence level 0.0-1.0`,{minimum:0,maximum:1,default:1}).required(`category`,`content`)),e(`save_page_snapshot`,e=>e.desc(`Save current page state.`).string(`label`,`Human-readable label for this snapshot`).readOnly()),e(`restore_page_snapshot`,e=>e.desc(`Restore a saved page snapshot.`).string(`snapshotId`,`Snapshot ID from save_page_snapshot`).required(`snapshotId`).idempotent()),e(`list_page_snapshots`,e=>e.desc(`List saved page snapshots.`).query())];export{t};
@@ -0,0 +1,2 @@
1
+ import{a as e,n as t,r as n}from"./parse-args-Cuk7-xUt.mjs";import"./definitions-NoVp_9Pm.mjs";import{homedir as r,tmpdir as i}from"node:os";import{isAbsolute as a,resolve as o}from"node:path";import{readFile as s,realpath as c}from"node:fs/promises";function l(e,t,n){let r=[],i=0,a=0;for(;i<e.length;){let o=d(e,i);if(o.error)return{fields:r,bytesConsumed:i,error:o.error};let s=o.value;i=o.offset;let c=Number(s>>3n),l=Number(s&7n);if(c<=0)return{fields:r,bytesConsumed:i,error:`Invalid field number ${c} at offset ${i}`};if(l===0){let t=d(e,i);if(t.error)return{fields:r,bytesConsumed:i,error:t.error};i=t.offset,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:p(t.value)})}else if(l===1){if(i+8>e.length)return{fields:r,bytesConsumed:i,error:`Unexpected EOF for fixed64 at offset ${i}`};let t=e.subarray(i,i+8),n=t.readBigUInt64LE(0);i+=8,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:{uint64:p(n),hex:t.toString(`hex`)}})}else if(l===2){let o=d(e,i);if(o.error)return{fields:r,bytesConsumed:i,error:o.error};i=o.offset;let s=o.value;if(s>BigInt(2**53-1))return{fields:r,bytesConsumed:i,error:`Length-delimited field is too large at offset ${i}`};let p=Number(s);if(p<0||i+p>e.length)return{fields:r,bytesConsumed:i,error:`Invalid length-delimited field length=${p} at offset ${i}`};let m=e.subarray(i,i+p);i+=p,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:u(m,t,n)})}else if(l===5){if(i+4>e.length)return{fields:r,bytesConsumed:i,error:`Unexpected EOF for fixed32 at offset ${i}`};let t=e.subarray(i,i+4),n=t.readUInt32LE(0);i+=4,r.push({index:a,fieldNumber:c,wireType:l,wireTypeName:f(l),value:{uint32:n,hex:t.toString(`hex`)}})}else return{fields:r,bytesConsumed:i,error:`Unsupported wire type ${l} at offset ${i}`};a+=1}return{fields:r,bytesConsumed:i}}function u(e,t,n){if(e.length===0)return{kind:`empty`,length:0};if(t<n){let r=l(e,t+1,n);if(!r.error&&r.bytesConsumed===e.length&&r.fields.length>0)return{kind:`message`,fields:r.fields}}let r=m(e);return r!==null&&h(r)?{kind:`string`,value:r}:{kind:`bytes`,length:e.length,hex:e.toString(`hex`),base64:e.toString(`base64`)}}function d(e,t){let n=0n,r=0n,i=t;for(let t=0;t<10;t+=1){let t=e[i];if(t===void 0)return{error:`Unexpected EOF while parsing varint at offset ${i}`};let a=BigInt(t);if(n|=(a&127n)<<r,i+=1,(a&128n)==0n)return{value:n,offset:i};r+=7n}return{error:`Varint exceeds 10 bytes at offset ${t}`}}function f(e){return e===0?`varint`:e===1?`fixed64`:e===2?`length-delimited`:e===5?`fixed32`:`unknown`}function p(e){let t=BigInt(2**53-1),n=BigInt(-(2**53-1));return e<=t&&e>=n?Number(e):e.toString()}function m(e){let t=e.toString(`utf8`);return(t.match(/\uFFFD/g)??[]).length>0?null:t}function h(e){if(e.length===0)return!0;let t=0;for(let n of e){let e=n.charCodeAt(0);(e>=32&&e<=126||e===9||e===10||e===13)&&(t+=1)}return t/e.length>=.85}function g(e){let t=_(e,0,0);if(t.offset!==e.length)throw Error(`MessagePack decode ended early: consumed ${t.offset} of ${e.length} bytes`);return t.value}function _(e,t,n){if(n>64)throw Error(`MessagePack decode depth exceeds safety limit`);let r=e[t];if(r===void 0)throw Error(`Unexpected EOF at offset ${t}`);let i=t+1;if(r<=127)return{value:r,offset:i};if(r>=224)return{value:r-256,offset:i};if(r>=160&&r<=191){let t=r&31;return x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r>=144&&r<=159){let t=r&15;return v(e,i,t,n+1)}if(r>=128&&r<=143){let t=r&15;return y(e,i,t,n+1)}if(r===192)return{value:null,offset:i};if(r===194)return{value:!1,offset:i};if(r===195)return{value:!0,offset:i};if(r===204)return x(e,i,1),{value:e.readUInt8(i),offset:i+1};if(r===205)return x(e,i,2),{value:e.readUInt16BE(i),offset:i+2};if(r===206)return x(e,i,4),{value:e.readUInt32BE(i),offset:i+4};if(r===207)return x(e,i,8),{value:p(e.readBigUInt64BE(i)),offset:i+8};if(r===208)return x(e,i,1),{value:e.readInt8(i),offset:i+1};if(r===209)return x(e,i,2),{value:e.readInt16BE(i),offset:i+2};if(r===210)return x(e,i,4),{value:e.readInt32BE(i),offset:i+4};if(r===211)return x(e,i,8),{value:p(e.readBigInt64BE(i)),offset:i+8};if(r===202)return x(e,i,4),{value:e.readFloatBE(i),offset:i+4};if(r===203)return x(e,i,8),{value:e.readDoubleBE(i),offset:i+8};if(r===217){x(e,i,1);let t=e.readUInt8(i);return i+=1,x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r===218){x(e,i,2);let t=e.readUInt16BE(i);return i+=2,x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r===219){x(e,i,4);let t=e.readUInt32BE(i);return i+=4,x(e,i,t),{value:e.subarray(i,i+t).toString(`utf8`),offset:i+t}}if(r===196){x(e,i,1);let t=e.readUInt8(i);i+=1,x(e,i,t);let n=e.subarray(i,i+t);return{value:{type:`bytes`,base64:n.toString(`base64`),hex:n.toString(`hex`)},offset:i+t}}if(r===197){x(e,i,2);let t=e.readUInt16BE(i);i+=2,x(e,i,t);let n=e.subarray(i,i+t);return{value:{type:`bytes`,base64:n.toString(`base64`),hex:n.toString(`hex`)},offset:i+t}}if(r===198){x(e,i,4);let t=e.readUInt32BE(i);i+=4,x(e,i,t);let n=e.subarray(i,i+t);return{value:{type:`bytes`,base64:n.toString(`base64`),hex:n.toString(`hex`)},offset:i+t}}if(r===220){x(e,i,2);let t=e.readUInt16BE(i);return i+=2,v(e,i,t,n+1)}if(r===221){x(e,i,4);let t=e.readUInt32BE(i);return i+=4,v(e,i,t,n+1)}if(r===222){x(e,i,2);let t=e.readUInt16BE(i);return i+=2,y(e,i,t,n+1)}if(r===223){x(e,i,4);let t=e.readUInt32BE(i);return i+=4,y(e,i,t,n+1)}if(r>=212&&r<=216){let t={212:1,213:2,214:4,215:8,216:16}[r];x(e,i,1+t);let n=e.readInt8(i),a=e.subarray(i+1,i+1+t);return{value:{type:`ext`,extType:n,base64:a.toString(`base64`),hex:a.toString(`hex`)},offset:i+1+t}}if(r===199||r===200||r===201){let t=r===199?1:r===200?2:4;x(e,i,t);let n=t===1?e.readUInt8(i):t===2?e.readUInt16BE(i):e.readUInt32BE(i);i+=t,x(e,i,1+n);let a=e.readInt8(i),o=e.subarray(i+1,i+1+n);return{value:{type:`ext`,extType:a,base64:o.toString(`base64`),hex:o.toString(`hex`)},offset:i+1+n}}throw Error(`Unsupported MessagePack prefix 0x${r.toString(16)} at offset ${t}`)}function v(e,t,n,r){let i=t,a=[];for(let t=0;t<n;t+=1){let t=_(e,i,r);a.push(t.value),i=t.offset}return{value:a,offset:i}}function y(e,t,n,r){let i=t,a={};for(let t=0;t<n;t+=1){let t=_(e,i,r);i=t.offset;let n=_(e,i,r);i=n.offset;let o=b(t.value);a[o]=n.value}return{value:a,offset:i}}function b(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`bigint`)return e.toString();if(e===null)return`null`;try{return JSON.stringify(e)}catch{return String(e)}}function x(e,t,n){if(t<0||n<0||t+n>e.length)throw Error(`Unexpected EOF while reading ${n} bytes at offset ${t}`)}const S=[{format:`png`,bytes:[137,80,78,71]},{format:`jpeg`,bytes:[255,216,255]},{format:`gif`,bytes:[71,73,70]},{format:`wasm`,bytes:[0,97,115,109]},{format:`zip/apk`,bytes:[80,75,3,4]},{format:`pdf`,bytes:[37,80,68,70]}],C=new Set([`base64`,`hex`,`file`,`raw`]),w=new Set([`base64`,`hex`,`raw`,`file`]),T=new Set([`base64`,`hex`,`url`,`protobuf`,`msgpack`]),E=new Set([`hex`,`utf8`,`json`]),D=new Set([`utf8`,`hex`,`json`]),O=new Set([`base64`,`hex`,`url`]);function k(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function A(e,t){return k({success:!1,tool:e,error:t instanceof Error?t.message:String(t)})}function j(e){let t=e.trim().replace(/^0x/i,``).replace(/[\s:,-]/g,``);if(t.length===0)return Buffer.alloc(0);if(t.length%2!=0||!/^[0-9a-fA-F]+$/.test(t))throw Error(`Invalid hex string`);return Buffer.from(t,`hex`)}function M(e){let t=e.trim().replace(/\s+/g,``);if(t.length===0)return Buffer.alloc(0);if(!F(t))throw Error(`Invalid base64 string`);return Buffer.from(t,`base64`)}function N(e){let t=e.trim();return t.length===0?Buffer.alloc(0):P(t)?j(t):F(t)?M(t):Buffer.from(t,`utf8`)}function P(e){let t=e.trim().replace(/^0x/i,``).replace(/[\s:,-]/g,``);return t.length>0&&t.length%2==0&&/^[0-9a-fA-F]+$/.test(t)}function F(e){let t=e.trim().replace(/\s+/g,``);if(t.length===0||t.length%4!=0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))return!1;try{let e=Buffer.from(t,`base64`);return t.replace(/=+$/,``)===e.toString(`base64`).replace(/=+$/,``)}catch{return!1}}function I(e){return/%[0-9a-fA-F]{2}/.test(e)||/\+/.test(e)}function L(e){return decodeURIComponent(e.replace(/\+/g,`%20`))}function R(e){let t=``;for(let n of e.values())t+=n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===45||n===46||n===95||n===126?String.fromCharCode(n):`%${n.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function z(e){let t=e.toString(`utf8`);return(t.match(/\uFFFD/g)??[]).length>0?null:t}function B(e){try{return JSON.parse(e)}catch{return null}}function V(e,t){return Array.from(e.subarray(0,t).values()).map(e=>e.toString(16).padStart(2,`0`)).join(` `)}function H(e,t=16){let n=[];for(let r=0;r<e.length;r+=t){let i=e.subarray(r,r+t),a=Array.from(i.values()).map(e=>e.toString(16).padStart(2,`0`)).join(` `),o=Array.from(i.values()).map(e=>e>=32&&e<=126?String.fromCharCode(e):`.`).join(``);n.push(`${r.toString(16).padStart(8,`0`)} ${a.padEnd(47)} |${o}|`)}return n.join(`
2
+ `)}function U(e){let{encoding:t,outputFormat:n,buffer:r,jsonValue:i}=e;if(n===`hex`)return k({success:!0,encoding:t,outputFormat:n,byteLength:r.length,result:r.toString(`hex`),hexDump:H(r)});if(n===`utf8`)return k({success:!0,encoding:t,outputFormat:n,byteLength:r.length,result:r.toString(`utf8`)});let a=z(r),o=a===null?null:B(a);return k({success:!0,encoding:t,outputFormat:n,byteLength:r.length,result:i??{parsedJson:o,utf8:a,hex:r.toString(`hex`)}})}async function W(e){let{source:t,data:n,filePath:l,maxBytes:u}=e;if(t===`file`){if(!l)throw Error(`filePath is required when source=file`);let e=await c(o(l));if(!(await Promise.all([i(),r(),process.cwd()].map(async e=>{let t=a(e)?e:o(e);try{return await c(t)}catch{return t}}))).some(t=>e.startsWith(t)))throw Error(`File access denied: path "${l}" is outside allowed directories`);let t=await s(e);return typeof u==`number`?t.subarray(0,u):t}if(t===`base64`){if(!n)throw Error(`data is required for base64 source`);return M(n)}if(t===`hex`){if(!n)throw Error(`data is required for hex source`);return j(n)}return Buffer.from(n??``,`utf8`)}async function G(e,t){try{let n=await(await e.getActivePage()).evaluate(e=>{let t=t=>{if(!t||typeof t!=`object`)return null;let n=t;if(n.requestId!==e)return null;if(typeof n.responseBody==`string`)return{body:n.responseBody,base64Encoded:!!n.base64Encoded};if(typeof n.body==`string`)return{body:n.body,base64Encoded:!!n.base64Encoded};let r=n.response;if(r&&typeof r==`object`){let e=r;if(typeof e.body==`string`)return{body:e.body,base64Encoded:!!e.base64Encoded}}return null},n=e=>{if(!Array.isArray(e))return null;for(let n of e){let e=t(n);if(e)return e}return null},r=n(window.__capturedAPIs);if(r)return r;try{let e=window.localStorage.getItem(`__capturedAPIs`);return e?n(JSON.parse(e)):null}catch{return null}},t);if(!n||typeof n!=`object`)return null;let r=n;if(typeof r.body!=`string`)return null;if(r.base64Encoded)return Buffer.from(r.body,`base64`);let i=r.body.trim();return F(i)?Buffer.from(i,`base64`):Buffer.from(r.body,`utf8`)}catch{return null}}function K(e){let t=[];for(let n of S){if(e.length<n.bytes.length)continue;let r=!0;for(let t=0;t<n.bytes.length;t+=1)if(e[t]!==n.bytes[t]){r=!1;break}r&&t.push(n.format)}return t}function q(e){let t=e[0];if(t===void 0)return[];let n=new Set;return[8,16,24,32].includes(t)&&n.add(`protobuf`),(t>=128&&t<=143||t>=144&&t<=159||t>=160&&t<=191)&&n.add(`messagepack`),(t>=160&&t<=191||t>=128&&t<=159)&&n.add(`cbor`),Array.from(n)}function J(e,t,n){let r=new Set;if((e===`base64`||t&&F(t.trim()))&&r.add(`base64`),(e===`hex`||t&&P(t))&&r.add(`hex`),t&&I(t)&&r.add(`url-encoded`),n.length>=3){let[e,t,i]=n;e===239&&t===187&&i===191&&r.add(`utf8-bom`)}return Array.from(r)}function Y(e){if(e.length===0)return 0;let t=Array.from({length:256},()=>0);for(let n of e.values())t[n]+=1;let n=0;for(let r of t){if(r===0)continue;let t=r/e.length;n-=t*Math.log2(t)}return Number(n.toFixed(6))}function X(e){if(e.length===0)return[];let t=Array.from({length:256},()=>0);for(let n of e.values())t[n]+=1;let n=[];for(let r=0;r<256;r+=1){let i=t[r];i!==0&&n.push({byte:`0x${r.toString(16).padStart(2,`0`)}`,count:i,ratio:Number((i/e.length).toFixed(6))})}return n.sort((e,t)=>t.count-e.count),n}function Z(e,t){if(e.length===0)return[];let n=[],r=0;for(let i=0;i<e.length;i+=t){let a=Math.min(i+t,e.length);n.push({index:r,start:i,end:a,entropy:Y(e.subarray(i,a))}),r+=1}return n}function Q(e,t){let n=$(t);return e<3.8&&n>.85?`plaintext`:e<5.8?`encoded`:e<7.2?`compressed`:e<7.8?`encrypted`:`random`}function $(e){if(e.length===0)return 1;let t=0;for(let n of e.values())(n>=32&&n<=126||n===9||n===10||n===13)&&(t+=1);return t/e.length}var ee=class{collector;responseBodyResolver;constructor(e,t){this.collector=e,this.responseBodyResolver=t}async resolveCapturedRequestBody(e){if(this.responseBodyResolver)try{let t=await this.responseBodyResolver(e);if(t&&typeof t.body==`string`){if(t.base64Encoded)return Buffer.from(t.body,`base64`);let e=t.body.trim();return F(e)?Buffer.from(e,`base64`):Buffer.from(t.body,`utf8`)}}catch{}return G(this.collector,e)}async handleBinaryDetectFormat(n){try{let r=t(n,`source`,C,`raw`),i=e(n,`data`),a=e(n,`filePath`),o=e(n,`requestId`),s=null,c=!1;if(r===`raw`&&o&&(s=await this.resolveCapturedRequestBody(o),c=s!==null),!s){if(r!==`file`&&!i)throw Error(`data is required for non-file source when requestId payload is unavailable`);s=await W({source:r,data:i,filePath:a,maxBytes:r===`file`?512:void 0})}let l=Y(s);return k({success:!0,source:r,requestId:o??null,requestBodyUsed:c,byteLength:s.length,previewHex:V(s,64),magicFormats:K(s),structuredFormats:q(s),encodingSignals:J(r,i,s),entropy:l,assessment:Q(l,s),topBytes:X(s).slice(0,8)})}catch(e){return A(`binary_detect_format`,e)}}async handleBinaryDecode(n){try{let r=e(n,`data`,``),i=t(n,`encoding`,T),a=t(n,`outputFormat`,E,`hex`);if(!r)throw Error(`data is required`);if(!i)throw Error(`encoding is required`);if(i===`url`){let e=L(r);if(a===`hex`){let t=Buffer.from(e,`utf8`);return k({success:!0,encoding:i,outputFormat:a,byteLength:t.length,result:t.toString(`hex`),hexDump:H(t)})}return k(a===`utf8`?{success:!0,encoding:i,outputFormat:a,result:e}:{success:!0,encoding:i,outputFormat:a,result:B(e)??{text:e}})}let o=i===`base64`?M(r):i===`hex`?j(r):N(r);if(i===`protobuf`){let e=l(o,0,5);return U({encoding:i,outputFormat:a,buffer:o,jsonValue:{fields:e.fields,bytesConsumed:e.bytesConsumed,error:e.error??null}})}return U(i===`msgpack`?{encoding:i,outputFormat:a,buffer:o,jsonValue:g(o)}:{encoding:i,outputFormat:a,buffer:o})}catch(e){return A(`binary_decode`,e)}}async handleBinaryEncode(n){try{let r=e(n,`data`,``),i=t(n,`inputFormat`,D,`utf8`),a=t(n,`outputEncoding`,O,`base64`);if(!r)throw Error(`data is required`);let o;if(i===`utf8`)o=Buffer.from(r,`utf8`);else if(i===`hex`)o=j(r);else{let e=JSON.parse(r);o=Buffer.from(JSON.stringify(e),`utf8`)}let s=a===`base64`?o.toString(`base64`):a===`hex`?o.toString(`hex`):R(o);return k({success:!0,inputFormat:i,outputEncoding:a,byteLength:o.length,output:s})}catch(e){return A(`binary_encode`,e)}}async handleBinaryEntropyAnalysis(r){try{let i=t(r,`source`,w,`raw`),a=e(r,`data`),o=e(r,`filePath`);if(i!==`file`&&!a)throw Error(`data is required for non-file source`);let s=n(r,`blockSize`,256),c=Math.max(16,Math.min(8192,Math.trunc(s||256))),l=await W({source:i,data:a,filePath:o}),u=Y(l);return k({success:!0,source:i,byteLength:l.length,blockSize:c,overallEntropy:u,blockEntropies:Z(l,c),byteFrequency:X(l).slice(0,20),assessment:Q(u,l)})}catch(e){return A(`binary_entropy_analysis`,e)}}async handleProtobufDecodeRaw(t){try{let r=e(t,`data`,``);if(!r)throw Error(`data is required`);let i=n(t,`maxDepth`,5),a=Math.max(1,Math.min(20,Math.trunc(i||5))),o=M(r),s=l(o,0,a);return k({success:s.error===void 0,byteLength:o.length,maxDepth:a,parsedBytes:s.bytesConsumed,fields:s.fields,error:s.error??null})}catch(e){return A(`protobuf_decode_raw`,e)}}};export{ee as EncodingToolHandlers};
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./PageController-D9jVkH0i.mjs";import{n,t as r}from"./DOMInspector-BYY_EJ0C.mjs";import{t as i}from"./ScriptManager-fgqiALgj.mjs";var a=e({ensureBrowserCore:()=>c});let o=null;async function s(){return o||=(await import(`./ConsoleMonitor-Dkqc0HNi.mjs`)).ConsoleMonitor,o}async function c(e){e.collector||(e.collector=new n(e.config.puppeteer),e.registerCaches()),e.pageController||=new t(e.collector),e.domInspector||=new r(e.collector),e.scriptManager||=new i(e.collector),e.consoleMonitor||=new(await(s()))(e.collector)}export{a as n,c as t};
@@ -0,0 +1 @@
1
+ var e=class{graph;constructor(e){this.graph=e}getGraph(){return this.graph}addNode(e,t,n){return this.graph.addNode(e,t,n)}addV8Object(e,t){let n=this.graph.addNode(`v8-heap-object`,e.name,{domain:`v8-inspector`,address:e.address,name:e.name});return t&&this.graph.addEdge(t,n.id,`heap-allocates`,{domain:`cross-domain`,relation:`script-allocates-heap-object`}),n}addNetworkRequest(e,t){let n=e.method?`${e.method} ${e.url}`:e.url,r=this.graph.addNode(`network-request`,n,{domain:`network`,requestId:e.requestId,url:e.url,method:e.method??`GET`}),i;return t&&(i=this.graph.getNode(t),this.graph.addEdge(t,r.id,`network-initiated-by`,{domain:`cross-domain`,relation:`heap-initiates-network`})),{node:r,initiatorNode:i}}addCanvasNode(e,t){let n=this.graph.addNode(`canvas-scene-node`,e.label,{domain:`canvas`,nodeId:e.nodeId,label:e.label});return t&&this.graph.addEdge(t,n.id,`canvas-rendered-by`,{domain:`cross-domain`,relation:`heap-creates-canvas-node`}),n}addSyscallEvent(e,t){let n=this.graph.addNode(`syscall-event`,e.syscallName,{domain:`syscall-hook`,pid:e.pid,tid:e.tid,syscallName:e.syscallName,timestamp:e.timestamp});return t&&this.graph.addEdge(t,n.id,`syscall-emitted-by`,{domain:`cross-domain`,relation:`js-triggers-syscall`}),n}addMojoMessage(e,t){let n=this.graph.addNode(`mojo-message`,`${e.interface}:${e.method}`,{domain:`mojo-ipc`,interface:e.interface,method:e.method,timestamp:e.timestamp});return t&&this.graph.addEdge(t,n.id,`mojo-routed-to`,{domain:`cross-domain`,relation:`cdp-routes-to-mojo`}),n}addBinarySymbol(e,t){let n=this.graph.addNode(`binary-symbol`,e.symbolName,{domain:`binary-instrument`,moduleName:e.moduleName,symbolName:e.symbolName,address:e.address});return t&&this.graph.addEdge(t,n.id,`binary-exports`,{domain:`cross-domain`,relation:`js-references-native-symbol`}),n}queryByHeapAddress(e){let t=this.graph.exportJson(),n=[];for(let r of t.nodes){let t=r.metadata.address;typeof t==`string`&&t.includes(e)&&n.push(r.id)}return this.collectConnectedNodes(n)}queryByNetworkUrl(e){return this.graph.queryByUrl(e)}exportGraph(){return this.graph.exportJson()}getStats(){let e=this.graph.exportJson(),t={};for(let n of e.nodes){let e=t[n.type]??0;t[n.type]=e+1}return{nodeCount:e.nodes.length,edgeCount:e.edges.length,nodesByType:t}}collectConnectedNodes(e){let t=new Map;for(let n of e){for(let e of this.graph.getEvidenceChain(n,`forward`))t.set(e.id,e);for(let e of this.graph.getEvidenceChain(n,`backward`))t.set(e.id,e)}return[...t.values()]}};export{e as CrossDomainEvidenceBridge};
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunk-C_pMuVsO.mjs";import{_ as t,b as n,d as r,f as i,h as a,i as o,l as s,m as c,n as l,p as u,s as d,t as f,u as p,v as ee,y as m}from"./Win32API-Bhi5xFBe.mjs";import{_ as h,a as g,b as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,u as te,v as j,y as M}from"./DarwinAPI-DC4HGGLl.mjs";import N from"node:fs";const P=new WeakMap;function F(e){let t=P.get(e);if(t===void 0)throw Error(`Invalid ProcessHandle — not a Win32 handle`);return t}function I(e){let t=0;return e&p.READONLY&&(t|=1),e&p.READWRITE&&(t|=3),e&p.WRITECOPY&&(t|=17),e&p.EXECUTE&&(t|=4),e&p.EXECUTE_READ&&(t|=5),e&p.EXECUTE_READWRITE&&(t|=7),e&p.EXECUTE_WRITECOPY&&(t|=21),e&p.GUARD&&(t|=8),t}function L(e){let t=(e&1)!=0,n=(e&2)!=0,r=(e&4)!=0,i=p.NOACCESS;return t&&n&&r?i=p.EXECUTE_READWRITE:t&&r?i=p.EXECUTE_READ:t&&n?i=p.READWRITE:r?i=p.EXECUTE:t&&(i=p.READONLY),e&8&&(i|=p.GUARD),i}function R(e){return e===s.COMMIT?`committed`:e===s.RESERVE?`reserved`:`free`}function z(e){return e===16777216?`image`:e===262144?`mapped`:e===131072?`private`:`unknown`}var B=class{platform=`win32`;async checkAvailability(){return m()?ee()?{available:!0,platform:`win32`}:{available:!1,reason:`koffi FFI library not available`,platform:`win32`}:{available:!1,reason:`Not running on Windows`,platform:`win32`}}openProcess(e,t){let r=n(e,t),i={pid:e,writeAccess:t};return P.set(i,r),i}closeProcess(e){f(F(e))}readMemory(e,t,n){let i=r(F(e),t,n);return{data:i,bytesRead:i.length}}writeMemory(e,n,r){return{bytesWritten:t(F(e),n,r)}}queryRegion(e,t){let{success:n,info:r}=a(F(e),t);if(!n||r.RegionSize===0n)return null;let i=I(r.Protect);return{baseAddress:r.BaseAddress,size:Number(r.RegionSize),protection:i,state:R(r.State),type:z(r.Type),isReadable:(i&1)!=0,isWritable:(i&2)!=0,isExecutable:(i&4)!=0}}changeProtection(e,t,n,r){let{success:i,oldProtect:a}=c(F(e),t,n,L(r));if(!i)throw Error(`VirtualProtectEx failed`);return{oldProtection:I(a)}}allocateMemory(e,t,n){let r=F(e),a=L(n),o=i(r,0n,t,s.COMMIT|s.RESERVE,a);if(!o)throw Error(`VirtualAllocEx failed`);return{address:o}}freeMemory(e,t,n){u(F(e),t,0,s.RELEASE)}enumerateModules(e){let t=F(e),{success:n,modules:r,count:i}=l(t);if(!n)throw Error(`EnumProcessModules failed`);let a=[];for(let e=0;e<i;e++){let n=r[e];if(!n)continue;let i=o(t,n),{success:s,info:c}=d(t,n);s&&c&&a.push({name:i,baseAddress:BigInt(c.lpBaseOfDll),size:c.SizeOfImage})}return a}};const V=new WeakMap;function H(e){let t=V.get(e);if(t===void 0)throw Error(`Invalid ProcessHandle — not a Darwin handle`);return t}function U(e){let t=0;return e&g.READ&&(t|=1),e&g.WRITE&&(t|=2),e&g.EXECUTE&&(t|=4),t}function W(e){let t=g.NONE;return e&1&&(t|=g.READ),e&2&&(t|=g.WRITE),e&4&&(t|=g.EXECUTE),t}function G(e){switch(e){case k.PRIVATE:case k.PRIVATE_ALIASED:case k.COW:return`private`;case k.SHARED:case k.TRUESHARED:case k.SHARED_ALIASED:return`mapped`;case k.EMPTY:return`unknown`;default:return`unknown`}}var K=class{platform=`darwin`;async checkAvailability(){if(!w())return{available:!1,reason:`Not running on macOS`,platform:`darwin`};if(!te())return{available:!1,reason:`koffi FFI library cannot load libSystem.B.dylib`,platform:`darwin`};try{let{kr:e}=_(O(),process.pid);if(e!==E.SUCCESS)return{available:!1,reason:`task_for_pid failed (${y(e)}). Run with sudo or add debugger entitlement.`,platform:`darwin`}}catch(e){let t=e instanceof Error?e.message:String(e);return{available:!1,reason:/signal|bus error|segfault|abort/i.test(t)?`Mach API call crashed (${t}). This may be caused by SIP (System Integrity Protection) on ARM64 macOS. Disable SIP or use a code-signed binary with com.apple.security.cs.debugger entitlement.`:`task_for_pid permission check failed: ${t}. Run with sudo or add debugger entitlement.`,platform:`darwin`}}return{available:!0,platform:`darwin`}}openProcess(e,t){let{kr:n,task:r}=_(O(),e);if(n!==E.SUCCESS)throw Error(`Failed to open process ${e}: ${y(n)} (${n}). `+(n===E.FAILURE?`Run with sudo or sign with com.apple.security.cs.debugger entitlement.`:n===E.INVALID_ARGUMENT?`Invalid PID — process may not exist.`:`Check macOS permissions.`));let i={pid:e,writeAccess:t};return V.set(i,{task:r}),i}closeProcess(e){let t=H(e);b(O(),t.task)}readMemory(e,t,n){let{kr:r,data:i,outsize:a}=h(H(e).task,t,n);if(r!==E.SUCCESS)throw Error(`mach_vm_read_overwrite failed at 0x${t.toString(16)}: ${y(r)} (${r})`);return{data:i,bytesRead:Number(a)}}writeMemory(e,t,n){let r=M(H(e).task,t,n);if(r!==E.SUCCESS)throw Error(`mach_vm_write failed at 0x${t.toString(16)}: ${y(r)} (${r})`);return{bytesWritten:n.length}}queryRegion(e,t){let{kr:n,address:r,size:i,info:a}=j(H(e).task,t);if(n!==E.SUCCESS)return null;let o=U(a.protection);return{baseAddress:r,size:Number(i),protection:o,state:`committed`,type:G(a.behavior),isReadable:(o&1)!=0,isWritable:(o&2)!=0,isExecutable:(o&4)!=0}}changeProtection(e,t,n,r){let i=H(e),a=W(r),{kr:o,info:s}=j(i.task,t),c=o===E.SUCCESS?U(s.protection):0;if((a&g.WRITE)!==0&&(a&g.EXECUTE)!==0){let e=x(i.task,t,BigInt(n),!0,g.ALL);if(e!==E.SUCCESS)throw Error(`mach_vm_protect (set_maximum) failed at 0x${t.toString(16)}: ${y(e)} (${e})`)}let l=x(i.task,t,BigInt(n),!1,a);if(l!==E.SUCCESS)throw Error(`mach_vm_protect failed at 0x${t.toString(16)}: ${y(l)} (${l})`);return{oldProtection:c}}allocateMemory(e,t,n){let r=H(e),{kr:i,address:a}=T(r.task,BigInt(t),C.ANYWHERE);if(i!==E.SUCCESS)throw Error(`mach_vm_allocate failed: ${y(i)} (${i})`);let o=W(n);if(o!==(g.READ|g.WRITE)){let e=x(r.task,a,BigInt(t),!1,o);if(e!==E.SUCCESS)throw S(r.task,a,BigInt(t)),Error(`mach_vm_protect after allocate failed: ${y(e)} (${e})`)}return{address:a}}freeMemory(e,t,n){let r=S(H(e).task,t,BigInt(n));if(r!==E.SUCCESS)throw Error(`mach_vm_deallocate failed at 0x${t.toString(16)}: ${y(r)} (${r})`)}enumerateModules(e){let t=H(e);return e.pid===process.pid?this.enumerateModulesSelf():this.enumerateModulesRemote(t.task)}enumerateModulesSelf(){let e=v(),t=[];for(let n=0;n<e;n++){let e=A(n),r=D(n);if(!e||r===0n)continue;let i=e.split(`/`).pop()??e;t.push({name:i,baseAddress:r,size:0})}return t}enumerateModulesRemote(e){let t=[],n=0n;for(let r=0;r<1e4;r++){let{kr:r,address:i,size:a,info:o}=j(e,n);if(r!==E.SUCCESS)break;let s=(o.protection&g.READ)!==0,c=(o.protection&g.EXECUTE)!==0;if(s&&c&&a>0n)try{let{kr:n,data:r}=h(e,i,4);if(n===E.SUCCESS&&r.length>=4){let e=r.readUInt32LE(0);(e===4277009103||e===4277009102)&&t.push({name:`module_0x${i.toString(16)}`,baseAddress:i,size:Number(a)})}}catch{}n=i+a}return t}};const q=/^([0-9a-f]+)-([0-9a-f]+)\s+([r-][w-][x-][ps])\s+([0-9a-f]+)\s+(\S+)\s+(\d+)\s*(.*)$/i;function J(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trimEnd().match(q);if(!e)continue;let r=e[3];t.push({start:BigInt(`0x${e[1]}`),end:BigInt(`0x${e[2]}`),permissions:{read:r[0]===`r`,write:r[1]===`w`,exec:r[2]===`x`,private:r[3]===`p`},offset:BigInt(`0x${e[4]}`),dev:e[5],inode:parseInt(e[6],10),pathname:e[7]?.trim()??``})}return t}function Y(e){return`${e.read?`r`:`-`}${e.write?`w`:`-`}${e.exec?`x`:`-`}`}function X(){return process.platform===`linux`}function Z(e){let t=0;return e.includes(`r`)&&(t|=1),e.includes(`w`)&&(t|=2),e.includes(`x`)&&(t|=4),t}function ne(e){let t=Z(e.perms);return{baseAddress:e.start,size:Number(e.end-e.start),protection:t,state:`committed`,type:e.path?`mapped`:`private`,isReadable:(t&1)!=0,isWritable:(t&2)!=0,isExecutable:(t&4)!=0}}function re(e){return Buffer.isBuffer(e)?e:e.startsWith(`0x`)&&e.length%2==0?Buffer.from(e.slice(2),`hex`):Buffer.from(e,`utf8`)}var ie=class{pid;platform=`linux`;constructor(e=process.pid){this.pid=e}isAvailable(){return X()}async read(e,t){let n=this.openProcess(this.pid,!1);return this.readMemory(n,e,t).data}async write(e,t){let n=this.openProcess(this.pid,!0);return this.writeMemory(n,e,t).bytesWritten===t.length}async scan(e){let t=re(e),n=this.openProcess(this.pid,!1),r=await this.queryRegions(),i=[];for(let e of r){if(!e.perms.includes(`r`))continue;let r=Number(e.end-e.start);if(!(r<=0))try{let a=this.readMemory(n,e.start,r).data,o=a.indexOf(t);for(;o>=0;)i.push(e.start+BigInt(o)),o=a.indexOf(t,o+1)}catch{continue}}return i}async queryRegions(){let e=`/proc/${this.pid}/maps`;return J(await N.promises.readFile(e,`utf8`)).map(e=>({start:e.start,end:e.end,perms:`${e.permissions.read?`r`:`-`}${e.permissions.write?`w`:`-`}${e.permissions.exec?`x`:`-`}${e.permissions.private?`p`:`s`}`,path:e.pathname||void 0}))}async checkAvailability(){return this.isAvailable()?{available:!0,platform:`linux`}:{available:!1,platform:`linux`,reason:`Not running on Linux`}}openProcess(e,t){return{pid:e,writeAccess:t}}closeProcess(e){}readMemory(e,t,n){let r=`/proc/${e.pid}/mem`,i=N.openSync(r,e.writeAccess?`r+`:`r`),a=Buffer.alloc(n);try{let e=N.readSync(i,a,0,n,Number(t));return{data:a.subarray(0,e),bytesRead:e}}finally{N.closeSync(i)}}writeMemory(e,t,n){let r=`/proc/${e.pid}/mem`,i=N.openSync(r,`r+`);try{return{bytesWritten:N.writeSync(i,n,0,n.length,Number(t))}}finally{N.closeSync(i)}}queryRegion(e,t){let n=`/proc/${e.pid}/maps`,r=J(N.readFileSync(n,`utf8`));for(let e of r)if(t>=e.start&&t<e.end)return ne({start:e.start,end:e.end,perms:`${e.permissions.read?`r`:`-`}${e.permissions.write?`w`:`-`}${e.permissions.exec?`x`:`-`}${e.permissions.private?`p`:`s`}`,path:e.pathname||void 0});return null}changeProtection(e,t,n,r){throw Error(`Linux memory protection changes are not supported by LinuxMemoryProviderImpl`)}allocateMemory(e,t,n){throw Error(`Linux remote memory allocation is not supported by LinuxMemoryProviderImpl`)}freeMemory(e,t,n){throw Error(`Linux remote memory free is not supported by LinuxMemoryProviderImpl`)}enumerateModules(e){let t=`/proc/${e.pid}/maps`,n=J(N.readFileSync(t,`utf8`)),r=new Map;for(let e of n){if(!e.pathname||e.pathname.startsWith(`[`))continue;let t=r.get(e.pathname);if(t){let n=Number(e.end-t.baseAddress);r.set(e.pathname,{...t,size:n>t.size?n:t.size});continue}r.set(e.pathname,{name:e.pathname.split(`/`).pop()??e.pathname,baseAddress:e.start,size:Number(e.end-e.start)})}return[...r.values()]}},ae=class extends ie{},oe=e({createPlatformProvider:()=>$});let Q=null;function $(){if(Q)return Q;switch(process.platform){case`win32`:Q=new B;break;case`darwin`:Q=new K;break;case`linux`:Q=new ae;break;default:throw Error(`Unsupported platform: ${process.platform}. Memory operations require Windows, macOS, or Linux.`)}if(!Q)throw Error(`Failed to create memory provider`);return Q}export{J as i,oe as n,Y as r,$ as t};
@@ -0,0 +1 @@
1
+ function e(e){if(typeof e!=`object`||!e)return null;let t=e.sessionId;return typeof t==`string`&&t.length>0?t:null}function t(e){let t=e.id?.();return typeof t==`string`&&t.length>0?t:null}async function n(t,n){let r=e(await t.send(`Target.attachToTarget`,{targetId:n,flatten:!0}));if(!r)throw Error(`Target.attachToTarget did not return sessionId for ${n}`);let i=t.connection?.();if(!i||typeof i.session!=`function`)throw Error(`CDP connection lookup unavailable for attached target ${n}`);let a=i.session(r);if(!a)throw Error(`CDP attached target session ${r} was not registered for ${n}`);return a}async function r(e,n){let r=t(n);if(!r)throw Error(`CDP attached target session id unavailable for detach`);await e.send(`Target.detachFromTarget`,{sessionId:r})}export{r as n,n as t};
@@ -0,0 +1 @@
1
+ function e(e){return`0x${e.toString(16).toUpperCase()}`}function t(e){return BigInt(e.startsWith(`0x`)||e.startsWith(`0X`)?e:`0x${e}`)}export{t as n,e as t};
@@ -0,0 +1,62 @@
1
+ import{at as e,it as t,nt as n,rt as r,tt as i}from"./constants-Cp6hBrrx.mjs";import{t as a}from"./ToolError-DWU_z7gp.mjs";import{t as o}from"./PrerequisiteError-Bl3dK8XA.mjs";import{a as s,i as c,r as l,t as u}from"./parse-args-Cuk7-xUt.mjs";import{s as d}from"./PageController-D9jVkH0i.mjs";import{c as f}from"./ssrf-policy-T96MR3r6.mjs";import"./definitions-DI9YXsJk.mjs";function p(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function m(e,t){let n={success:!1,error:h(e)};e instanceof a&&(n.code=e.code,e.toolName&&(n.toolName=e.toolName),e.details&&(n.details=e.details)),t&&(n.context=t);let r=e instanceof o;return{content:[{type:`text`,text:JSON.stringify(n,null,2)}],...r?{}:{isError:!0}}}function h(e){return e instanceof Error?e.message:String(e)}function g(e,t,n,r,i){let a=e[t],o=n;if(typeof a==`number`&&Number.isFinite(a))o=a;else if(typeof a==`string`){let e=Number(a);Number.isFinite(e)&&(o=e)}return o<r?r:o>i?i:Math.trunc(o)}function _(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=new Set([`__proto__`,`constructor`,`prototype`]),n=Object.create(null);for(let[r,i]of Object.entries(e))t.has(r)||(typeof i==`string`?n[r]=i:(typeof i==`number`||typeof i==`boolean`)&&(n[r]=String(i)));return n}function v(e){let t;try{t=new URL(e)}catch{return{error:`Invalid endpoint URL: ${e}`}}return t.protocol!==`http:`&&t.protocol!==`https:`?{error:`Unsupported endpoint protocol: ${t.protocol} — only http/https allowed`}:{parsedEndpoint:t}}async function y(e){let t=v(e);return`error`in t?t.error:await f(t.parsedEndpoint.toString())?`Blocked: endpoint "${e}" resolves to a private/reserved address`:null}async function b(e,t){let n=v(e);if(`error`in n)return n.error;if(!await f(n.parsedEndpoint.toString()))return null;if(typeof t==`string`&&t.length>0)try{if(new URL(t).origin===n.parsedEndpoint.origin)return null}catch{}return`Blocked: endpoint "${e}" resolves to a private/reserved address`}function x(e,t){return e.length<=t?{preview:e,truncated:!1,totalLength:e.length}:{preview:`${e.slice(0,t)}\n... (truncated)`,truncated:!0,totalLength:e.length}}function S(e,t){let n;if(typeof e==`string`)n=e;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}return x(n,t)}function ee(e){return e===`exact`||e===`contains`||e===`regex`?e:`contains`}function C(){return`script_rule_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function w(e){if(typeof e.isInterceptResolutionHandled!=`function`)return!1;try{return e.isInterceptResolutionHandled()}catch{return!1}}async function T(e){if(!w(e))try{await e.continue()}catch{}}function te(e,t){if(e.matchType===`exact`)return t===e.url;if(e.matchType===`contains`)return t.includes(e.url);try{return new RegExp(e.url).test(t)}catch{return!1}}function E(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r&&te(r,t))return r}return null}async function D(e,t){if(w(t))return;if(t.resourceType()!==`script`){await T(t);return}let n=E(e,t.url());if(!n){await T(t);return}n.hits+=1;try{await t.respond({status:200,contentType:`application/javascript; charset=utf-8`,headers:{"cache-control":`no-store`,"x-script-replaced-by":`script_replace_persist`},body:n.replacement})}catch{await T(t)}}async function ne(e,t,n){if(t.has(n))return;await n.setRequestInterception(!0);let r=t=>{D(e,t)},i=n;typeof i.prependListener==`function`?i.prependListener(`request`,r):i.on(`request`,r),t.add(n)}function O(e){let t=[`kind`,`name`];return e>0&&t.push(`ofType { ${O(e-1)} }`),t.join(`
2
+ `)}const k=`
3
+ query IntrospectionQuery {
4
+ __schema {
5
+ queryType { name }
6
+ mutationType { name }
7
+ subscriptionType { name }
8
+ types { ...FullType }
9
+ directives {
10
+ name
11
+ description
12
+ locations
13
+ args(includeDeprecated: true) { ...InputValue }
14
+ }
15
+ }
16
+ }
17
+ fragment FullType on __Type {
18
+ kind
19
+ name
20
+ description
21
+ fields(includeDeprecated: true) {
22
+ name
23
+ description
24
+ args(includeDeprecated: true) { ...InputValue }
25
+ type { ...TypeRef }
26
+ isDeprecated
27
+ deprecationReason
28
+ }
29
+ inputFields(includeDeprecated: true) { ...InputValue }
30
+ interfaces { ...TypeRef }
31
+ enumValues(includeDeprecated: true) {
32
+ name
33
+ description
34
+ isDeprecated
35
+ deprecationReason
36
+ }
37
+ possibleTypes { ...TypeRef }
38
+ }
39
+ fragment InputValue on __InputValue {
40
+ name
41
+ description
42
+ type { ...TypeRef }
43
+ defaultValue
44
+ isDeprecated
45
+ deprecationReason
46
+ }
47
+ fragment TypeRef on __Type {
48
+ ${O(7)}
49
+ }
50
+ `.trim();var A=class{collector;constructor(e){this.collector=e}async handleCallGraphAnalyze(e){try{let t=g(e,`maxDepth`,5,1,20),r=s(e,`filterPattern`)?.trim()||``;if(r)try{RegExp(r)}catch(e){return m(`Invalid filterPattern regex`,{filterPattern:r,reason:e instanceof Error?e.message:String(e)})}let a=await d(await this.collector.getActivePage(),({maxDepth:e,filterPattern:t})=>{let n=window,r=new Map,i=new Map,a=0,o=0,s=t?new RegExp(t):null,c=e=>s?(s.lastIndex=0,s.test(e)):!0,l=(e,t)=>s?c(e)||c(t):!0,u=(e,t=1)=>{let n=i.get(e);if(n){n.callCount+=t;return}i.set(e,{id:e,name:e,callCount:t})},d=(e,t)=>{let n=typeof e==`string`&&e.trim()||``,i=typeof t==`string`&&t.trim()||``;if(!n||!i||n===i||!l(n,i))return;let a=`${n}__->__${i}`,o=r.get(a);o?o.count+=1:r.set(a,{source:n,target:i,count:1}),u(n,1),u(i,1)},f=(t,n)=>{a+=1;let r=t.callee??t.functionName??t.fn??t.name??t.method??t.target??n,i=typeof r==`string`&&r.trim()||n,s=t.caller??t.parent??t.from??``,c=typeof s==`string`&&s.trim()||``,l=!1;c&&i&&(d(c,i),l=!0);let u=t.stack??t.stackTrace??t.trace,f=typeof u==`string`&&u.trim().length>0?u.split(`
51
+ `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>{let t=e.match(/at\s+([^(<\s]+)/);if(t?.[1])return t[1];let n=e.match(/^([^(<\s]+)@/);return n?.[1]?n[1]:``}).filter(e=>e.length>0):[];if(f.length>1){let t=Math.min(e,f.length-1);for(let e=0;e<t;e+=1)d(f[e+1],f[e]);l=!0}else f.length===1&&i&&f[0]!==i&&(d(f[0],i),l=!0);l&&(o+=1)},p=n.__aiHooks;if(p&&typeof p==`object`){for(let[e,t]of Object.entries(p))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}for(let e of[`__functionTraceRecords`,`__functionTracerRecords`,`__functionCalls`,`__callTrace`,`__traceCalls`]){let t=n[e];if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}let m=n.__functionTracer;if(m&&typeof m==`object`){let e=m.records;if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&f(t,`functionTracer.records`)}let h=Array.from(i.values()).toSorted((e,t)=>t.callCount-e.callCount),g=Array.from(r.values()).toSorted((e,t)=>t.count-e.count);return{nodes:h,edges:g,stats:{scannedRecords:a,acceptedRecords:o,nodeCount:h.length,edgeCount:g.length,maxDepth:e,filterPattern:t||null}}},{maxDepth:t,filterPattern:r}),o=a.nodes.length>n,c=a.edges.length>i;return p({success:!0,nodes:a.nodes.slice(0,n),edges:a.edges.slice(0,i),stats:{...a.stats,nodesReturned:Math.min(a.nodes.length,n),edgesReturned:Math.min(a.edges.length,i),nodesTruncated:o,edgesTruncated:c}})}catch(e){return m(e)}}},j=class{collector;scriptReplaceRules=[];interceptionInstalledPages=new WeakSet;constructor(e){this.collector=e}async handleScriptReplacePersist(e){try{let t=s(e,`url`)?.trim(),n=s(e,`replacement`),i=ee(e.matchType);if(!t)return m(`Missing required argument: url`);if(typeof n!=`string`||n.length===0)return m(`Missing required argument: replacement`);if(i===`regex`)try{RegExp(t)}catch(e){return m(`Invalid regex in url for matchType=regex`,{url:t,reason:h(e)})}let a=await this.collector.getActivePage(),o={id:C(),url:t,replacement:n,matchType:i,createdAt:Date.now(),hits:0};this.scriptReplaceRules.push(o),await ne(this.scriptReplaceRules,this.interceptionInstalledPages,a),await a.evaluateOnNewDocument(e=>{let t=window,n=`__scriptReplacePersistRules`,r=(Array.isArray(t[n])?t[n]:[]).filter(t=>t&&t.id!==e.id);r.push(e),t[n]=r},{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt});let c=x(n,r);return p({success:!0,message:`Script replacement rule registered and interception enabled`,rule:{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt},replacement:{length:n.length,preview:c.preview,truncated:c.truncated},activeRuleCount:this.scriptReplaceRules.length})}catch(e){return m(e)}}},re=class{collector;constructor(e){this.collector=e}async handleGraphqlIntrospect(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),r=await b(t,typeof e.url==`function`?e.url():null);return r?m(r):await this.introspectViaBrowser(e,t,n)}let r=await y(t);return r?m(r):await this.introspectViaNode(t,n)}catch(e){return m(e)}}async introspectViaNode(t,n){let r={"content-type":`application/json`,...n},i,a;try{let e=new AbortController,n=setTimeout(()=>e.abort(),1e4);try{i=await fetch(t,{method:`POST`,headers:r,body:JSON.stringify({query:k,operationName:`IntrospectionQuery`}),signal:e.signal}),a=await i.text()}finally{clearTimeout(n)}}catch(e){return p({success:!1,endpoint:t,status:0,statusText:`FETCH_ERROR`,error:e instanceof Error?e.message:String(e)})}let o={};i.headers.forEach((e,t)=>{o[t]=e});let s=null;try{s=JSON.parse(a)}catch{}if(a=``,!i.ok&&!s)return p({success:!1,endpoint:t,status:i.status,statusText:i.statusText,error:`Introspection request failed`});let c=s&&typeof s==`object`?s:null,l=c&&`data`in c?c.data:s,u=s!=null&&l!==void 0?S(l,e):{preview:``,truncated:!1,totalLength:0},d={success:i.ok,endpoint:t,status:i.status,statusText:i.statusText,schemaLength:u.totalLength,schemaPreview:u.preview,schemaTruncated:u.truncated,responseHeaders:o};return u.truncated||(d.schema=l),c&&Array.isArray(c.errors)&&(d.errors=c.errors),p(d)}async introspectViaBrowser(t,n,i){let a=await d(t,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,operationName:`IntrospectionQuery`}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o={};a.headers.forEach((e,t)=>{o[t]=e});let s=i.length,c=null;try{c=JSON.parse(i)}catch{}let l=c===null?i:``;return i=``,{ok:a.ok,status:a.status,statusText:a.statusText,responseHeaders:o,totalLength:s,preview:l,truncated:!1,json:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseHeaders:{},totalLength:0,preview:``,truncated:!1,json:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:n,headers:i,query:k,maxSchemaChars:e});if(!a.ok&&!a.json)return p({success:!1,endpoint:n,status:a.status,statusText:a.statusText,error:a.error??`Introspection request failed`,responsePreview:x(a.preview||``,r)});let o=a.json&&typeof a.json==`object`?a.json:null,s=o&&`data`in o?o.data:a.json,c=a.json!==null&&a.json!==void 0&&s!==void 0?S(s,e):{preview:a.preview??``,truncated:a.truncated??!1,totalLength:a.totalLength??0},l={success:a.ok,endpoint:n,status:a.status,statusText:a.statusText,schemaLength:c.totalLength,schemaPreview:c.preview,schemaTruncated:c.truncated,responseHeaders:a.responseHeaders??{}};return c.truncated||(l.schema=s),o&&Array.isArray(o.errors)&&(l.errors=o.errors),a.error&&(l.error=a.error),p(l)}};function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e,t,n){if(!t)return;let r=t.query;if(typeof r!=`string`||r.trim().length===0)return;let i=t.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;e.push({source:n.source,url:n.url,method:n.method,operationName:a,query:r,variables:t.variables??null,timestamp:n.timestamp,contentType:n.contentType})}function P(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(M(e))return e}catch{}if(t.includes(`query=`))try{let e=new URLSearchParams(t),n=e.get(`query`);if(n){let t=e.get(`operationName`),r=e.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:t,variables:i}}}catch{}return t.startsWith(`query `)||t.startsWith(`mutation `)||t.startsWith(`subscription `)?{query:t}:null}function F(e){return M(e.headers)?e.headers:M(e.requestHeaders)?e.requestHeaders:{}}function I(e){let t=F(e);for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`content-type`)return typeof n==`string`?n.toLowerCase():String(n).toLowerCase();return``}function L(e){let t=[e.body,e.postData];return M(e.options)&&t.push(e.options.body),M(e.request)&&t.push(e.request.postData),t}function R(e,t){let n={scannedRecords:0,extracted:[]};if(!Array.isArray(e))return n;for(let r of e){if(!M(r))continue;n.scannedRecords+=1;let e=typeof r.url==`string`?r.url:``,i=typeof r.method==`string`?r.method:`POST`,a=typeof r.timestamp==`number`?r.timestamp:null,o=I(r);for(let s of L(r)){let r=null;M(s)?r=s:typeof s==`string`&&(r=P(s)),N(n.extracted,r,{source:t,url:e,method:i,timestamp:a,contentType:o})}o.includes(`application/graphql`)&&typeof r.body==`string`&&N(n.extracted,{query:r.body,variables:null,operationName:null},{source:t,url:e,method:i,timestamp:a,contentType:o})}return n}function z(e){let t=e.toSorted((e,t)=>(t.timestamp??0)-(e.timestamp??0)),n=[],r=new Set;for(let e of t){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;r.has(t)||(r.add(t),n.push(e))}return n}var B=class{deps;constructor(e){this.deps=`collector`in e?e:{collector:e}}async handleGraphqlExtractQueries(e){try{let n=g(e,`limit`,50,1,200),i=await d(await this.deps.collector.getActivePage(),e=>{let t=window,n=[],r=0,i=(e,t)=>{if(!e)return;let r=e.query;if(typeof r!=`string`||r.trim().length===0)return;let i=e.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;n.push({source:t.source,url:t.url,method:t.method,operationName:a,query:r,variables:e.variables??null,timestamp:t.timestamp,contentType:t.contentType})},a=e=>{if(!e)return null;try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}if(e.includes(`query=`))try{let t=new URLSearchParams(e),n=t.get(`query`);if(n){let e=t.get(`operationName`),r=t.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:e,variables:i}}}catch{}return e.startsWith(`query `)||e.startsWith(`mutation `)||e.startsWith(`subscription `)?{query:e}:null},o=(e,t)=>{r+=1;let n=typeof e.url==`string`?e.url:``,o=typeof e.method==`string`?e.method:`POST`,s=typeof e.timestamp==`number`?e.timestamp:null,c=(e.headers&&typeof e.headers==`object`&&!Array.isArray(e.headers)?e.headers:null)??(e.requestHeaders&&typeof e.requestHeaders==`object`&&!Array.isArray(e.requestHeaders)?e.requestHeaders:null)??{},l=``;for(let[e,t]of Object.entries(c))if(e.toLowerCase()===`content-type`){l=typeof t==`string`?t:String(t);break}l=l.toLowerCase();let u=[e.body,e.postData];e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&u.push(e.options.body);for(let e of u){let r=null;e&&typeof e==`object`&&!Array.isArray(e)?r=e:typeof e==`string`&&(r=a(e)),i(r,{source:t,url:n,method:o,timestamp:s,contentType:l})}l.includes(`application/graphql`)&&typeof e.body==`string`&&i({query:e.body,variables:null,operationName:null},{source:t,url:n,method:o,timestamp:s,contentType:l})},s=(e,t)=>{if(Array.isArray(e))for(let n of e)n&&typeof n==`object`&&o(n,t)},c=Array.isArray(t.__fetchRequests)?t.__fetchRequests:typeof t.__getFetchRequests==`function`?t.__getFetchRequests():void 0,l=Array.isArray(t.__xhrRequests)?t.__xhrRequests:typeof t.__getXHRRequests==`function`?t.__getXHRRequests():void 0;s(c,`window.__fetchRequests`),s(l,`window.__xhrRequests`),s(t.__networkRequests,`window.__networkRequests`);let u=t.__aiHooks;if(u&&typeof u==`object`){for(let[e,t]of Object.entries(u))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&o(n,`window.__aiHooks.${e}`)}n.sort((e,t)=>(t.timestamp??0)-(e.timestamp??0));let d=[],f=new Set;for(let e of n){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;f.has(t)||(f.add(t),d.push(e))}return{scannedRecords:r,totalExtracted:d.length,extracted:d.slice(0,e)}},n),a=i.scannedRecords,o=[...i.extracted];if(this.deps.consoleMonitor){let e=typeof this.deps.consoleMonitor.getFetchRequests==`function`?this.deps.consoleMonitor.getFetchRequests().catch(()=>[]):Promise.resolve([]),t=typeof this.deps.consoleMonitor.getXHRRequests==`function`?this.deps.consoleMonitor.getXHRRequests().catch(()=>[]):Promise.resolve([]),[n,r]=await Promise.all([e,t]),i=[];try{i=typeof this.deps.consoleMonitor.getNetworkRequests==`function`?this.deps.consoleMonitor.getNetworkRequests({limit:500}):[]}catch{i=[]}let s=[R(n,`consoleMonitor.fetchRequests`),R(r,`consoleMonitor.xhrRequests`),R(i,`consoleMonitor.networkRequests`)];for(let e of s)a+=e.scannedRecords,o.push(...e.extracted)}let s=z(o),c=Math.max(i.totalExtracted,s.length),l=s.slice(0,n).map((e,n)=>{let i=x(e.query,t),a=S(e.variables,r),o={index:n,source:e.source,url:e.url,method:e.method,operationName:e.operationName,contentType:e.contentType,timestamp:e.timestamp,queryLength:e.query.length,queryPreview:i.preview,queryTruncated:i.truncated};return i.truncated||(o.query=e.query),a.truncated?(o.variablesPreview=a.preview,o.variablesTruncated=!0):o.variables=e.variables,o});return p({success:!0,limit:n,stats:{scannedRecords:a,totalExtracted:c,returned:l.length},queries:l})}catch(e){return m(e)}}},V=class{collector;constructor(e){this.collector=e}async handleGraphqlReplay(e){try{let t=s(e,`endpoint`)?.trim(),n=s(e,`query`);if(!t)return m(`Missing required argument: endpoint`);if(typeof n!=`string`||n.trim().length===0)return m(`Missing required argument: query`);let r=c(e,`variables`)??{},i=s(e,`operationName`),a=i&&i.trim().length>0?i.trim():null,o=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),i=await b(t,typeof e.url==`function`?e.url():null);return i?m(i):await this.replayViaBrowser(e,t,n,r,a,o)}let l=await y(t);return l?m(l):await this.replayViaNode(t,n,r,a,o)}catch(e){return m(e)}}async replayViaNode(e,t,n,r,i){let a={"content-type":`application/json`,...i},o,s;try{let i=new AbortController,c=setTimeout(()=>i.abort(),1e4);try{o=await fetch(e,{method:`POST`,headers:a,body:JSON.stringify({query:t,variables:n,operationName:r}),signal:i.signal}),s=await o.text()}finally{clearTimeout(c)}}catch(t){return p({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,error:t instanceof Error?t.message:String(t),operationName:r})}let c={};o.headers.forEach((e,t)=>{c[t]=e});let l=null;try{l=JSON.parse(s)}catch{l=null}return s=``,p(H(l,e,r,o.ok,o.status,o.statusText,c))}async replayViaBrowser(t,n,r,i,a,o){let s=await d(t,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,variables:e.variables,operationName:e.operationName}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o=null;try{o=JSON.parse(i)}catch{o=null}let s=o===null?i:``;i=``;let c={};return a.headers.forEach((e,t)=>{c[t]=e}),{ok:a.ok,status:a.status,statusText:a.statusText,responseText:s,responseJson:o,responseHeaders:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseText:``,responseJson:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:n,query:r,variables:i,operationName:a,headers:o}),c={success:s.ok,endpoint:n,status:s.status,statusText:s.statusText,operationName:a,responseHeaders:s.responseHeaders??{}};if(s.responseJson!==null){let t=S(s.responseJson,e);c.responseLength=t.totalLength,c.responsePreview=t.preview,c.responseTruncated=t.truncated,t.truncated||(c.response=s.responseJson)}else if(s.responseText){let t=s.responseText;c.responseFormat=`text`,c.responseLength=t.length,c.responsePreview=t.length>e?t.slice(0,e):t,c.responseTruncated=t.length>e}return s.error&&(c.error=s.error),p(c)}};function H(t,n,r,i,a,o,s){let c={success:i,endpoint:n,status:a,statusText:o,operationName:r,responseHeaders:s};if(t!==null){let n=S(t,e);c.responseLength=n.totalLength,c.responsePreview=n.preview,c.responseTruncated=n.truncated,n.truncated||(c.response=t)}return c}const U=new Map;function W(e){let t=U.get(e);if(t)return t;let n=`
52
+ query EnumSchemaTypeProbe($typeName: String!) {
53
+ __type(name: $typeName) {
54
+ fields(includeDeprecated: true) {
55
+ name
56
+ type {
57
+ ${O(e)}
58
+ }
59
+ }
60
+ }
61
+ }
62
+ `.trim();return U.set(e,n),n}function G(e){let t=e??null;for(;t;){if(typeof t.name==`string`&&t.name.length>0)return{kind:typeof t.kind==`string`?t.kind:null,name:t.name};t=t.ofType??null}return{kind:null,name:null}}function K(e){return e===`OBJECT`||e===`INTERFACE`}function q(e){return e&&typeof e.data==`object`&&e.data!==null&&`__type`in e.data?e.data.__type:null}function J(e){let t=q(e);return Array.isArray(t?.fields)?t.fields.filter(e=>typeof e==`object`&&!!e&&typeof e.name==`string`):[]}function Y(e){let t=e??null,n=0;for(;t;){if(n+=1,typeof t.name==`string`&&t.name.length>0)return null;if(!t.ofType)return t.kind===`LIST`||t.kind===`NON_NULL`?n:null;t=t.ofType??null}return null}function ie(e){let t=null;for(let n of e){let e=Y(n.type);e!==null&&(t=Math.max(t??0,e))}return t}function ae(e){let t=[],n=e??null;for(;n;)t.push(`${n.kind??``}:${n.name??``}`),n=n.ofType??null;return t.join(`>`)}function oe(e){return e.map(e=>`${e.name??``}=${ae(e.type)}`).join(`|`)}async function se(e,t,n){let r=null,i=null,a=0;for(;;){let o=await X(e,t,{query:W(a),variables:{typeName:n}});if(!q(o.record))return r;let s=J(o.record);r=s;let c=ie(s);if(c===null)return r;let l=oe(s);if(c<=a||l===i)return r;i=l,a=c}}async function X(e,t,n){let r={"content-type":`application/json`,...t};try{let t=new AbortController,i=setTimeout(()=>t.abort(),1e4);try{let i=await fetch(e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:t.signal}),a=await i.text(),o=null;try{o=JSON.parse(a)}catch{o=null}let s=o&&typeof o==`object`?o:null,c=Array.isArray(s?.errors)?s.errors:[];return{ok:i.ok||c.length>0,status:i.status,statusText:i.statusText,record:s,errors:c}}finally{clearTimeout(i)}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,record:null,errors:[],error:e instanceof Error?e.message:String(e)}}}async function ce(e,t,n,r){let i=[{typeName:n,depth:0}],a=new Map,o=new Set;for(;i.length>0;){let n=i.shift();if(o.has(n.typeName))continue;o.add(n.typeName);let s=await se(e,t,n.typeName);if(!s)return a.size>0?a:null;if(a.set(n.typeName,s.map(e=>e.name?.trim()??``).filter(e=>e.length>0)),!(n.depth+1>=r))for(let e of s){let t=G(e.type);!t.name||!K(t.kind)||o.has(t.name)||i.push({typeName:t.name,depth:n.depth+1})}}return a}const le=/Cannot query field\s+"[^"]+"\s+on type\s+"([^"]+)".*?Did you mean\s+(.+?)\?/i,ue=/"([^"]+)"/g,Z=`__jshook_probe__`;function de(e){let t=le.exec(e);if(!t)return null;let[,n,r]=t;if(!n||!r)return null;let i=Array.from(r.matchAll(ue),e=>e[1]??``).filter(e=>e.length>0);return i.length>0?{typeName:n,suggestions:i}:null}function Q(e){return e.length===0?`query EnumSchemaProbe { ${Z} }`:`query EnumSchemaProbe { ${e.join(` { `)} { ${Z} }${`}`.repeat(e.length)} }`}function $(t){let n=t.discovered.get(t.parentType)??t.discovered.get(t.typeName)??[],r=JSON.stringify({rootType:t.typeName,parentType:t.parentType,fields:n},null,2);return p({success:!0,endpoint:t.endpoint,typeName:t.typeName,parentType:t.parentType,maxDepth:t.maxDepth,concurrency:t.concurrency,fields:n,discoveredTypes:Object.fromEntries(Array.from(t.discovered.entries()).filter(([e])=>!e.includes(`.`))),responsePreview:r.length>e?`${r.slice(0,e)}\n... (truncated)`:r})}var fe=class{async handleGraphqlEnumSchema(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=await y(t);if(n)return m(n);let r=_(e.headers),i=s(e,`typeName`,`Query`)?.trim()||`Query`,a=s(e,`parentType`,i)?.trim()||i,o=l(e,`maxDepth`,1)??1,c=Math.min(Math.max(Math.trunc(o),1),6),u=l(e,`concurrency`,3)??3,d=Math.min(Math.max(Math.trunc(u),1),10),f=await X(t,r,{query:Q([])});if(!f.ok)return p({success:!1,endpoint:t,typeName:i,parentType:a,status:f.status,statusText:f.statusText,error:f.error??`Schema enumeration request failed`});let h=this.extractSuggestions(f.errors);if(!h)return $({endpoint:t,typeName:i,parentType:a,maxDepth:c,concurrency:d,discovered:await ce(t,r,a,c)??new Map([[a,[]]])});let g=[],v=new Map;if(v.set(h.typeName,h.suggestions),c>1)for(let e of h.suggestions){let t=[e],n=t.join(`.`);v.has(n)||(v.set(n,[]),g.push({path:t,depth:1,typeName:e}))}for(;g.length>0;){let e=g.shift(),n=await X(t,r,{query:Q(e.path)});if(!n.ok)return p({success:!1,endpoint:t,typeName:i,parentType:a,status:n.status,statusText:n.statusText,error:n.error??`Schema enumeration request failed`});let o=this.extractSuggestions(n.errors);if(!o){v.set(e.typeName,[]);continue}if(v.set(o.typeName,o.suggestions),!(e.depth+1>=c))for(let t of o.suggestions){let n=[...e.path,t],r=n.join(`.`);v.has(r)||(v.set(r,[]),g.push({path:n,depth:e.depth+1,typeName:t}))}}return $({endpoint:t,typeName:i,parentType:a,maxDepth:c,concurrency:d,discovered:v})}catch(e){return m(e)}}extractSuggestions(e){for(let t of e){if(typeof t.message!=`string`)continue;let e=de(t.message);if(e)return e}return null}};function pe(e){return`collector`in e?e:{collector:e}}var me=class{callGraph;scriptReplace;introspection;extract;replay;schemaEnum;constructor(e){let t=pe(e);this.callGraph=new A(t.collector),this.scriptReplace=new j(t.collector),this.introspection=new re(t.collector),this.extract=new B(t),this.replay=new V(t.collector),this.schemaEnum=new fe}async handleCallGraphAnalyze(e){return this.callGraph.handleCallGraphAnalyze(e)}async handleScriptReplacePersist(e){return this.scriptReplace.handleScriptReplacePersist(e)}async handleGraphqlIntrospect(e){return this.introspection.handleGraphqlIntrospect(e)}async handleGraphqlExtractQueries(e){return this.extract.handleGraphqlExtractQueries(e)}async handleGraphqlReplay(e){return this.replay.handleGraphqlReplay(e)}async handleGraphqlEnumSchema(e){return this.schemaEnum.handleGraphqlEnumSchema(e)}};export{me as GraphQLToolHandlers};
@@ -0,0 +1,54 @@
1
+ import{Cr as e,Sr as t,wr as n}from"./constants-Cp6hBrrx.mjs";const r=[`etw`,`strace`,`dtrace`],i=3e3,a={etw:[{syscall:`NtCreateFile`,args:[`C:\\Windows\\Temp\\jshookmcp.log`,`GENERIC_READ`],returnValue:0,duration:.7},{syscall:`NtReadFile`,args:[`handle=0x90`,`buffer=4096`],returnValue:512,duration:.2},{syscall:`NtWriteFile`,args:[`handle=0x90`,`buffer=128`],returnValue:128,duration:.3},{syscall:`NtDeviceIoControlFile`,args:[`handle=0x44`,`code=0x222004`],returnValue:0,duration:1.1}],strace:[{syscall:`openat`,args:[`/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.4},{syscall:`read`,args:[`fd=3`,`count=4096`],returnValue:256,duration:.1},{syscall:`write`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=18`,`127.0.0.1:9222`],returnValue:0,duration:1.4}],dtrace:[{syscall:`open_nocancel`,args:[`/private/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.5},{syscall:`read_nocancel`,args:[`fd=3`,`count=4096`],returnValue:320,duration:.1},{syscall:`write_nocancel`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=21`,`127.0.0.1:9222`],returnValue:0,duration:1.3}]};function o(e){return e===`etw`?process.platform===`win32`:e===`strace`?process.platform===`linux`:e===`dtrace`?process.platform===`darwin`:!1}function s(){return process.platform===`win32`?`etw`:process.platform===`linux`?`strace`:process.platform===`darwin`?`dtrace`:`etw`}function c(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function l(e,t,n,r){let a=!1,o=setTimeout(()=>{if(!a){a=!0;try{r?.()}catch{}n(Error(`${e} did not signal readiness within ${i}ms`))}},i);return{resolveReady(e){a||(a=!0,clearTimeout(o),t(e))},rejectReady(e){a||(a=!0,clearTimeout(o),n(e))}}}function u(e,t){return t?!(t.pid!==void 0&&e.pid!==t.pid||t.name&&t.name.length>0&&!t.name.includes(e.syscall)):!0}function d(e,t,n){let r=/^(\d+)\s+([\d:.]+)\s+(\w+)\(([^)]*)\)\s*=\s*(-?\d+)(?:\s+<([\d.]+)>)?$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[5]),s=r[6]?Number(r[6]):void 0,c=a.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:t,syscall:i,args:c,returnValue:Number.isFinite(o)?o:void 0,duration:s!==void 0&&Number.isFinite(s)?s*1e3:void 0}}function f(e,t,n){let r=/^\[([^\]]+)\]\s+PID=(\d+)\s+(\w+)\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}function p(e,t,n){let r=/^\s*(\d+)\s+\d+\s+(\d+)\s+(\w+):\w+\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}var m=class{activeState;capturedEvents=[];lastBackend=s();subprocessError;async start(e){let t=e?.backend??s(),n=Date.now();if(!o(t))throw Error(`Backend "${t}" is not available on platform "${process.platform}"`);if(e?.simulate??process.env.JSHOOK_SIMULATE===`1`){this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}let r=e?.pid??process.pid,i;try{t===`strace`?i=await this.captureWithStrace(r,n):t===`etw`?i=await this.captureWithETW(r,n):t===`dtrace`&&(i=await this.captureWithDTrace(r,n))}catch(r){this.subprocessError=r instanceof Error?r.message:String(r),this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0,subprocess:i},this.lastBackend=t,this.capturedEvents.length=0,this.subprocessError=void 0}async stop(){this.activeState?.subprocess&&(this.activeState.subprocess.kill(`SIGTERM`),this.activeState.subprocess=void 0),this.activeState=void 0}async captureEvents(e){return this.activeState&&!this.activeState.subprocess&&this.generateSyntheticEvents(),this.capturedEvents.filter(t=>u(t,e)).map(c)}getStats(){let e=this.activeState?.backend??this.lastBackend,t=this.activeState?Date.now()-this.activeState.startedAt:0;return{eventsCaptured:this.capturedEvents.length,uptime:t,backend:e,subprocessActive:!!this.activeState?.subprocess,subprocessError:this.subprocessError}}getSupportedBackends(){return r.filter(e=>o(e))}isRunning(){return this.activeState!==void 0}async captureWithStrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`strace`,[`-p`,String(e),`-f`,`-e`,`trace=all`,`-t`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`strace process`,r,i,()=>a.kill(`SIGTERM`)),s=``,c=``;a.stdout?.on(`data`,t=>{c+=t.toString(),this.processLineBuffer(c,e,`strace`)}),a.stderr?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r)if(n.length>0){let r=d(n,e,t);r&&this.capturedEvents.push(r)}}),a.on(`error`,e=>{o.rejectReady(Error(`strace process error: ${e.message}. Is strace installed?`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithETW(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`logman`,[`create`,`trace`,`JSHookETW_${e}`,`-p`,`NT Kernel Logger`,`0x10000`,`-o`,`jshook_etw_${e}.etl`,`-ets`],{stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),o=l(`ETW trace session`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=f(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t.length>0&&t.startsWith(`The command completed successfully`)}),a.on(`error`,e=>{o.rejectReady(Error(`ETW trace error: ${e.message}. Run as Administrator.`))}),a.on(`exit`,e=>{e!==0&&e!==void 0&&o.rejectReady(Error(`ETW trace session ended (code ${e}). Check permissions.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithDTrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`dtrace`,[`-n`,`
2
+ syscall:::entry
3
+ /pid == ${e}/
4
+ {
5
+ printf("%d %d %s:entry %s", pid, probeproc, probefunc, copyinstr(arg0));
6
+ }
7
+ `],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`dtrace process`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=p(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,()=>{}),a.on(`error`,e=>{o.rejectReady(Error(`dtrace error: ${e.message}. Run with sudo.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}generateSyntheticEvents(){if(!this.activeState)return;let e=a[this.activeState.backend];if(!e)return;let t=Date.now()-this.activeState.startedAt,n=Math.max(1,Math.min(e.length*3,Math.floor(t/150)+1)),r=this.activeState.pid??process.pid;for(;this.activeState.generatedEvents<n;){let t=e[this.activeState.generatedEvents%e.length];if(!t)break;let n=this.activeState.generatedEvents*75;this.capturedEvents.push({timestamp:n,pid:r,syscall:t.syscall,args:[...t.args],returnValue:t.returnValue,duration:t.duration}),this.activeState.generatedEvents+=1}}processLineBuffer(e,t,n){}};const h=[{syscallNames:[`NtCreateFile`,`openat`,`open_nocancel`],jsFunction:`fs.open`,baseConfidence:.8,explanation:`File open syscalls commonly originate from Node.js file-system entry points.`},{syscallNames:[`NtReadFile`,`read`,`read_nocancel`],jsFunction:`fs.readFile`,baseConfidence:.78,explanation:`Read-oriented syscalls usually map back to file or stream reads in JavaScript.`},{syscallNames:[`NtWriteFile`,`write`,`write_nocancel`],jsFunction:`fs.writeFile`,baseConfidence:.78,explanation:`Write-oriented syscalls are strongly associated with Node.js file writes.`},{syscallNames:[`NtDeviceIoControlFile`,`ioctl`],jsFunction:`child_process.spawn`,baseConfidence:.55,explanation:`Device and control syscalls are often triggered by child processes or native helpers.`},{syscallNames:[`connect`,`sendto`,`recvfrom`],jsFunction:`fetch`,baseConfidence:.7,explanation:`Socket syscalls generally indicate outbound network activity from fetch-like APIs.`}];function g(e){return h.find(t=>t.syscallNames.includes(e))}function _(e){return e<0?0:e>1?1:e}function v(e,t){return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}var y=class{map(e){let t=this.findJSFunction(e.syscall);if(!t)return null;let n=g(e.syscall);if(!n)return null;let r=n.baseConfidence;return t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&(r+=.08),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&(r+=.1),{syscall:{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration},jsFunction:t,confidence:_(r),reasoning:this.getCorrelationReason(e,t)}}findJSFunction(e){let t=g(e);return t?t.jsFunction:null}getCorrelationReason(e,t){let n=g(e.syscall),r=[];return n&&r.push(n.explanation),t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&r.push(`The syscall arguments reference module-like file extensions, which strengthens the fs correlation.`),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&r.push(`The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.`),r.length===0&&r.push(`Mapped ${e.syscall} to ${t} using the default syscall-to-JS heuristic table.`),r.join(` `)}};function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e==`number`&&Number.isFinite(e))return e}function S(e){if(typeof e==`boolean`)return e}function C(e){if(typeof e==`string`)return e}function w(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)return;t.push(n)}return t}const T=/^[a-z][a-z0-9_]*$/;function E(e){return T.test(e)&&e.length<=64}function D(e){if(e===`etw`||e===`strace`||e===`dtrace`)return e}function O(e){if(!b(e))return;let t={},n=w(e.name),r=x(e.pid);return n&&(t.name=n),r!==void 0&&(t.pid=r),t}function k(e){if(!b(e))return!1;let t=x(e.timestamp),n=x(e.pid),r=C(e.syscall),i=w(e.args),a=e.returnValue,o=e.duration,s=a===void 0||x(a)!==void 0,c=o===void 0||x(o)!==void 0;return t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0&&s&&c}function A(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function j(e){return e instanceof Error?e.message:`Unknown syscall-hook error`}var M=class{monitor;mapper;eventBus;constructor(e,t,n){this.monitor=e,this.mapper=t,this.eventBus=n}async handleSyscallStartMonitor(e){let t=D(e.backend);if(!t)return{ok:!1,error:`backend must be one of: etw, strace, dtrace`};let n=x(e.pid),r=S(e.simulate)??!1;if(e.pid!==void 0&&e.pid!==null&&(n===void 0||!Number.isInteger(n)||n<0))return{ok:!1,error:`pid must be a non-negative integer when provided`};let i=n,a=this.ensureMonitor();try{return await a.start({backend:t,pid:i,simulate:r}),this.eventBus?.emit(`syscall:trace_started`,{backend:t,pid:i,simulate:r,timestamp:new Date().toISOString()}),{ok:!0,started:!0,backend:t,pid:i,simulate:r,stats:a.getStats()}}catch(e){return{ok:!1,error:j(e),requestedBackend:t,supportedBackends:a.getSupportedBackends()}}}async handleSyscallStopMonitor(){let e=this.ensureMonitor();try{return await e.stop(),{ok:!0,stopped:!0,stats:e.getStats()}}catch(e){return{ok:!1,error:j(e)}}}async handleSyscallCaptureEvents(e){let t=this.ensureMonitor(),n=O(e.filter),r=await t.captureEvents(n);return{ok:!0,events:r,count:r.length,stats:t.getStats()}}async handleSyscallCorrelateJs(e){let t=e.syscallEvents;if(!Array.isArray(t)||!t.every(e=>k(e)))return{ok:!1,error:`syscallEvents must be an array of valid SyscallEvent objects`};let n=this.ensureMapper(),r=[],i=[];for(let e of t){let t=A(e),a=n.map(t);a?r.push(a):i.push(t)}return{ok:!0,correlations:r,matched:r.length,unmatched:i}}async handleSyscallFilter(e){let t=w(e.names);if(e.names!==void 0&&t===void 0)return{ok:!1,error:`names must be an array of strings when provided`};let n=await this.ensureMonitor().captureEvents(t&&t.length>0?{name:t}:void 0);return{ok:!0,names:t,events:n,count:n.length}}async handleSyscallGetStats(){let e=this.ensureMonitor();return{ok:!0,...e.getStats(),running:e.isRunning(),supportedBackends:e.getSupportedBackends()}}async handleSyscallEbpfTrace(r){let i=x(r.pid),a=w(r.syscalls),o=x(r.durationSec)??t,s=S(r.simulate)??!1;if(r.pid!==void 0&&r.pid!==null&&(i===void 0||!Number.isInteger(i)||i<0))return{ok:!1,error:`pid must be a non-negative integer (0 for all processes)`};let c=i??0;if(o<n||o>e)return{ok:!1,error:`durationSec must be between ${n} and ${e}`};if(a?.length){let e=a.filter(e=>!E(e));if(e.length>0)return{ok:!1,error:`Invalid syscall names (must be lowercase alphanumeric with underscores): ${e.join(`, `)}`}}if(s){let e=[],t=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`],n=o*50;for(let r=0;r<20;r++)e.push({timestamp:r*n,pid:c||1234,syscall:t[r%t.length]??`read`,args:[`fd=${r%5+3}`,`count=${(r+1)*64}`],returnValue:r%3==0?-1:(r+1)*64,duration:Math.random()*2});return{ok:!0,backend:`ebpf`,simulated:!0,pid:c,durationSec:o,events:e,count:e.length,syscallsTraced:t}}let l=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`,`connect`,`sendto`,`recvfrom`,`clone`,`execve`],u=c>0?`/pid == ${c}/`:``,d=l.map(e=>`tracepoint:syscalls:sys_enter_${e}`).join(`, `),f=l.map(e=>`tracepoint:syscalls:sys_exit_${e}`).join(`, `),p=`#!/usr/bin/env bpftrace
8
+ // Generated by jshookmcp syscall_ebpf_trace
9
+ // Target PID: ${c||`all`} | Duration: ${o}s | Syscalls: ${l.join(`, `)}
10
+
11
+ BEGIN {
12
+ printf("=== eBPF syscall trace started (pid=${c||`all`}, duration=${o}s) ===\\n");
13
+ }
14
+
15
+ ${d} ${u}
16
+ {
17
+ @enter_ts[tid] = nsecs;
18
+ printf("{\\"timestamp\\": %llu, \\"pid\\": %d, \\"tid\\": %d, \\"syscall\\": \\"%s\\", \\"phase\\": \\"enter\\", \\"args\\": {",
19
+ elapsed / 1000000, pid, tid, probe);
20
+ // Log key arguments based on syscall
21
+ if (probe == "tracepoint:syscalls:sys_enter_openat" || probe == "tracepoint:syscalls:sys_enter_open") {
22
+ printf("\\"pathname\\": \\"%s\\", \\"flags\\": %d, \\"mode\\": %d", args->pathname, args->flags, args->mode);
23
+ } else if (probe == "tracepoint:syscalls:sys_enter_read" || probe == "tracepoint:syscalls:sys_enter_write") {
24
+ printf("\\"fd\\": %d, \\"count\\": %d", args->fd, args->count);
25
+ } else if (probe == "tracepoint:syscalls:sys_enter_connect") {
26
+ printf("\\"fd\\": %d", args->fd);
27
+ } else if (probe == "tracepoint:syscalls:sys_enter_mmap") {
28
+ printf("\\"addr\\": %llu, \\"length\\": %llu, \\"prot\\": %d, \\"flags\\": %d, \\"fd\\": %d", args->addr, args->length, args->prot, args->flags, args->fd);
29
+ } else if (probe == "tracepoint:syscalls:sys_enter_execve") {
30
+ printf("\\"filename\\": \\"%s\\"", args->filename);
31
+ } else {
32
+ printf("\\"raw_args\\": \\"(see bpftrace -v output)\\"");
33
+ }
34
+ printf("}}\\n");
35
+ }
36
+
37
+ ${f} ${u}
38
+ {
39
+ $elapsed_ns = nsecs - @enter_ts[tid];
40
+ printf("{\\"timestamp\\": %llu, \\"pid\\": %d, \\"tid\\": %d, \\"syscall\\": \\"%s\\", \\"phase\\": \\"exit\\", \\"ret\\": %d, \\"duration_us\\": %llu}\\n",
41
+ elapsed / 1000000, pid, tid, probe, args->ret, $elapsed_ns / 1000);
42
+ delete(@enter_ts[tid]);
43
+ }
44
+
45
+ interval:s:${o} {
46
+ printf("=== Trace duration (${o}s) elapsed, exiting ===\\n");
47
+ exit();
48
+ }
49
+
50
+ END {
51
+ printf("=== eBPF syscall trace complete ===\\n");
52
+ clear(@enter_ts);
53
+ }
54
+ `;return{ok:!0,backend:`ebpf`,mode:`script`,pid:c,durationSec:o,syscallCount:l.length,syscallsTraced:l,script:p,usage:`bpftrace -e '${p.replace(/'/g,`'\\''`)}'`,note:`Run the generated bpftrace script on a Linux system with bpftrace installed and CAP_BPF/root privileges.`,requiredCapabilities:[`CAP_BPF`,`root`,`bpftrace`]}}ensureMonitor(){return this.monitor||=new m,this.monitor}ensureMapper(){return this.mapper||=new y,this.mapper}};export{M as SyscallHookHandlers};
@@ -0,0 +1,4 @@
1
+ import{an as e,cn as t,ln as n,on as r,sn as i}from"./constants-Cp6hBrrx.mjs";import{n as a}from"./response-C7rKQst4.mjs";import{i as o,o as s,s as c}from"./parse-args-Cuk7-xUt.mjs";import{readFile as l,writeFile as u}from"node:fs/promises";import{isIP as d}from"node:net";const f={20:`ChangeCipherSpec`,21:`Alert`,22:`Handshake`,23:`ApplicationData`},p={"0300":`SSL 3.0`,"0301":`TLS 1.0`,"0302":`TLS 1.1`,"0303":`TLS 1.2`,"0304":`TLS 1.3`},ee={1301:`TLS_AES_128_GCM_SHA256`,1302:`TLS_AES_256_GCM_SHA384`,1303:`TLS_CHACHA20_POLY1305_SHA256`,c02b:`TLS_ECDHE_ECDSA_AES_128_GCM_SHA256`,c02f:`TLS_ECDHE_RSA_AES_128_GCM_SHA256`,c02c:`TLS_ECDHE_ECDSA_AES_256_GCM_SHA384`,c030:`TLS_ECDHE_RSA_AES_256_GCM_SHA384`,cca9:`TLS_ECDHE_ECDSA_CHACHA20_POLY1305`,cca8:`TLS_ECDHE_RSA_CHACHA20_POLY1305`,"009c":`TLS_RSA_AES_128_GCM_SHA256`,"009d":`TLS_RSA_AES_256_GCM_SHA384`,"002f":`TLS_RSA_AES_128_CBC_SHA`,"0035":`TLS_RSA_AES_256_CBC_SHA`,c013:`TLS_ECDHE_RSA_AES_128_CBC_SHA`,c014:`TLS_ECDHE_RSA_AES_256_CBC_SHA`,"00ff":`TLS_EMPTY_RENEGOTIATION_INFO_SCSV`,5600:`TLS_FALLBACK_SCSV`},m={0:`NOERROR`,1:`FORMERR`,2:`SERVFAIL`,3:`NXDOMAIN`,4:`NOTIMP`,5:`REFUSED`},h={0:`QUERY`,1:`IQUERY`,2:`STATUS`,3:`UNASSIGNED`,4:`NOTIFY`,5:`UPDATE`},g={474554:`GET`,"504f5354":`POST`,505554:`PUT`,"44454c45":`DELETE`,48454144:`HEAD`,50415443:`PATCH`,"4f505449":`OPTIONS`,"434f4e4e":`CONNECT`},_={"0000":`server_name`,"000a":`supported_groups`,"000b":`ec_point_formats`,"000d":`signature_algorithms`,"0010":`application_layer_protocol_negotiation`,"0015":`padding`,"0017":`extended_master_secret`,"001b":`compress_certificate`,"0023":`session_ticket`,"0029":`pre_shared_key`,"002b":`supported_versions`,"002d":`psk_key_exchange_modes`,"0033":`key_share`,"0039":`quic_transport_parameters`,4469:`next_protocol_negotiation`,fe0d:`encrypted_client_hello`,ff01:`renegotiation_info`},te={0:`continuation`,1:`text`,2:`binary`,8:`close`,9:`ping`,10:`pong`};function v(e,t){return Number.parseInt(e.substring(t*2,t*2+2),16)}function y(e,t){return Number.parseInt(e.substring(t*2,t*2+4),16)}function b(e,t,n){return e.substring(t*2,(t+n)*2)}function x(e){return e.length>=24&&/^0{24}$/i.test(e.slice(0,24))}function ne(e){if(e.length<44)return null;let t=v(e,0);if(t!==22)return null;let n=b(e,1,2),r=y(e,3);if(e.length/2<5+r||v(e,5)!==1)return null;let i={recordType:f[t]??`0x${t.toString(16)}`,recordVersion:p[n]??n,recordLength:r,handshakeType:`ClientHello`},a=9;if(a+2>e.length/2)return i;let o=b(e,a,2);if(i.clientVersion=p[o]??o,a+=34,a>=e.length/2)return i;let s=v(e,a);if(a+=1+s,a+2>e.length/2)return i;let c=y(e,a);a+=2;let l=[];for(let t=0;t<c/2&&a+2<=e.length/2;t++){let t=b(e,a,2).toLowerCase();l.push({hex:t,name:ee[t]??`Unknown(0x${t})`}),a+=2}if(i.cipherSuites=l,i.cipherSuiteCount=l.length,a>=e.length/2)return i;let u=v(e,a);if(a+=1+u,a+2>e.length/2)return i;let d=y(e,a);a+=2;let m=a+d,h=[];for(;a+4<=m&&a+4<=e.length/2;){let t=b(e,a,2).toLowerCase(),n=y(e,a+2);h.push({type:t,length:n,name:_[t]}),a+=4+n}return i.extensions=h,i.extensionCount=h.length,i}function re(e){if(e.length<24)return null;let t=y(e,0),n=v(e,2),r=v(e,3),i=n>>7&1,a=n>>3&15,o=n>>2&1,s=n>>1&1,c=n&1,l=r>>7&1,u=r>>4&7,d=r&15;return{transactionId:`0x${t.toString(16).padStart(4,`0`)}`,flags:{qr:i===1?`Response`:`Query`,opcode:h[a]??a,authoritativeAnswer:!!o,truncation:!!s,recursionDesired:!!c,recursionAvailable:!!l,reserved:u,responseCode:m[d]??d},questionCount:y(e,4),answerCount:y(e,6),authorityCount:y(e,8),additionalCount:y(e,10)}}function ie(e){if(e.length<24||x(e))return!1;let t=v(e,2),n=v(e,3),r=t>>7&1,i=t>>3&15,a=n&15,o=y(e,4),s=y(e,6);return!(i>2||o+s===0||r===0&&a!==0||r===1&&a>5)}function S(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ae(e,t){if(!S(e))throw Error(`fields[${t}] must be an object`);let n=e.name,r=e.offset,i=e.length,a=e.type;if(typeof n!=`string`||n.trim().length===0)throw Error(`fields[${t}].name must be a non-empty string`);if(typeof r!=`number`||!Number.isInteger(r)||r<0)throw Error(`fields[${t}].offset must be a non-negative integer`);if(typeof i!=`number`||!Number.isInteger(i)||i<=0)throw Error(`fields[${t}].length must be a positive integer`);if(a!==`int`&&a!==`string`&&a!==`bytes`&&a!==`bool`&&a!==`float`)throw Error(`fields[${t}].type is invalid`);return{name:n,offset:r,length:i,type:a}}function oe(e,t){if(!S(e))throw Error(`fields[${t}] must be an object`);let n=e.name,r=e.offset,i=e.length,a=e.type,o=e.description;if(typeof n!=`string`||n.trim().length===0)throw Error(`fields[${t}].name must be a non-empty string`);if(typeof r!=`number`||!Number.isInteger(r)||r<0)throw Error(`fields[${t}].offset must be a non-negative integer`);if(typeof i!=`number`||!Number.isInteger(i)||i<=0)throw Error(`fields[${t}].length must be a positive integer`);if(a!==`uint8`&&a!==`uint16`&&a!==`uint32`&&a!==`int64`&&a!==`float`&&a!==`string`&&a!==`bytes`)throw Error(`fields[${t}].type is invalid`);return{name:n,offset:r,length:i,type:a,...typeof o==`string`?{description:o}:{}}}function se(e,t){let n=t.fields;if(!Array.isArray(n))throw Error(`spec.fields must be an array`);let r=typeof t.fieldDelimiter==`string`&&t.fieldDelimiter.length>0?t.fieldDelimiter:void 0,i=t.byteOrder,a=i===`le`||i===`be`?i:void 0;return{name:e,...r?{fieldDelimiter:r}:{},...a?{byteOrder:a}:{},fields:n.map((e,t)=>ae(e,t))}}function ce(e){if(!S(e))return;let t=e.type;if(t!==`aes`&&t!==`xor`&&t!==`rc4`&&t!==`custom`)return;let n=typeof e.key==`string`?e.key:void 0,r=typeof e.iv==`string`?e.iv:void 0,i=typeof e.notes==`string`?e.notes:void 0;return{type:t,...n?{key:n}:{},...r?{iv:r}:{},...i?{notes:i}:{}}}function le(e,t){if(!S(e))throw Error(`messages[${t}] must be an object`);let n=e.direction,r=e.timestamp,i=e.fields,a=e.raw;if(n!==`req`&&n!==`res`)throw Error(`messages[${t}].direction must be "req" or "res"`);if(typeof r!=`number`||!Number.isFinite(r))throw Error(`messages[${t}].timestamp must be a number`);if(!S(i))throw Error(`messages[${t}].fields must be an object`);if(typeof a!=`string`)throw Error(`messages[${t}].raw must be a string`);return{direction:n,timestamp:r,fields:i,raw:a}}const ue=[`utf8`,`ascii`],C=[`utf8`,`ascii`,`hex`,`base64`],de=[`u8`,`u16`,`u32`,`i8`,`i16`,`i32`,`string`,`bytes`],fe=[`set_byte`,`flip_bit`,`overwrite_bytes`,`append_bytes`,`truncate`,`increment_integer`];function w(e,t=`big`){return e===`little`?`little`:t}function T(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function E(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}function D(e,t){if(typeof e!=`number`||!Number.isInteger(e))throw Error(`${t} must be an integer`);return e}function O(e,t){let n=D(e,t);if(n<0||n>255)throw Error(`${t} must be between 0 and 255`);return n}function pe(e,t){return e===void 0?void 0:E(e,t)}function k(e,t,n,r){if(e===void 0)return n;if(typeof e!=`string`||!t.includes(e))throw Error(`${r} is invalid`);return e}function A(e,t){if(typeof e!=`string`)throw Error(`${t} must be a string`);return e}function j(e,t){let n=e.replace(/^0x/i,``).replace(/\s+/g,``);if(n.length===0)return n;if(n.length%2!=0||/[^0-9a-f]/i.test(n))throw Error(`${t} must be a valid even-length hex string`);return n.toLowerCase()}function M(e,t,n){switch(t){case`utf8`:case`ascii`:return Buffer.from(e,t);case`hex`:return Buffer.from(j(e,n),`hex`);case`base64`:return Buffer.from(e,`base64`)}}function me(e,t){let n=e*8;return t?{min:-(2**(n-1)),max:2**(n-1)-1}:{min:0,max:2**n-1}}function N(e){switch(e){case`u8`:return{width:1,signed:!1};case`u16`:return{width:2,signed:!1};case`u32`:return{width:4,signed:!1};case`i8`:return{width:1,signed:!0};case`i16`:return{width:2,signed:!0};case`i32`:return{width:4,signed:!0};default:return null}}function P(e,t,n,r,i){if(r)switch(n){case 1:e.writeInt8(t,0);return;case 2:i===`little`?e.writeInt16LE(t,0):e.writeInt16BE(t,0);return;case 4:i===`little`?e.writeInt32LE(t,0):e.writeInt32BE(t,0);return}switch(n){case 1:e.writeUInt8(t,0);return;case 2:i===`little`?e.writeUInt16LE(t,0):e.writeUInt16BE(t,0);return;case 4:i===`little`?e.writeUInt32LE(t,0):e.writeUInt32BE(t,0);return}}function he(e,t,n,r,i){if(r)switch(n){case 1:return e.readInt8(t);case 2:return i===`little`?e.readInt16LE(t):e.readInt16BE(t);case 4:return i===`little`?e.readInt32LE(t):e.readInt32BE(t)}switch(n){case 1:return e.readUInt8(t);case 2:return i===`little`?e.readUInt16LE(t):e.readUInt16BE(t);case 4:return i===`little`?e.readUInt32LE(t):e.readUInt32BE(t)}}function F(e,t,n){return t===void 0||e.length===t?e:e.length>t?e.subarray(0,t):Buffer.concat([e,Buffer.alloc(t-e.length,n)])}function ge(e,t){if(!S(e))throw Error(`fields[${t}] must be an object`);let n=e.name,r=e.type,i=e.value;if(typeof n!=`string`||n.trim().length===0)throw Error(`fields[${t}].name must be a non-empty string`);if(typeof r!=`string`||!de.includes(r))throw Error(`fields[${t}].type is invalid`);let a=r,o=N(a);if(o){let s=D(i,`fields[${t}].value`),c=me(o.width,o.signed);if(s<c.min||s>c.max)throw Error(`fields[${t}].value is out of range for ${r} (${c.min}..${c.max})`);if(e.length!==void 0||e.padByte!==void 0||e.encoding!==void 0)throw Error(`fields[${t}] does not support length, padByte, or encoding`);return{name:n,type:a,value:s}}let s=A(i,`fields[${t}].value`),c=pe(e.length,`fields[${t}].length`),l=e.padByte===void 0?0:O(e.padByte,`fields[${t}].padByte`);return r===`string`?{name:n,type:`string`,value:s,encoding:k(e.encoding,ue,`utf8`,`fields[${t}].encoding`),...c===void 0?{}:{length:c},padByte:l}:{name:n,type:`bytes`,value:s,encoding:k(e.encoding,C,`hex`,`fields[${t}].encoding`),...c===void 0?{}:{length:c},padByte:l}}function _e(e,t){switch(e.type){case`u8`:case`u16`:case`u32`:case`i8`:case`i16`:case`i32`:{let n=N(e.type);if(!n)throw Error(`Unsupported numeric field type: ${e.type}`);let r=Buffer.alloc(n.width);return P(r,e.value,n.width,n.signed,t),r}case`string`:return F(Buffer.from(e.value,e.encoding),e.length,e.padByte);case`bytes`:return F(M(e.value,e.encoding,`field ${e.name}`),e.length,e.padByte)}}function ve(e,t){let n=[],r=[],i=0;for(let a of e){let e=_e(a,t);n.push(e),r.push({name:a.name,offset:i,length:e.length,hex:e.toString(`hex`)}),i+=e.length}return{payload:Buffer.concat(n),segments:r}}function ye(e,t){if(!S(e))throw Error(`mutations[${t}] must be an object`);let n=e.strategy;if(typeof n!=`string`||!fe.includes(n))throw Error(`mutations[${t}].strategy is invalid`);switch(n){case`set_byte`:return{strategy:`set_byte`,offset:T(e.offset,`mutations[${t}].offset`),value:O(e.value,`mutations[${t}].value`)};case`flip_bit`:return{strategy:`flip_bit`,offset:T(e.offset,`mutations[${t}].offset`),bit:(()=>{let n=D(e.bit,`mutations[${t}].bit`);if(n<0||n>7)throw Error(`mutations[${t}].bit must be between 0 and 7`);return n})()};case`overwrite_bytes`:return{strategy:`overwrite_bytes`,offset:T(e.offset,`mutations[${t}].offset`),data:M(A(e.data,`mutations[${t}].data`),k(e.encoding,C,`hex`,`mutations[${t}].encoding`),`mutations[${t}].data`)};case`append_bytes`:return{strategy:`append_bytes`,data:M(A(e.data,`mutations[${t}].data`),k(e.encoding,C,`hex`,`mutations[${t}].encoding`),`mutations[${t}].data`)};case`truncate`:return{strategy:`truncate`,length:T(e.length,`mutations[${t}].length`)};case`increment_integer`:{let n=e.width;if(n!==1&&n!==2&&n!==4)throw Error(`mutations[${t}].width must be 1, 2, or 4`);return{strategy:`increment_integer`,offset:T(e.offset,`mutations[${t}].offset`),width:n,delta:D(e.delta,`mutations[${t}].delta`),endian:w(e.endian),signed:e.signed===!0}}}}function be(e,t,n){let r=Buffer.from(e);switch(t.strategy){case`set_byte`:if(t.offset>=r.length)throw Error(`mutations[${n}] offset is outside the payload`);return r[t.offset]=t.value,{payload:r,summary:{index:n,strategy:t.strategy,detail:`set payload[${t.offset}] to ${t.value}`}};case`flip_bit`:if(t.offset>=r.length)throw Error(`mutations[${n}] offset is outside the payload`);{let e=r[t.offset];r[t.offset]=e^1<<t.bit}return{payload:r,summary:{index:n,strategy:t.strategy,detail:`flipped bit ${t.bit} at offset ${t.offset}`}};case`overwrite_bytes`:if(t.offset+t.data.length>r.length)throw Error(`mutations[${n}] overwrite exceeds payload length`);return t.data.copy(r,t.offset),{payload:r,summary:{index:n,strategy:t.strategy,detail:`overwrote ${t.data.length} bytes at offset ${t.offset}`}};case`append_bytes`:return{payload:Buffer.concat([r,t.data]),summary:{index:n,strategy:t.strategy,detail:`appended ${t.data.length} bytes`}};case`truncate`:if(t.length>r.length)throw Error(`mutations[${n}] length exceeds payload size`);return{payload:r.subarray(0,t.length),summary:{index:n,strategy:t.strategy,detail:`truncated payload to ${t.length} bytes`}};case`increment_integer`:{if(t.offset+t.width>r.length)throw Error(`mutations[${n}] integer range exceeds payload length`);let e=he(r,t.offset,t.width,t.signed,t.endian)+t.delta,i=me(t.width,t.signed);if(e<i.min||e>i.max)throw Error(`mutations[${n}] integer overflow (${i.min}..${i.max})`);return P(r.subarray(t.offset,t.offset+t.width),e,t.width,t.signed,t.endian),{payload:r,summary:{index:n,strategy:t.strategy,detail:`incremented ${t.signed?`signed`:`unsigned`} ${t.width}-byte integer at offset ${t.offset} by ${t.delta}`}}}}}const xe=Object.freeze({arp:2054,ipv4:2048,ipv6:34525,vlan:33024}),Se=Object.freeze({icmp:1,igmp:2,tcp:6,udp:17,gre:47,esp:50,ah:51,icmpv6:58,ospf:89}),Ce=Object.freeze({loopback:0,ethernet:1,raw:101});function I(e,t,n,r){if(typeof e==`number`){if(!Number.isInteger(e)||e<0||e>r)throw Error(`${t} must be an integer between 0 and ${r}`);return e}if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string or integer`);let i=e.trim().toLowerCase(),a=n[i];if(a!==void 0)return a;if(/^\d+$/.test(i)){let e=Number.parseInt(i,10);if(e>r)throw Error(`${t} must be less than or equal to ${r}`);return e}let o=j(i,t),s=Number.parseInt(o,16);if(s>r)throw Error(`${t} must be less than or equal to ${r}`);return s}function L(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty MAC address string`);let n=e.trim().toLowerCase().replace(/^0x/,``).replace(/[:\-.\s]/g,``);if(!/^[0-9a-f]{12}$/i.test(n))throw Error(`${t} must be a valid 6-byte MAC address`);let r=n.match(/.{2}/g)?.join(`:`);if(!r)throw Error(`${t} must be a valid 6-byte MAC address`);return{canonical:r,bytes:Buffer.from(n,`hex`)}}function R(e,t){if(typeof e!=`string`||d(e.trim())!==4)throw Error(`${t} must be a valid IPv4 address`);let n=e.trim().split(`.`).map(e=>Number.parseInt(e,10));return Buffer.from(n)}function z(e,t){return e.length===0?[]:e.split(`:`).flatMap(e=>{if(e.length===0)return[];if(e.includes(`.`)){let n=R(e,t);return[n.readUInt16BE(0).toString(16),n.readUInt16BE(2).toString(16)]}if(!/^[0-9a-f]{1,4}$/i.test(e))throw Error(`${t} contains an invalid IPv6 group`);return[e]})}function we(e,t){if(typeof e!=`string`)throw Error(`${t} must be a valid IPv6 address`);let n=e.trim().toLowerCase().split(`%`)[0]??``;if(d(n)!==6)throw Error(`${t} must be a valid IPv6 address`);let r=n.split(`::`);if(r.length>2)throw Error(`${t} must be a valid IPv6 address`);let i=z(r[0]??``,t),a=z(r[1]??``,t),o=r.length===2?[...i,...Array.from({length:8-i.length-a.length},()=>`0`),...a]:i;if(o.length!==8)throw Error(`${t} must expand to exactly 8 IPv6 groups`);let s=Buffer.alloc(16);for(let[e,t]of o.entries())s.writeUInt16BE(Number.parseInt(t,16),e*2);return s}function B(e,t,n){return t===`ipv4`?R(e,n):we(e,n)}function V(e,t){return I(e,t,xe,65535)}function Te(e,t){return I(e,t,Se,255)}function Ee(e,t){return I(e,t,Ce,4294967295)}function De(e){return e===`little`?`little`:`big`}function Oe(e){return e===`big`?`big`:`little`}function ke(e){return e===`nano`?`nano`:`micro`}function H(e,t){if(typeof e!=`string`)throw Error(`${t} must be a hex string`);return Buffer.from(j(e,t),`hex`)}function U(e){let t=0;for(let n=0;n<e.length;n+=2){let r=e[n]??0,i=e[n+1]??0;for(t+=r<<8|i;t>65535;)t=(t&65535)+(t>>>16)}return~t&65535}function Ae(e,t,n,r){let i=Buffer.alloc(14);return e.bytes.copy(i,0),t.bytes.copy(i,6),i.writeUInt16BE(n,12),Buffer.concat([i,r])}function je(e){if(e.hardwareSize!==e.senderMac.bytes.length||e.hardwareSize!==e.targetMac.bytes.length)throw Error(`hardwareSize must match the provided MAC address lengths`);if(e.protocolSize!==e.senderIp.length||e.protocolSize!==e.targetIp.length)throw Error(`protocolSize must match the provided IP address lengths`);let t=Buffer.alloc(8+e.hardwareSize*2+e.protocolSize*2),n=0;return t.writeUInt16BE(e.hardwareType,n),n+=2,t.writeUInt16BE(e.protocolType,n),n+=2,t.writeUInt8(e.hardwareSize,n++),t.writeUInt8(e.protocolSize,n++),t.writeUInt16BE(e.operation===`reply`?2:1,n),n+=2,e.senderMac.bytes.copy(t,n),n+=e.hardwareSize,e.senderIp.copy(t,n),n+=e.protocolSize,e.targetMac.bytes.copy(t,n),n+=e.hardwareSize,e.targetIp.copy(t,n),t}function Me(e){let t=Buffer.alloc(20);t[0]=69,t[1]=(e.dscp&63)<<2|e.ecn&3,t.writeUInt16BE(t.length+e.payload.length,2),t.writeUInt16BE(e.identification,4);let n=!!e.dontFragment<<1|!!e.moreFragments;t.writeUInt16BE((n&7)<<13|e.fragmentOffset&8191,6),t[8]=e.ttl,t[9]=e.protocol,t.writeUInt16BE(0,10),e.sourceIp.copy(t,12),e.destinationIp.copy(t,16);let r=U(t);return t.writeUInt16BE(r,10),{packet:Buffer.concat([t,e.payload]),checksum:r}}function Ne(e){let t=Buffer.alloc(40),n=6<<28|(((e.dscp&63)<<2|e.ecn&3)&255)<<20|e.flowLabel&1048575;return t.writeUInt32BE(n>>>0,0),t.writeUInt16BE(e.payload.length,4),t.writeUInt8(e.protocol,6),t.writeUInt8(e.hopLimit,7),e.sourceIp.copy(t,8),e.destinationIp.copy(t,24),Buffer.concat([t,e.payload])}function Pe(e){let t=Buffer.alloc(8+e.payload.length);t[0]=e.operation===`reply`?0:8,t[1]=0,t.writeUInt16BE(0,2),t.writeUInt16BE(e.identifier,4),t.writeUInt16BE(e.sequenceNumber,6),e.payload.copy(t,8);let n=U(t);return t.writeUInt16BE(n,2),{packet:t,checksum:n}}function W(e,t,n,r){r===`little`?e.writeUInt32LE(n,t):e.writeUInt32BE(n,t)}function G(e,t,n,r){r===`little`?e.writeUInt16LE(n,t):e.writeUInt16BE(n,t)}function K(e,t,n){return n===`little`?e.readUInt32LE(t):e.readUInt32BE(t)}function q(e,t,n){return n===`little`?e.readUInt16LE(t):e.readUInt16BE(t)}function Fe(e,t){let n=e===`little`?t===`nano`?`4d3cb2a1`:`d4c3b2a1`:t===`nano`?`a1b23c4d`:`a1b2c3d4`;return Buffer.from(n,`hex`)}function Ie(e){if(e.length<24)throw Error(`PCAP file is too small to contain a global header`);let t=e.subarray(0,4).toString(`hex`),n,r;switch(t){case`d4c3b2a1`:n=`little`,r=`micro`;break;case`4d3cb2a1`:n=`little`,r=`nano`;break;case`a1b2c3d4`:n=`big`,r=`micro`;break;case`a1b23c4d`:n=`big`,r=`nano`;break;default:throw Error(`Unsupported capture format: only classic PCAP files are supported`)}return{endianness:n,timestampPrecision:r,versionMajor:q(e,4,n),versionMinor:q(e,6,n),snapLength:K(e,16,n),linkType:K(e,20,n)}}function Le(e,t){if(!S(e))throw Error(`packets[${t}] must be an object`);let n=H(e.dataHex,`packets[${t}].dataHex`),r=e.timestampSeconds===void 0?0:T(e.timestampSeconds,`packets[${t}].timestampSeconds`),i=e.timestampFraction===void 0?0:T(e.timestampFraction,`packets[${t}].timestampFraction`),a=e.originalLength===void 0?n.length:E(e.originalLength,`packets[${t}].originalLength`);if(a<n.length)throw Error(`packets[${t}].originalLength must be >= included packet length`);return{data:n,timestampSeconds:r,timestampFraction:i,originalLength:a}}function Re(e){let t=Buffer.alloc(24);Fe(e.endianness,e.timestampPrecision).copy(t,0),G(t,4,2,e.endianness),G(t,6,4,e.endianness),W(t,8,0,e.endianness),W(t,12,0,e.endianness),W(t,16,e.snapLength,e.endianness),W(t,20,e.linkType,e.endianness);let n=e.packets.map(t=>{let n=Buffer.alloc(16);return W(n,0,t.timestampSeconds,e.endianness),W(n,4,t.timestampFraction,e.endianness),W(n,8,t.data.length,e.endianness),W(n,12,t.originalLength,e.endianness),Buffer.concat([n,t.data])});return Buffer.concat([t,...n])}function ze(e,t,n){let r=Ie(e),i=[],a=24;for(;a<e.length&&!(t!==void 0&&i.length>=t);){if(a+16>e.length)throw Error(`PCAP file ends with an incomplete packet header`);let t=K(e,a,r.endianness),o=K(e,a+4,r.endianness),s=K(e,a+8,r.endianness),c=K(e,a+12,r.endianness);if(a+=16,a+s>e.length)throw Error(`PCAP file ends with an incomplete packet payload`);let l=e.subarray(a,a+s);a+=s;let u=n===void 0?l.length:n,d=Math.min(u,l.length);i.push({index:i.length,timestampSeconds:t,timestampFraction:o,includedLength:s,originalLength:c,dataHex:l.subarray(0,d).toString(`hex`),truncated:d<l.length})}return{header:r,packets:i}}const Be=[Buffer.from([44]),Buffer.from([124]),Buffer.from([58]),Buffer.from([59]),Buffer.from([9]),Buffer.from([0]),Buffer.from([13,10])];function J(e){return e.replace(/^0x/i,``).replace(/\s+/g,``).toLowerCase()}function Y(e){let t=J(e);return t.length===0||t.length%2!=0?!1:/^[0-9a-f]+$/i.test(t)}function X(e){return Y(e)?Buffer.from(J(e),`hex`):null}function Z(e){return e>=32&&e<=126}function Q(e){if(e.length===0)return 0;let t=0;for(let n of e.values())Z(n)&&(t+=1);return t/e.length}function Ve(e){return e.length===0?0:e.reduce((e,t)=>e+Q(t),0)/e.length}function He(e,t){if(t.length===0)return[e];let n=[],r=0,i=e.indexOf(t,r);for(;i>=0;)n.push(e.subarray(r,i)),r=i+t.length,i=e.indexOf(t,r);return n.push(e.subarray(r)),n}function Ue(e){return Q(e)===1?e.toString(`utf8`):e.toString(`hex`)}function We(e){let t=[];for(let n of e){let e=X(n);e&&t.push(e)}return t}function Ge(e,t){if(e.length===0)return null;if(e.length===1)return e.readUInt8(0);if(e.length===2)return t===`le`?e.readUInt16LE(0):e.readUInt16BE(0);if(e.length===4)return t===`le`?e.readUInt32LE(0):e.readUInt32BE(0);if(e.length===8){let n=Number(t===`le`?e.readBigUInt64LE(0):e.readBigUInt64BE(0));return Number.isFinite(n)?n:null}let n=0,r=t===`le`?[...e.values()].toReversed():[...e.values()];for(let e of r)n=n*256+e;return Number.isFinite(n)?n:null}function Ke(e,t){if(e.length===4){let n=t===`le`?e.readFloatLE(0):e.readFloatBE(0);return Number.isFinite(n)?n:null}if(e.length===8){let n=t===`le`?e.readDoubleLE(0):e.readDoubleBE(0);return Number.isFinite(n)?n:null}return null}function qe(e,t){if(t.length===0)return 0;let n=0,r=0,i=e.indexOf(t,r);for(;i>=0;)n+=1,r=i+t.length,i=e.indexOf(t,r);return n}function Je(e){return e.length===0?`bytes`:e.every(e=>e.length===1)&&e.every(e=>e[0]===0||e[0]===1)?`bool`:Ve(e)>=.7?`string`:e.every(e=>e.length===4)&&Ye(e)?`float`:e.every(e=>e.length<=4)?`int`:`bytes`}function Ye(e){let t=[];for(let n of e){let e=Ke(n,`be`);if(e===null)return!1;t.push(e)}return t.some(e=>Math.abs(e)>.001&&Math.abs(e)<1e6)}function Xe(e,t){let n=0,r=0;for(let i of e){let e=i[t];e!==void 0&&(n+=1,Z(e)&&(r+=1))}return n>0&&r/n>=.8}function Ze(e,t){let n=0;for(let r of e){let e=r[t];if(e!==void 0&&(n+=1,e!==0&&e!==1))return!1}return n>0}function Qe(e,t){if(t.length===0)return[];let n=e.map(e=>He(e,t)),r=n[0];if(!r||r.length<2)return[];let i=r.length;if(!n.every(e=>e.length===i))return[];let a=[],o=0;for(let e=0;e<i;e+=1){let i=r[e];if(!i)continue;let s=n.map(t=>t[e]).filter(e=>Buffer.isBuffer(e));a.push({name:`field_${e+1}`,offset:o,length:i.length,type:Je(s)}),o+=i.length+t.length}return a}function $e(e){let t=Math.min(...e.map(e=>e.length)),n=[],r=0;for(;r<t&&n.length<24;){if(Xe(e,r)){let i=r+1;for(;i<t&&Xe(e,i);)i+=1;n.push({name:`field_${n.length+1}`,offset:r,length:i-r,type:`string`}),r=i;continue}if(Ze(e,r)){n.push({name:`field_${n.length+1}`,offset:r,length:1,type:`bool`}),r+=1;continue}let i=t-r;if(i>=4&&Ye(e.map(e=>e.subarray(r,r+4)))){n.push({name:`field_${n.length+1}`,offset:r,length:4,type:`float`}),r+=4;continue}let a=i>=4?4:Math.min(i,2),o=e.map(e=>e.subarray(r,r+a));n.push({name:`field_${n.length+1}`,offset:r,length:a,type:Je(o)}),r+=a}return n}function et(e){for(let t of Be){let n=e.map(e=>qe(e,t)),r=n[0];if(typeof r==`number`&&r>=2&&n.every(e=>e===r))return Ue(t)}}function tt(e){let t=Math.min(...e.map(e=>e.length));if(t<2)return`be`;let n=0,r=0,i=Math.min(t-1,8);for(let t=0;t<i;t+=2){let i=0,a=0;for(let n of e){let e=n.readUInt16LE(t),r=n.readUInt16BE(t);e<4096&&(i+=1),r<4096&&(a+=1)}i>a?n+=1:a>i&&(r+=1)}return n>r?`le`:`be`}function nt(e,t){if(e.length===0||t.length<2)return e;let n=Math.min(...t.map(e=>e.length)),r=0;for(let e=0;e<n;e+=1){let n=t[0][e];if(t.every(t=>t[e]===n))r=e+1;else break}if(r===0)return e;let i=!1;return e.map(e=>!i&&e.offset===0&&r>=2?(i=!0,{...e,name:`magic`}):i&&e.type===`int`&&e.length<=2&&e.offset<=r?{...e,name:`version`}:e)}var rt=class{patterns=new Map;legacyPatterns=new Map;definePattern(e,t,n){let r=Array.isArray(t)?this.createLegacyPattern(e,t,n):this.createLegacyPatternFromSpec(e,t),i=this.createSpecFromLegacyPattern(r);if(this.patterns.set(e,i),this.legacyPatterns.set(e,r),Array.isArray(t))return r}detectPattern(e){let t=X(e);if(!t)return null;let n=null;for(let e of this.patterns.values()){let r=e.fields.length+ +!!e.fieldDelimiter;if(r===0)continue;let i=0;e.fieldDelimiter&&this.payloadContainsDelimiter(t,e.fieldDelimiter)&&(i+=1);for(let n of e.fields)this.matchesField(t,n,e.byteOrder??`be`)&&(i+=1);let a=Number((i/r).toFixed(2));if(a<=0)continue;let o={pattern:e,confidence:a,matches:i,total:r};(!n||o.confidence>n.confidence||o.confidence===n.confidence&&o.matches>n.matches)&&(n=o)}return n}autoDetect(e){let t=We(e);if(t.length===0)return null;let n=et(t),r=this.inferFields(e);return{name:`auto-detected-pattern`,fieldDelimiter:n,byteOrder:tt(t),fields:r}}inferFields(e){let t=We(e);if(t.length===0)return[];let n=et(t);if(n){let e=Qe(t,this.parseDelimiter(n));if(e.length>0)return nt(e,t)}return nt($e(t),t)}autoDetectPattern(e,t){let n=e.map(e=>e.toString(`hex`)),r=this.autoDetect(n),i=t?.name??r?.name??`auto_detected`;if(!r){let e=this.createLegacyPattern(i,[]);return this.patterns.set(i,this.createSpecFromLegacyPattern(e)),this.legacyPatterns.set(i,e),e}let a={...r,name:i};return this.definePattern(i,a),this.getPattern(i)??this.createLegacyPatternFromSpec(i,a)}getPattern(e){return this.legacyPatterns.get(e)}listPatterns(){return[...this.patterns.keys()]}exportProto(e){let t=this.isLegacyPattern(e)?e:this.createLegacyPatternFromSpec(e.name,e),n=[`// Protocol: ${t.name}`,`// Byte order: ${t.byteOrder}`,``];t.encryption&&(n.push(`// Encryption: ${t.encryption.type}`),t.encryption.notes&&n.push(`// Notes: ${t.encryption.notes}`),n.push(``)),n.push(`message ${this.toPascalCase(t.name)} {`);for(let e=0;e<t.fields.length;e+=1){let r=t.fields[e];if(!r)continue;let i=r.description?` // ${r.description}`:``;n.push(` ${this.toProtoType(r.type)} ${r.name} = ${e+1};${i}`)}return n.push(`}`),n.push(``),n.join(`
2
+ `)}payloadContainsDelimiter(e,t){let n=this.parseDelimiter(t);return n.length===0?!1:e.includes(n)}matchesField(e,t,n){if(t.offset<0||t.length<=0||e.length<t.offset+t.length)return!1;let r=e.subarray(t.offset,t.offset+t.length);switch(t.type){case`bytes`:return r.length===t.length;case`bool`:return r.length===1&&(r[0]===0||r[0]===1);case`string`:return Q(r)>=.6;case`int`:return Ge(r,n)!==null;case`float`:return Ke(r,n)!==null;default:return!1}}createLegacyPattern(e,t,n){return{name:e,fields:t.map(e=>({name:e.name,offset:e.offset,length:e.length,type:e.type,...e.description?{description:e.description}:{}})).toSorted((e,t)=>e.offset-t.offset),byteOrder:n?.byteOrder??`big`,...n?.encryption?{encryption:n.encryption}:{}}}createLegacyPatternFromSpec(e,t){return{name:e,fieldDelimiter:t.fieldDelimiter,byteOrder:t.byteOrder===`le`?`little`:`big`,fields:t.fields.map(e=>({name:e.name,offset:e.offset,length:e.length,type:this.toLegacyFieldType(e),...e.description?{description:e.description}:{}}))}}createSpecFromLegacyPattern(e){return{name:e.name,fieldDelimiter:e.fieldDelimiter,byteOrder:e.byteOrder===`little`?`le`:`be`,fields:e.fields.map(e=>({name:e.name,offset:e.offset,length:e.length,type:this.toSpecFieldType(e.type),...e.description?{description:e.description}:{}}))}}isLegacyPattern(e){return e.byteOrder===`big`||e.byteOrder===`little`}toLegacyFieldType(e){return e.type===`float`?`float`:e.type===`string`?`string`:e.type===`bytes`?`bytes`:e.length===1?`uint8`:e.length===2?`uint16`:e.length===4?`uint32`:`int64`}toSpecFieldType(e){return e===`float`?`float`:e===`string`?`string`:e===`bytes`?`bytes`:`int`}parseDelimiter(e){if(Y(e)){let t=X(e);if(t)return t}return Buffer.from(e,`utf8`)}toProtoType(e){return{uint8:`uint32`,uint16:`uint32`,uint32:`uint32`,int64:`int64`,float:`float`,string:`string`,bytes:`bytes`}[e]}toPascalCase(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`).split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)||`Message`}};function it(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e){return e.trim().toLowerCase()}function at(e){if(e.length===0)return 0;let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0;for(let r of t.values()){let t=r/e.length;t>0&&(n-=t*Math.log2(t))}return n}function ot(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);r>=32&&r<=126&&(t+=1)}return t/e.length}var st=class{infer(e){if(e.length===0)return{states:[],transitions:[],initial:``,initialState:``,finalStates:[]};let t=new Map,n=new Map,r=``;for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)continue;let o=this.buildSignature(a),s=t.get(o);if(s?s.type=this.mergeStateTypes(s.type,this.inferStateType(a,i===e.length-1)):(s={id:`state_${t.size+1}`,name:this.buildStateName(a,t.size+1),type:this.inferStateType(a,i===e.length-1)},t.set(o,s)),r&&a.timestamp!==void 0){let t=e[0];t&&t.timestamp!==void 0&&(s.timeout=a.timestamp-t.timestamp)}if(r){let e=this.buildEventName(a),t=this.buildCondition(a.fields),i=this.buildAction(a),o=`${r}:${s.id}:${e}`;n.has(o)||n.set(o,{from:r,to:s.id,event:e,confidence:this.computeTransitionConfidence(a),...t?{condition:t}:{},...i?{action:i}:{}})}r=s.id}let i=e[0],a=i?t.get(this.buildSignature(i))?.id??``:``;return{states:[...t.values()],transitions:[...n.values()],initial:a,initialState:a,finalStates:this.collectTerminalStates([...t.values()])}}visualize(e){if(e.states.length===0)return["```mermaid",`stateDiagram-v2`,` [*] --> empty`,"```"].join(`
3
+ `);let t=["```mermaid",`stateDiagram-v2`],n=e.initialState??e.initial;n&&t.push(` [*] --> ${n}`);for(let n of e.states){let e=n.type??`normal`,r=e===`normal`?n.name:`${n.name} (${e})`;t.push(` state "${r}" as ${n.id}`)}for(let n of e.transitions){let e=[n.event??n.trigger??`transition`];typeof n.confidence==`number`&&e.push(`(${n.confidence.toFixed(2)})`),n.condition&&e.push(`[${n.condition}]`),n.action&&e.push(`/ ${n.action}`),t.push(` ${n.from} --> ${n.to} : ${e.join(` `)}`)}let r=new Set(e.finalStates??[]);for(let n of e.states){let e=n.type??`normal`;(e===`accept`||e===`reject`||r.has(n.id))&&t.push(` ${n.id} --> [*]`)}return t.push("```"),t.join(`
4
+ `)}inferStateMachine(e){let t=e.map(e=>({direction:e.direction===`out`?`req`:`res`,timestamp:e.timestamp??0,fields:{},raw:e.payload.length>0?e.payload.toString(`utf8`):e.payload.toString(`hex`),rawBuffer:e.payload}));return this.infer(t)}generateMermaid(e){return this.visualize(e)}simplify(e){if(e.states.length<2)return{...e,initialState:e.initialState??e.initial,finalStates:e.finalStates??this.collectTerminalStates(e.states)};let t=new Map,n=new Map;for(let r of e.states){let e=this.getPayloadPrefix(r);if(!e)continue;let i=[...n.entries()].find(([t])=>t===e);i?t.set(r.id,i[0]):(n.set(e,r.id),t.set(r.id,e))}let r=new Map,i=new Map;for(let[e,t]of n)i.set(e,t);for(let t of e.states){let e=this.getPayloadPrefix(t);if(!e)continue;let n=i.get(e);n&&n!==t.id&&r.set(t.id,n)}if(r.size===0)return{...e,initialState:e.initialState??e.initial,finalStates:e.finalStates??this.collectTerminalStates(e.states)};let a=e.states.filter(e=>!r.has(e.id)),o=e.transitions.map(e=>({...e,from:r.get(e.from)??e.from,to:r.get(e.to)??e.to})).filter(e=>e.from!==e.to),s=e.initialState??e.initial??``,c=r.get(s)??s;return{states:a,transitions:o,initial:c,initialState:c,finalStates:e.finalStates.map(e=>r.get(e)??e).filter((e,t,n)=>n.indexOf(e)===t)}}getPayloadPrefix(e){let t=e.expectedPayload;return!t||t.length<8?null:t.slice(0,8).toLowerCase()}buildSignature(e){let t=Object.keys(e.fields).toSorted().join(`,`),n=$(e.rawBuffer?e.rawBuffer.toString(`hex`):e.raw).slice(0,24);return`${e.direction}|${t}|${n}`}buildStateName(e,t){let n=e.direction===`req`?`send`:`recv`,r=this.findPrimaryFieldName(e.fields),i=e.raw;if(i.length===0)return`${n}_empty`;let a=e.rawBuffer,o=Buffer.isBuffer(a)?a.toString(`hex`):i;if(o.startsWith(`16`)||o.startsWith(`15`)||o.startsWith(`17`))return`${n}_tls_handshake`;let s=i.trimStart();if(s.startsWith(`{`)||s.startsWith(`[`))return`${n}_json_${r||`step_${t}`}`;if(ot(i)>=.7){let e=$(i);return e.includes(`close`)||e.includes(`fin`)||e.includes(`bye`)?`${n}_close`:e.startsWith(`get `)||e.startsWith(`post `)||e.startsWith(`http`)?`${n}_text_http`:`${n}_text_${r||`step_${t}`}`}return Buffer.isBuffer(a)&&a.length>=32&&at(a)>6?`${n}_encrypted`:Buffer.isBuffer(a)&&a.length<=4?`${n}_control`:`${n}_${r||`step_${t}`}`}findPrimaryFieldName(e){return Object.keys(e).toSorted()[0]||``}inferStateType(e,t){let n=$(e.raw),r=this.findStatusValue(e.fields);return this.containsRejectSignal(n)||this.containsRejectSignal(r)?`reject`:this.containsAcceptSignal(n)||this.containsAcceptSignal(r)||t&&e.direction===`res`?`accept`:`normal`}mergeStateTypes(e,t){return e===`reject`||t===`reject`?`reject`:e===`accept`||t===`accept`?`accept`:`normal`}findStatusValue(e){for(let t of[`status`,`result`,`code`,`reason`,`message`]){let n=e[t];if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)return String(n)}return``}containsRejectSignal(e){return[`error`,`fail`,`denied`,`reject`,`timeout`,`invalid`].some(t=>$(e).includes(t))}containsAcceptSignal(e){return[`ok`,`success`,`accept`,`ready`,`done`,`complete`].some(t=>$(e).includes(t))}buildEventName(e){let t=this.findStatusValue(e.fields);if(t)return`${e.direction}_${$(t).replace(/[^a-z0-9]+/g,`_`)}`;let n=this.findPrimaryFieldName(e.fields);return n?`${e.direction}_${n}`:`${e.direction}_message`}buildCondition(e){let t=this.findStatusValue(e);if(t)return`status=${t}`;let n=Object.keys(e).toSorted().slice(0,2);if(n.length===0)return;let r=[];for(let t of n){let n=e[t];(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&r.push(`${t}=${n}`)}return r.length>0?r.join(`, `):void 0}buildAction(e){let t=this.findStatusValue(e.fields);if(this.containsRejectSignal(t)||this.containsRejectSignal(e.raw))return`reject`;if(this.containsAcceptSignal(t)||this.containsAcceptSignal(e.raw))return`complete`;let n=$(e.raw);if(n.includes(`ack`))return`acknowledge`;if(n.includes(`retry`))return`retry`;if(Object.keys(e.fields).length>0&&it(e.fields))return e.direction===`req`?`send`:`receive`}collectTerminalStates(e){let t=e.filter(e=>{let t=e.type??`normal`;return t===`accept`||t===`reject`}).map(e=>e.id);for(let n of e){let e=$(n.name);(e.includes(`close`)||e.includes(`fin`)||e.includes(`bye`))&&(t.includes(n.id)||t.push(n.id))}return t}computeTransitionConfidence(e){let t=.3;return Object.keys(e.fields).length>0&&(t+=.3),this.findStatusValue(e.fields)&&(t+=.2),e.raw.length>0&&(t+=.2),Math.min(t,1)}};const ct={states:[],transitions:[],initial:``,initialState:``,finalStates:[]};var lt=class{engine;inferrer;eventBus;constructor(e,t,n){this.engine=e,this.inferrer=t,this.eventBus=n}emitEvent(e,t){this.eventBus?.emit(e,{...t,timestamp:new Date().toISOString()})}getEngine(){return this.engine||=new rt,this.engine}getInferrer(){return this.inferrer||=new st,this.inferrer}errorMessage(e){return e instanceof Error?e.message:String(e)}},ut=class extends lt{async handleDefinePattern(e){try{let t=typeof e.name==`string`&&e.name.trim().length>0?e.name:`unnamed_pattern`,n=o(e,`spec`);if(n){let e=se(t,n);return this.getEngine().definePattern(t,e),{patternId:t,pattern:this.getEngine().getPattern(t)??{name:t,fields:[],byteOrder:`big`},success:!0}}let r=(Array.isArray(e.fields)?e.fields:[]).map((e,t)=>oe(e,t)),i=e.byteOrder===`little`||e.byteOrder===`big`?e.byteOrder:void 0,a=ce(e.encryption);return{patternId:t,pattern:this.getEngine().definePattern(t,r,{...i?{byteOrder:i}:{},...a?{encryption:a}:{}}),success:!0}}catch(e){return{patternId:`error`,pattern:{name:`error`,fields:[],byteOrder:`big`},success:!1,error:this.errorMessage(e)}}}async handleAutoDetect(e){try{let t=(()=>{let t=s(e,`hexPayloads`);return t.length>0?t:s(e,`payloads`)})(),n=this.getEngine().autoDetect(t),r=typeof e.name==`string`&&e.name.trim().length>0?e.name:void 0;if(!n)return{patterns:[this.getEngine().autoDetectPattern([],r?{name:r}:{})],success:!0};let i={...n,name:r??n.name};this.getEngine().definePattern(i.name,i);let a=this.getEngine().getPattern(i.name)??{name:i.name,fields:[],byteOrder:`big`};return this.emitEvent(`protocol:pattern_detected`,{patternName:i.name,confidence:0}),{patterns:[a],success:!0}}catch(e){return{patterns:[],success:!1,error:this.errorMessage(e)}}}async handleInferFields(e){try{let t=s(e,`hexPayloads`);return{success:!0,fields:this.getEngine().inferFields(t)}}catch(e){return{fields:[],success:!1,error:this.errorMessage(e)}}}async handleExportSchema(e){try{let t=c(e,`patternId`),n=this.getEngine().getPattern(t);return n?{schema:this.getEngine().exportProto(n)}:{schema:`// Error: pattern '${t}' not found`}}catch(e){return{schema:`// Error: ${this.errorMessage(e)}`}}}async handleInferStateMachine(e){try{let t=e.messages;if(!Array.isArray(t))throw Error(`messages must be an array`);let n=t.some(e=>S(e)&&(e.direction===`in`||e.direction===`out`)),r;if(n){let e=t.map((e,t)=>{if(!S(e))throw Error(`messages[${t}] must be an object`);let n=e.direction,r=typeof e.payloadHex==`string`?e.payloadHex:``,i=typeof e.timestamp==`number`?e.timestamp:void 0,a=Buffer.from(r.replace(/\s+/g,``),`hex`);if(n!==`in`&&n!==`out`)throw Error(`messages[${t}].direction must be "in" or "out"`);return{direction:n,payload:a,...i===void 0?{}:{timestamp:i}}});r=this.getInferrer().inferStateMachine(e)}else{let e=t.map((e,t)=>le(e,t));r=this.getInferrer().infer(e)}return e.simplify===!0&&(r=this.getInferrer().simplify(r)),{stateMachine:r,mermaid:this.getInferrer().generateMermaid(r),success:!0}}catch(e){return{stateMachine:{...ct},success:!1,error:this.errorMessage(e)}}}async handleVisualizeState(e){try{let t=e.stateMachine;if(!S(t))return{mermaidDiagram:this.getInferrer().generateMermaid(ct)};let n=Array.isArray(t.states)?t.states:[],r=Array.isArray(t.transitions)?t.transitions:[],i=typeof t.initialState==`string`?t.initialState:``,a=Array.isArray(t.finalStates)?t.finalStates.filter(e=>typeof e==`string`):[];return{mermaidDiagram:this.getInferrer().generateMermaid({states:n.filter(e=>S(e)),transitions:r.filter(e=>S(e)),initial:i,initialState:i,finalStates:a})}}catch(e){return{mermaidDiagram:`stateDiagram-v2\n note right of empty: ${this.errorMessage(e)}`}}}},dt=class extends ut{async handlePayloadTemplateBuild(e){try{let t=e.fields;if(!Array.isArray(t))throw Error(`fields must be an array`);let{payload:n,segments:r}=ve(t.map((e,t)=>ge(e,t)),w(e.endian));return this.emitEvent(`protocol:payload_built`,{byteLength:n.length,fieldCount:r.length}),{hexPayload:n.toString(`hex`),byteLength:n.length,fields:r,success:!0}}catch(e){return{hexPayload:``,byteLength:0,fields:[],success:!1,error:this.errorMessage(e)}}}async handlePayloadMutate(e){let t=``;try{if(typeof e.hexPayload!=`string`)throw Error(`hexPayload must be a string`);t=j(e.hexPayload,`hexPayload`);let n=e.mutations;if(!Array.isArray(n))throw Error(`mutations must be an array`);let r=Buffer.from(t,`hex`),i=[];for(let[e,t]of n.entries()){let n=ye(t,e),a=be(r,n,e);r=a.payload,i.push(a.summary)}return this.emitEvent(`protocol:payload_mutated`,{byteLength:r.length,mutationCount:i.length}),{originalHex:t,mutatedHex:r.toString(`hex`),byteLength:r.length,appliedMutations:i,success:!0}}catch(e){return{originalHex:t,mutatedHex:``,byteLength:0,appliedMutations:[],success:!1,error:this.errorMessage(e)}}}},ft=class extends dt{async handleEthernetFrameBuild(e){try{let t=L(e.destinationMac,`destinationMac`),n=L(e.sourceMac,`sourceMac`),r=V(e.etherType,`etherType`),i=Ae(t,n,r,H(e.payloadHex,`payloadHex`));return this.emitEvent(`protocol:ethernet_frame_built`,{byteLength:i.length,etherType:`0x${r.toString(16).padStart(4,`0`)}`}),{destinationMac:t.canonical,sourceMac:n.canonical,etherType:r,etherTypeHex:`0x${r.toString(16).padStart(4,`0`)}`,byteLength:i.length,headerHex:i.subarray(0,14).toString(`hex`),frameHex:i.toString(`hex`),success:!0}}catch(e){return{destinationMac:``,sourceMac:``,etherType:0,etherTypeHex:`0x0000`,byteLength:0,headerHex:``,frameHex:``,success:!1,error:this.errorMessage(e)}}}async handleArpBuild(e){try{let t=e.operation===`reply`?`reply`:`request`,n=L(e.senderMac,`senderMac`),r=L(e.targetMac??`00:00:00:00:00:00`,`targetMac`),i=R(e.senderIp,`senderIp`),a=R(e.targetIp,`targetIp`),o=je({operation:t,hardwareType:e.hardwareType===void 0?1:T(e.hardwareType,`hardwareType`),protocolType:V(e.protocolType??`ipv4`,`protocolType`),hardwareSize:e.hardwareSize===void 0?6:E(e.hardwareSize,`hardwareSize`),protocolSize:e.protocolSize===void 0?4:E(e.protocolSize,`protocolSize`),senderMac:n,senderIp:i,targetMac:r,targetIp:a});return this.emitEvent(`protocol:arp_built`,{operation:t,byteLength:o.length}),{operation:t,byteLength:o.length,payloadHex:o.toString(`hex`),senderMac:n.canonical,senderIp:e.senderIp,targetMac:r.canonical,targetIp:e.targetIp,success:!0}}catch(e){return{operation:null,byteLength:0,payloadHex:``,senderMac:``,senderIp:``,targetMac:``,targetIp:``,success:!1,error:this.errorMessage(e)}}}},pt=class extends ft{async handleRawIpPacketBuild(e){try{let t=e.version===`ipv6`?`ipv6`:`ipv4`,n=H(e.payloadHex??``,`payloadHex`),r=Te(e.protocol,`protocol`),i=e.dscp===void 0?0:T(e.dscp,`dscp`),a=e.ecn===void 0?0:T(e.ecn,`ecn`);if(i>63)throw Error(`dscp must be between 0 and 63`);if(a>3)throw Error(`ecn must be between 0 and 3`);if(t===`ipv4`){let o=e.ttl===void 0?64:O(e.ttl,`ttl`),s=e.identification===void 0?0:T(e.identification,`identification`),c=e.fragmentOffset===void 0?0:T(e.fragmentOffset,`fragmentOffset`);if(s>65535)throw Error(`identification must be between 0 and 65535`);if(c>8191)throw Error(`fragmentOffset must be between 0 and 8191`);let{packet:l,checksum:u}=Me({sourceIp:B(e.sourceIp,`ipv4`,`sourceIp`),destinationIp:B(e.destinationIp,`ipv4`,`destinationIp`),protocol:r,payload:n,ttl:o,identification:s,dontFragment:e.dontFragment===!0,moreFragments:e.moreFragments===!0,fragmentOffset:c,dscp:i,ecn:a});return this.emitEvent(`protocol:ip_packet_built`,{version:t,protocol:r,byteLength:l.length}),{version:t,protocol:r,byteLength:l.length,headerLength:20,packetHex:l.toString(`hex`),headerHex:l.subarray(0,20).toString(`hex`),payloadHex:n.toString(`hex`),checksumHex:u.toString(16).padStart(4,`0`),success:!0}}let o=e.hopLimit===void 0?e.ttl===void 0?64:O(e.ttl,`ttl`):O(e.hopLimit,`hopLimit`),s=e.flowLabel===void 0?0:T(e.flowLabel,`flowLabel`);if(s>1048575)throw Error(`flowLabel must be between 0 and 1048575`);let c=Ne({sourceIp:B(e.sourceIp,`ipv6`,`sourceIp`),destinationIp:B(e.destinationIp,`ipv6`,`destinationIp`),protocol:r,payload:n,hopLimit:o,dscp:i,ecn:a,flowLabel:s});return this.emitEvent(`protocol:ip_packet_built`,{version:t,protocol:r,byteLength:c.length}),{version:t,protocol:r,byteLength:c.length,headerLength:40,packetHex:c.toString(`hex`),headerHex:c.subarray(0,40).toString(`hex`),payloadHex:n.toString(`hex`),checksumHex:null,success:!0}}catch(e){return{version:null,protocol:null,byteLength:0,headerLength:0,packetHex:``,headerHex:``,payloadHex:``,checksumHex:null,success:!1,error:this.errorMessage(e)}}}async handleIcmpEchoBuild(e){try{let t=e.operation===`reply`?`reply`:`request`,n=e.identifier===void 0?0:T(e.identifier,`identifier`),r=e.sequenceNumber===void 0?0:T(e.sequenceNumber,`sequenceNumber`);if(n>65535)throw Error(`identifier must be between 0 and 65535`);if(r>65535)throw Error(`sequenceNumber must be between 0 and 65535`);let i=H(e.payloadHex??``,`payloadHex`),{packet:a,checksum:o}=Pe({operation:t,identifier:n,sequenceNumber:r,payload:i}),s=o.toString(16).padStart(4,`0`);return this.emitEvent(`protocol:icmp_echo_built`,{operation:t,byteLength:a.length,checksumHex:s}),{operation:t,identifier:n,sequenceNumber:r,checksum:o,checksumHex:s,byteLength:a.length,packetHex:a.toString(`hex`),payloadHex:i.toString(`hex`),success:!0}}catch(e){return{operation:null,identifier:null,sequenceNumber:null,checksum:null,checksumHex:``,byteLength:0,packetHex:``,payloadHex:``,success:!1,error:this.errorMessage(e)}}}},mt=class extends pt{async handleChecksumApply(e){try{let t=H(e.hexPayload,`hexPayload`),n=e.startOffset===void 0?0:T(e.startOffset,`startOffset`),r=e.endOffset===void 0?t.length:T(e.endOffset,`endOffset`);if(n>r||r>t.length)throw Error(`checksum range must stay within the payload`);let i=e.zeroOffset===void 0?void 0:T(e.zeroOffset,`zeroOffset`),a=e.zeroLength===void 0?2:E(e.zeroLength,`zeroLength`),o=e.writeOffset===void 0?i:T(e.writeOffset,`writeOffset`),s=De(e.endian),c=Buffer.from(t);if(i!==void 0){if(i+a>c.length)throw Error(`zeroOffset and zeroLength must stay within the payload`);c.fill(0,i,i+a)}let l=U(c.subarray(n,r));if(o!==void 0){if(o+2>c.length)throw Error(`writeOffset must leave room for a 16-bit checksum field`);s===`little`?c.writeUInt16LE(l,o):c.writeUInt16BE(l,o)}let u=l.toString(16).padStart(4,`0`);return this.emitEvent(`protocol:checksum_applied`,{checksumHex:u,byteLength:c.length}),{checksumHex:u,checksum:l,mutatedHex:c.toString(`hex`),byteLength:c.length,rangeStart:n,rangeEnd:r,success:!0}}catch(e){return{checksumHex:``,checksum:0,mutatedHex:``,byteLength:0,rangeStart:0,rangeEnd:0,success:!1,error:this.errorMessage(e)}}}},ht=class extends mt{},gt=class extends ht{async handlePcapWrite(e){try{let t=this.parseRequiredPath(e);if(!Array.isArray(e.packets))throw Error(`packets must be an array`);let n=e.packets.map((e,t)=>Le(e,t)),r=Oe(e.endianness),i=ke(e.timestampPrecision),a=e.snapLength===void 0?65535:E(e.snapLength,`snapLength`),o=Ee(e.linkType??`ethernet`,`linkType`),s=Re({packets:n,endianness:r,timestampPrecision:i,snapLength:a,linkType:o});return await u(t,s),this.emitEvent(`protocol:pcap_written`,{path:t,packetCount:n.length,byteLength:s.length}),{path:t,packetCount:n.length,byteLength:s.length,endianness:r,timestampPrecision:i,linkType:o,success:!0}}catch(t){return{path:typeof e.path==`string`?e.path:``,packetCount:0,byteLength:0,endianness:null,timestampPrecision:null,linkType:null,success:!1,error:this.errorMessage(t)}}}async handlePcapRead(e){try{let t=this.parseRequiredPath(e),n=e.maxPackets===void 0?void 0:E(e.maxPackets,`maxPackets`),r=e.maxBytesPerPacket===void 0?void 0:E(e.maxBytesPerPacket,`maxBytesPerPacket`),{header:i,packets:a}=ze(await l(t),n,r);return this.emitEvent(`protocol:pcap_read`,{path:t,packetCount:a.length}),{path:t,header:i,packets:a,success:!0}}catch(t){return{path:typeof e.path==`string`?e.path:``,header:null,packets:[],success:!1,error:this.errorMessage(t)}}}parseRequiredPath(e){if(typeof e.path!=`string`||e.path.trim().length===0)throw Error(`path must be a non-empty string`);return e.path}},_t=class extends gt{},vt=class extends _t{async handleProtoFingerprint(o){let c=s(o,`hexPayloads`),l=o.includeKnownProtocols!==!1,u=o.includeFieldHints!==!1;return c.length===0?a({success:!1,error:`hexPayloads is required`}):a({success:!0,fingerprints:c.map((a,o)=>{let s=a.replace(/\s/g,``),c=[],d=s.length/2,f=d>=5?y(s,3):-1,p=Number.isFinite(f)&&f>=0&&d>=5+f,ee=p&&f>=t&&v(s,0)===22&&v(s,5)===1,m=ie(s),h=Object.keys(g).some(e=>s.toUpperCase().startsWith(e)),_=s.toUpperCase().startsWith(`5353482D`),b=s.length>=4&&(()=>{let e=v(s,0),t=v(s,1),n=e&15;if(n===0)return!1;let r=n<=10&&!(n>=3&&n<=7),i=(t>>7&1)==1,a=s.length/2,o=t&127,c=2;if(o===126){if(a<4)return!1;o=y(s,2),c=4}else if(o===127){if(a<10)return!1;let e=y(s,2)<<16|y(s,4),t=y(s,6)<<16|y(s,8);o=e>0?4294967295:t,c=10}return r&&a>=c+(i?4:0)+o})(),x=null;if(ee)c.push({protocol:`TLS ClientHello`,layer:`L6-TLS`,confidence:i}),u&&(x=ne(s));else if(h)c.push({protocol:`HTTP/1.x`,layer:`L7-HTTP`,confidence:e}),u&&(x={method:Object.entries(g).find(([e])=>s.toUpperCase().startsWith(e))?.[1]??`UNKNOWN`,httpVersion:s.indexOf(`2048545450`)>0?`1.x`:`unknown`});else if(_)c.push({protocol:`SSH`,layer:`L7-SSH`,confidence:r}),u&&s.length>=20&&(x={banner:Buffer.from(s.substring(0,Math.min(s.length,80)),`hex`).toString(`ascii`)});else if(b){if(c.push({protocol:`WebSocket`,layer:`L7-WS`,confidence:n}),u&&s.length>=4){let e=v(s,0),t=v(s,1),n=e&15,r=t>>7&1,i=t&127,a=2;if(i===126)i=s.length>=4?y(s,2):0,a=4;else if(i===127){if(s.length>=20){let e=y(s,2)<<16|y(s,4),t=y(s,6)<<16|y(s,8);i=e>0?4294967295:t}else i=0;a=10}r&&(a+=4),x={fin:e>>7&1,rsv1:e>>6&1,opcode:n,opcodeName:te[n]??`reserved(${n})`,masked:!!r,payloadLength:i,headerSize:a}}}else m&&(c.push({protocol:`DNS`,layer:`L7-DNS`,confidence:.85}),u&&(x=re(s)));l&&c.length===0&&(p&&/^160301|^160302|^160303/i.test(s.substring(0,8))&&c.push({protocol:`TLS Record`,layer:`L6-TLS`,confidence:.9}),s.substring(0,8).startsWith(`50524920`)&&c.push({protocol:`HTTP/2 PRI`,layer:`L7-HTTP2`,confidence:.9}));let S=[];if(u&&!x&&s.length>=8){let e=y(s,0);e>0&&e<s.length/2&&S.push({offset:0,hint:`possible length field (${e} bytes)`})}return{index:o,size:d,protocolMatches:c.length>0?c:[{protocol:`unknown`,layer:`unknown`,confidence:0}],...x?{parsedFields:x}:{},...S.length>0?{fieldHints:S}:{}}})})}},yt=class extends vt{};export{yt as ProtocolAnalysisHandlers};
@@ -0,0 +1 @@
1
+ import{zr as e}from"./constants-Cp6hBrrx.mjs";import{n as t}from"./response-C7rKQst4.mjs";import{i as n,r}from"./outputPaths-BonGThuc.mjs";import{a as i,i as a,s as o}from"./parse-args-Cuk7-xUt.mjs";import s from"node:http";import{createHash as c}from"node:crypto";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f}from"node:fs";import p from"node:path";import{fileURLToPath as m,pathToFileURL as h}from"node:url";import{mkdir as g,readFile as _,writeFile as v}from"node:fs/promises";import{EventEmitter as y}from"node:events";function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x(e){let t=e.trim().toLowerCase().replace(/\//g,`-`).replace(/(?!^@)[^a-z0-9@_-]+/g,`-`);return t.length>0?t:`plugin-${Date.now()}`}function S(e){if(!b(e))return null;let{id:t,name:n,version:r,entry:i,permissions:a,status:o}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||o!==`loaded`&&o!==`unloaded`?null:{id:t,name:n,version:r,entry:i,permissions:Array.isArray(a)?a.filter(e=>typeof e==`string`):[],status:o}}var C=class{rootDir;legacyPluginRoots;useLegacyScanApi;registryFile;moduleCacheDir;installedPlugins=new Map;loadedPlugins=new Map;constructor(e=r(),t=[]){let n=typeof e==`string`?e:r();this.useLegacyScanApi=typeof e!=`string`,this.rootDir=n,this.registryFile=p.join(n,`plugins.json`),this.moduleCacheDir=p.join(n,`modules`),this.legacyPluginRoots=t.length>0?t:process.env.JSHOOKMCP_PLUGIN_ROOT?[process.env.JSHOOKMCP_PLUGIN_ROOT]:[],!this.useLegacyScanApi&&this.initializeFromDisk()}async register(e){let t=x(e.id||e.name),n={id:t,name:e.name,version:e.version,entry:e.entry,permissions:e.permissions?[...e.permissions]:[],status:this.loadedPlugins.has(t)?`loaded`:`unloaded`};return this.installedPlugins.set(t,n),await this.persist(),t}async unregister(e){await this.unloadPlugin(e),this.installedPlugins.delete(e),await this.persist()}listInstalled(){return[...this.installedPlugins.values()].map(e=>({id:e.id,name:e.name,version:e.version,status:e.status,permissions:[...e.permissions]})).toSorted((e,t)=>e.name.localeCompare(t.name))}async loadPlugin(e){let t=this.installedPlugins.get(e);if(!t)throw Error(`Plugin not found: ${e}`);let n=this.loadedPlugins.get(e);if(n)return{manifest:this.toPublicManifest(n.manifest),exports:n.exports};let r=h(await this.resolveEntryPath(t));r.searchParams.set(`ts`,String(Date.now()));let i=await import(r.href),a=b(i)?i:{};return t.status=`loaded`,this.loadedPlugins.set(e,{manifest:t,exports:a}),await this.persist(),{manifest:this.toPublicManifest(t),exports:a}}async unloadPlugin(e){let t=this.installedPlugins.get(e);t&&(this.loadedPlugins.delete(e),t.status=`unloaded`,await this.persist())}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),l(this.moduleCacheDir)||u(this.moduleCacheDir,{recursive:!0}),!l(this.registryFile))return;let e=d(this.registryFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=S(e);t&&this.installedPlugins.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await g(this.moduleCacheDir,{recursive:!0}),await v(this.registryFile,JSON.stringify([...this.installedPlugins.values()],null,2),`utf8`)}async resolveEntryPath(e){return e.entry.startsWith(`http://`)||e.entry.startsWith(`https://`)?this.downloadRemoteModule(e.id,e.entry):e.entry.startsWith(`file://`)?m(new URL(e.entry)):p.isAbsolute(e.entry)?e.entry:p.resolve(n(),e.entry)}async downloadRemoteModule(e,t){let n=await fetch(t);if(!n.ok)throw Error(`Failed to download plugin module: ${n.status} ${n.statusText}`);let r=await n.text(),i=p.join(this.moduleCacheDir,`${x(e)}.mjs`),a=c(`sha256`).update(r).digest(`hex`);try{let e=await _(i,`utf8`);if(c(`sha256`).update(e).digest(`hex`)===a)return i}catch{}return await g(this.moduleCacheDir,{recursive:!0}),await v(i,r,`utf8`),i}toPublicManifest(e){return{id:e.id,name:e.name,version:e.version,entry:e.entry,permissions:[...e.permissions]}}listPlugins(){let e=[];for(let t of this.legacyPluginRoots){if(!l(t))continue;let n=f(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`))continue;let n=p.join(t,r.name,`package.json`);if(l(n))try{let t=JSON.parse(d(n,`utf8`)),r=this.toLegacyPluginInfo(t);r&&e.push(r)}catch{continue}}}return e}searchPlugins(e){let t=e.trim().toLowerCase();return t?this.listPlugins().filter(e=>e.name.toLowerCase().includes(t)||(e.description??``).toLowerCase().includes(t)||(e.capabilities??[]).some(e=>e.toLowerCase().includes(t))||(e.dependencies??[]).some(e=>e.toLowerCase().includes(t))):this.listPlugins()}async installPlugin(e){if(/^https:\/\/github\.com\/.+\.git$/u.test(e)||/^git@github\.com:.+\.git$/u.test(e))return{id:`git-plugin`,name:e.split(`/`).pop()?.replace(/\.git$/u,``)??`plugin`,version:`0.0.0`};if(e.includes(`://`)||e.startsWith(`git@`)||e===`invalid-url`)throw Error(`Invalid git URL`);if(e.startsWith(`/`)||e.includes(`\\`)){let t=p.join(e,`package.json`);if(!l(t))throw Error(`No package.json`);let n=JSON.parse(d(t,`utf8`)),r=this.toLegacyPluginInfo(n);if(!r)throw Error(`No package.json`);return r}for(let t of this.legacyPluginRoots){let n=p.join(t,e,`package.json`);if(!l(n))continue;let r=JSON.parse(d(n,`utf8`)),i=this.toLegacyPluginInfo(r);if(i)return i}throw Error(`Plugin not found`)}getPluginInfo(e){return this.listPlugins().find(t=>t.id===e||t.name===e)}getPluginDependencies(e){return this.getPluginInfo(e)?.dependencies??[]}async uninstallPlugin(e){}toLegacyPluginInfo(e){if(typeof e.name!=`string`)return null;let t=b(e.dependencies)?Object.keys(e.dependencies):[];return{id:x(e.name),name:e.name,version:typeof e.version==`string`?e.version:`0.0.0`,description:typeof e.description==`string`?e.description:void 0,capabilities:Array.isArray(e.capabilities)?e.capabilities.filter(e=>typeof e==`string`):void 0,dependencies:t}}};function w(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T(e){if(!w(e))return null;let{id:t,url:n,events:r,active:i}=e;return typeof t!=`string`||typeof n!=`string`||!Array.isArray(r)||typeof i!=`boolean`?null:{id:t,url:n,events:r.filter(e=>typeof e==`string`),active:i}}var E=class{rootDir;storageFile;webhooks=new Map;constructor(e=r()){this.rootDir=e,this.storageFile=p.join(e,`webhooks.json`),this.initializeFromDisk()}async registerWebhook(e,t){new URL(e);let n={id:`webhook-${Date.now()}-${this.webhooks.size+1}`,url:e,events:[...new Set(t.filter(e=>e.trim().length>0))],active:!0};return this.webhooks.set(n.id,n),await this.persist(),n.id}async sendEvent(e,t){let n=[...this.webhooks.values()].filter(t=>t.active&&(t.events.includes(e)||t.events.includes(`*`)));for(let r of n){let n=await fetch(r.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:e,payload:t,timestamp:new Date().toISOString()})});if(!n.ok)throw Error(`Webhook delivery failed for ${r.url}: ${n.status} ${n.statusText}`)}}listWebhooks(){return[...this.webhooks.values()].map(e=>({id:e.id,url:e.url,events:[...e.events],active:e.active}))}registerExternalCallback(e,t){let n=this.webhooks.get(e);if(n){n.url=t;return}this.webhooks.set(e,{id:e,url:t,events:[`*`],active:!0})}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),!l(this.storageFile))return;let e=d(this.storageFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=T(e);t&&this.webhooks.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await v(this.storageFile,JSON.stringify([...this.webhooks.values()],null,2),`utf8`)}};function D(e){return{...e}}function O(){return new Date().toISOString()}var k=class extends y{maxQueueSize;commands=new Map;order=[];maxRetries;retryDelay;processTimeout;nextId=1;constructor(t={}){super(),this.maxQueueSize=typeof t.maxQueueSize==`number`?t.maxQueueSize:1e3,this.maxRetries=typeof t.maxRetries==`number`?t.maxRetries:3,this.retryDelay=typeof t.retryDelay==`number`?t.retryDelay:0,this.processTimeout=typeof t.processTimeout==`number`?t.processTimeout:e}enqueue(e){if(this.order.length>=this.maxQueueSize)throw Error(`Command queue is full (${this.maxQueueSize})`);let t=`cmd-${this.nextId}`;this.nextId+=1;let n=O(),r={id:t,endpointId:e.endpointId,event:e.event,payload:e.payload,status:`pending`,retries:0,createdAt:n,updatedAt:n};return this.commands.set(t,r),this.order.push(t),this.emit(`enqueued`,D(r)),t}dequeue(e){if(!e){let e=this.getCommandsByFilter({status:`pending`})[0];return e?D(e):void 0}return this.getCommandsByFilter(e).map(D)}getStatus(e){let t=this.commands.get(e);return t?t.status===`processed`?`completed`:t.status:`failed`}retry(e){let t=this.commands.get(e);if(!t)throw Error(`Command ${e} not found`);if(t.status!==`failed`)throw Error(`Command ${e} is not in failed state`);t.status=`pending`,t.retries=0,t.lastError=void 0,t.updatedAt=O()}getCommand(e){return this.commands.get(e)}getCommandsByFilter(e){let t=e.status===`completed`?`processed`:e.status,n=[];for(let r of this.order){let i=this.commands.get(r);i&&(t&&i.status!==t||e.endpointId&&i.endpointId!==e.endpointId||n.push(i))}return n}updateStatus(e,t,n){let r=this.commands.get(e);if(!r)throw Error(`Command ${e} not found`);return r.status=t,r.updatedAt=O(),r.lastError=n,r}},A=class extends k{async process(e,t){let n=this.getCommand(e);if(!n)throw Error(`Command ${e} not found`);if(n.status===`processed`)throw Error(`Command ${e} already processed`);if(n.status===`failed`)throw Error(`Command ${e} already processed with failure`);if(n.status===`processing`)throw Error(`Command ${e} is already processing`);this.updateStatus(e,`processing`);let r=`processed`,i;try{await Promise.race([Promise.resolve(t(D(n))),new Promise((e,t)=>{setTimeout(()=>{t(Error(`Process timeout`))},this.processTimeout)})])}catch(e){i=e instanceof Error?e.message:String(e),r=n.retries+1>=this.maxRetries?`failed`:`pending`}if(i!==void 0&&this.retryDelay>0&&setTimeout(()=>{},this.retryDelay),r===`processed`){let t=this.updateStatus(e,`processed`);this.emit(`processed`,D(t))}else if(r===`pending`){n.retries+=1;let t=this.updateStatus(e,`pending`,i);throw this.emit(`retried`,D(t)),Error(i===void 0?`retry`:i)}else{let t=this.updateStatus(e,`failed`,i);throw this.emit(`failed`,D(t)),Error(i===void 0?`failed`:i)}}async retry(e){super.retry(e)}exportState(){let e=[];for(let t of this.order){let n=this.commands.get(t);n&&e.push(D(n))}return e}importState(e){this.commands.clear(),this.order.length=0;let t=0;for(let n of e){let e=D(n);this.commands.set(e.id,e),this.order.push(e.id);let r=/^cmd-(\d+)$/.exec(e.id);if(r&&r[1]){let e=parseInt(r[1],10);e>t&&(t=e)}}t>0&&(this.nextId=t+1)}};function j(e){return e===`tool_called`||e===`domain_activated`||e===`evidence_added`||e===`workflow_completed`}function M(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{rawBody:e}}}var N=class extends y{endpoints=new Map;eventHandlers=new Map;port;commandQueue;stats={eventsRegistered:0,webhooksSent:0};server;nextEndpointId=1;constructor(e={}){super(),this.port=typeof e.port==`number`?e.port:18789,this.commandQueue=e.commandQueue}registerEndpoint(e){let t=`ep-${this.nextEndpointId}`;return this.nextEndpointId+=1,this.endpoints.set(t,{id:t,path:e.path,method:e.method??`POST`,secret:e.secret}),this.emit(`endpointRegistered`,t),t}removeEndpoint(e){if(!this.endpoints.delete(e))throw Error(`Endpoint ${e} not found`);this.emit(`endpointRemoved`,e)}listEndpoints(){return[...this.endpoints.values()].map(e=>({...e}))}getPort(){return this.port}isRunning(){return this.server!==void 0}registerEvent(e,t){let n=this.eventHandlers.get(e)??[];n.push(t),this.eventHandlers.set(e,n),this.stats.eventsRegistered+=1}start(){if(this.server)throw Error(`Webhook server already started`);this.server=s.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.listen(this.port),this.emit(`started`,this.port)}async stop(){if(!this.server)return;let e=this.server;this.server=void 0,await new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})}),this.emit(`stopped`)}async sendWebhook(e,t,n){await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:t,payload:n})}),this.stats.webhooksSent+=1,this.stats.lastSentAt=new Date().toISOString()}getStats(){return{...this.stats}}async handleRequest(e,t){let n=e.method??`GET`,r=e.url??`/`,i=[...this.endpoints.values()].find(e=>e.path===r&&e.method===n);if(!i){t.statusCode=404,t.end(`not found`);return}if(i.secret&&e.headers[`x-webhook-secret`]!==i.secret){t.statusCode=401,t.end(`unauthorized`);return}let a=[];await new Promise((t,n)=>{e.setEncoding(`utf8`),e.on(`data`,e=>{a.push(e)}),e.on(`end`,()=>{t()}),e.on(`error`,e=>{n(e)})});let o=M(a.join(``));this.commandQueue&&this.commandQueue.enqueue({endpointId:i.id,payload:o}),o&&typeof o==`object`&&`event`in o&&typeof o.event==`string`&&await this.invokeEventHandlers(o.event,o),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!0,endpointId:i.id}))}async invokeEventHandlers(e,t){if(!j(e))return;let n=this.eventHandlers.get(e)??[];for(let e of n)await Promise.resolve(e(t))}},P=class extends N{};function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return typeof e==`function`}var L=class{registry;webhook;webhookServer;commandQueue;constructor(e,t){this.registry=e,this.webhook=t}async handleListInstalled(){return t({success:!0,plugins:this.getRegistry().listInstalled()})}async handleExecuteInContext(e){let n=o(e,`pluginId`),r=o(e,`contextName`),i=a(e,`args`)??{},{manifest:s,exports:c}=await this.getRegistry().loadPlugin(n),l=this.resolveContext(c,r);if(!l)throw Error(`Context "${r}" was not found in plugin "${n}"`);let u=await Promise.resolve(l(i));return this.emitEvent(`extension.executed`,{pluginId:n,contextName:r}),t({success:!0,manifest:s,contextName:r,result:u})}async handleReload(e){let n=o(e,`pluginId`);await this.getRegistry().unloadPlugin(n);let r=await this.getRegistry().loadPlugin(n);return this.emitEvent(`extension.reloaded`,{pluginId:n}),t({success:!0,pluginId:n,manifest:r.manifest,exportedKeys:Object.keys(r.exports).toSorted()})}async handleUninstall(e){let n=o(e,`pluginId`);return await this.getRegistry().unregister(n),this.emitEvent(`extension.uninstalled`,{pluginId:n}),t({success:!0,pluginId:n})}async handleWebhookCreate(e){let n=o(e,`name`),r=o(e,`path`),a=i(e,`secret`),s=Array.isArray(e.events)?e.events.filter(e=>typeof e==`string`):[],c=this.getWebhookServer();c.isRunning()||c.start();let l=c.registerEndpoint({path:r,method:`POST`,secret:a??void 0}),u=this.getWebhook(),d=`http://localhost:${c.getPort()}${r}`;return u.registerExternalCallback(l,d),t({success:!0,endpointId:l,url:d,name:n,events:s})}async handleWebhookList(){let e=this.getWebhookServer();return t({success:!0,endpoints:e.listEndpoints(),port:e.getPort(),running:e.isRunning()})}async handleWebhookDelete(e){let n=o(e,`endpointId`),r=this.getWebhookServer();try{r.removeEndpoint(n)}catch(e){throw Error(`GRACEFUL: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return t({success:!0,endpointId:n})}async handleWebhookCommands(e){let n=o(e,`endpointId`),r=i(e,`status`),s=a(e,`command`);if(s)return t({success:!0,commandId:this.getCommandQueue().enqueue({endpointId:n,payload:s}),status:`pending`});let c=this.getCommandQueue(),l={endpointId:n};r&&(l.status=r);let u=c.dequeue(l);return t({success:!0,endpointId:n,commands:u,count:Array.isArray(u)?u.length:+!!u})}getWebhookServer(){return this.webhookServer||=(this.commandQueue=new A,new P({commandQueue:this.commandQueue})),this.webhookServer}async startWebhookServer(){let e=this.getWebhookServer();e.isRunning()||e.start()}async stopWebhookServer(){this.webhookServer&&(await this.webhookServer.stop(),this.webhookServer=void 0,this.commandQueue=void 0)}getRegistry(){return this.registry||=new C,this.registry}getWebhook(){return this.webhook||=new E,this.webhook}getCommandQueue(){return this.commandQueue||=new A,this.commandQueue}emitEvent(e,t){this.getWebhook().sendEvent(e,t).catch(()=>void 0)}resolveContext(e,t){let n=e[t];if(I(n))return n;let r=e.default;if(t===`default`&&I(r))return r;if(F(r)){let e=r[t];if(I(e))return e}return null}async handleWebhookDispatch(e){let n=i(e,`action`);switch(n){case`create`:return this.handleWebhookCreate(e);case`list`:return this.handleWebhookList();case`delete`:return this.handleWebhookDelete(e);case`commands`:return this.handleWebhookCommands(e);default:return t({error:`Invalid action: "${n}". Expected one of: create, list, delete, commands`})}}};export{L as ExtensionRegistryHandlers};