@jshookmcp/jshook 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/README.md +3 -3
  2. package/README.zh.md +3 -3
  3. package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
  4. package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
  5. package/dist/CodeInjector-Btj9upnf.mjs +1 -0
  6. package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
  7. package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
  8. package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
  9. package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
  10. package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
  11. package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
  12. package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
  13. package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
  14. package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
  15. package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
  16. package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
  17. package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
  18. package/dist/MemoryScanner-Dxd657li.mjs +1 -0
  19. package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
  20. package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
  21. package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
  22. package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
  23. package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
  24. package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
  25. package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
  26. package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
  27. package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
  28. package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
  29. package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
  30. package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
  31. package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
  32. package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
  33. package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
  34. package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
  35. package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
  36. package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
  37. package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
  38. package/dist/antidebug-CsnpOR9z.mjs +1 -0
  39. package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
  40. package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
  41. package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
  42. package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
  43. package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
  44. package/dist/browser-BUaB25bk.mjs +11 -0
  45. package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
  46. package/dist/collector-CB2syQEg.mjs +1 -0
  47. package/dist/constants-DMv3svps.mjs +2 -0
  48. package/dist/coordination-Dbohmj6D.mjs +1 -0
  49. package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
  50. package/dist/debugger-CLzkObIO.mjs +1 -0
  51. package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
  52. package/dist/definitions-B3a9QC2t.mjs +1 -0
  53. package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
  54. package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
  55. package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
  56. package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
  57. package/dist/definitions-DBYSxChX.mjs +1 -0
  58. package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
  59. package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
  60. package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
  61. package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
  62. package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
  63. package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
  64. package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
  65. package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
  66. package/dist/definitions-EGmqr85H.mjs +1 -0
  67. package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
  68. package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
  69. package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
  70. package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
  71. package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
  72. package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
  73. package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
  74. package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
  75. package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
  76. package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
  77. package/dist/handlers-6iNsXOVT.mjs +7 -0
  78. package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
  79. package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
  80. package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
  81. package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
  82. package/dist/handlers-CWKBBjai.mjs +1 -0
  83. package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
  84. package/dist/handlers-CrJsKnEI.mjs +1 -0
  85. package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
  86. package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
  87. package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
  88. package/dist/handlers-gVscChvl.mjs +1 -0
  89. package/dist/handlers-xFvI9P_y.mjs +1 -0
  90. package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
  91. package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
  92. package/dist/index.mjs +11 -11
  93. package/dist/macro-p8kuJVcm.mjs +2 -0
  94. package/dist/maintenance-DAqADb6Z.mjs +302 -0
  95. package/dist/manifest-4lmM6MZR.mjs +1 -0
  96. package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
  97. package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
  98. package/dist/manifest-Box-jWfr.mjs +1 -0
  99. package/dist/manifest-Bp33di0Q.mjs +1 -0
  100. package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
  101. package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
  102. package/dist/manifest-C7TdXCWY.mjs +1 -0
  103. package/dist/manifest-CM-n64K0.mjs +1 -0
  104. package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
  105. package/dist/manifest-CWJS45iO.mjs +1 -0
  106. package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
  107. package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
  108. package/dist/manifest-Cgxu2qdv.mjs +1 -0
  109. package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
  110. package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
  111. package/dist/manifest-CvDpVToN.mjs +1 -0
  112. package/dist/manifest-D8TL9RLE.mjs +1 -0
  113. package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
  114. package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
  115. package/dist/manifest-DLGtZH-0.mjs +1 -0
  116. package/dist/manifest-DXHdPt2T.mjs +1 -0
  117. package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
  118. package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
  119. package/dist/manifest-G2H52LKz.mjs +131 -0
  120. package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
  121. package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
  122. package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
  123. package/dist/manifest-dG6MuR1U.mjs +1 -0
  124. package/dist/manifest-nWXtgq5Y2.mjs +1 -0
  125. package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
  126. package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
  127. package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
  128. package/dist/native-g095qhpK.mjs +961 -0
  129. package/dist/network-Dvxm7eEI.mjs +7 -0
  130. package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
  131. package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
  132. package/dist/platform-DjWbuiF8.mjs +93 -0
  133. package/dist/process-Dq5I-KZW.mjs +2 -0
  134. package/dist/proxy-DPNgM7TE.mjs +2 -0
  135. package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
  136. package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
  137. package/dist/search-defaults-CJik67or.mjs +1 -0
  138. package/dist/server/plugin-api.mjs +1 -1
  139. package/dist/sourcemap-DqEW15Ao.mjs +1 -0
  140. package/dist/streaming-Dbk4eStJ.mjs +1 -0
  141. package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
  142. package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
  143. package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
  144. package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
  145. package/package.json +2 -2
  146. package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
  147. package/dist/DOMInspector-C19J4zeq.mjs +0 -95
  148. package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
  149. package/dist/ExtensionManager-BD724zkO.mjs +0 -1
  150. package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
  151. package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
  152. package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
  153. package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
  154. package/dist/PageController-Dfsm1_o7.mjs +0 -1
  155. package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
  156. package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
  157. package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
  158. package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
  159. package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
  160. package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
  161. package/dist/VersionDetector-CHT36Az0.mjs +0 -9
  162. package/dist/apk-packer-BqXcInnX.mjs +0 -1
  163. package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
  164. package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
  165. package/dist/browser-Qqco2rOT.mjs +0 -11
  166. package/dist/collector-Bpl6qy2L.mjs +0 -1
  167. package/dist/constants-BYj8Xek8.mjs +0 -1
  168. package/dist/coordination-CWXW1o8K.mjs +0 -1
  169. package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
  170. package/dist/debugger-DyALjYMk.mjs +0 -1
  171. package/dist/definitions-BftdXgXI.mjs +0 -1
  172. package/dist/definitions-Bio5XJYy.mjs +0 -1
  173. package/dist/definitions-CMZRSy3k.mjs +0 -1
  174. package/dist/definitions-DP1vgxEY.mjs +0 -1
  175. package/dist/definitions-Tls8c0A0.mjs +0 -1
  176. package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
  177. package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
  178. package/dist/handlers-8zN_vBIz.mjs +0 -1
  179. package/dist/handlers-DHO3rjsW.mjs +0 -1
  180. package/dist/handlers-FJ80VzUI.mjs +0 -2
  181. package/dist/handlers-VHWrxbM_.mjs +0 -1
  182. package/dist/handlers-mPFiNPe8.mjs +0 -302
  183. package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
  184. package/dist/maintenance-BUpIukhg.mjs +0 -1
  185. package/dist/manifest-B7NB2rh2.mjs +0 -1
  186. package/dist/manifest-BDi4nbH1.mjs +0 -1
  187. package/dist/manifest-BLDfkE7n.mjs +0 -1
  188. package/dist/manifest-BcXbB4gf.mjs +0 -1
  189. package/dist/manifest-Bdnc_vrc.mjs +0 -1
  190. package/dist/manifest-BuYKgCnp.mjs +0 -1
  191. package/dist/manifest-CBfNnGPV.mjs +0 -1
  192. package/dist/manifest-CPS1Xv69.mjs +0 -1
  193. package/dist/manifest-CRryuZF4.mjs +0 -1
  194. package/dist/manifest-CvTe5ZGV2.mjs +0 -1
  195. package/dist/manifest-D-5GH0DV.mjs +0 -1
  196. package/dist/manifest-D3Ssf3IC.mjs +0 -1
  197. package/dist/manifest-D5ck3NvC.mjs +0 -1
  198. package/dist/manifest-DG19q-Ld.mjs +0 -1
  199. package/dist/manifest-DLMlD0Zc.mjs +0 -1
  200. package/dist/manifest-DwL2ik8P.mjs +0 -1
  201. package/dist/manifest-ItF5P8A12.mjs +0 -1
  202. package/dist/manifest-KZphqIyX.mjs +0 -1
  203. package/dist/manifest-RcpX_MyZ.mjs +0 -123
  204. package/dist/manifest-Zy7Odg5J.mjs +0 -1
  205. package/dist/manifest-ff1H7Pdp.mjs +0 -1
  206. package/dist/manifest-iuhF6pTL2.mjs +0 -1
  207. package/dist/manifest-yC16OhL2.mjs +0 -1
  208. package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
  209. package/dist/native-j8l473zn.mjs +0 -961
  210. package/dist/network-T0VRwNPd.mjs +0 -7
  211. package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
  212. package/dist/platform-CzaQtISh.mjs +0 -93
  213. package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
  214. package/dist/process-CWhsCWrf.mjs +0 -2
  215. package/dist/proxy-DZFlDsG3.mjs +0 -2
  216. package/dist/search-defaults-lYBVn_3L.mjs +0 -1
  217. package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
  218. package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
  219. package/dist/streaming-BcJ0B6ao.mjs +0 -1
  220. package/dist/types-D9EiE5o9.mjs +0 -1
  221. /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
  222. /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
  223. /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
  224. /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
  225. /package/dist/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
  226. /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.mjs} +0 -0
  227. /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
  228. /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
  229. /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
  230. /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
  231. /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
  232. /package/dist/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
  233. /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
  234. /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
  235. /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
  236. /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
  237. /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
  238. /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
  239. /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
  240. /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
  241. /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
@@ -0,0 +1,961 @@
1
+ import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import{Bn as n,Fn as r,Gn as i,Hn as a,In as o,Kn as s,Kt as c,Ln as l,Mn as u,Nn as d,Ot as f,Pn as p,Rn as m,Vn as h,Wn as g,Xi as _,Yn as v,aa as ee,fr as y,jn as b,kt as x,oa as te,pr as S,qn as ne,zn as re}from"./constants-DMv3svps.mjs";import{t as C}from"./ProcessRegistry-D5y1yuP2.mjs";import{v as w,y as ie}from"./Win32API-DoP3MMHS.mjs";import{n as ae}from"./concurrency-Dehnw4JC.mjs";import{i as T,r as oe,t as se}from"./factory-BxNdBiZa.mjs";import{i as ce,r as E,t as D}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{existsSync as O,promises as le,readFileSync as ue}from"fs";import{platform as de,tmpdir as k}from"node:os";import{closeSync as fe,openSync as pe,promises as A,readFileSync as me,readSync as he}from"node:fs";import{join as j}from"node:path";import{fileURLToPath as ge}from"node:url";import{promisify as _e}from"node:util";import{exec as ve}from"node:child_process";import{exec as M,execFile as ye,spawn as N}from"child_process";import{promisify as P}from"util";var F=e({execAsync:()=>I,execFileAsync:()=>L,executePowerShellScript:()=>R});const I=P(M),L=P(ye);function be(){return process.platform===`win32`?`powershell.exe`:`powershell`}async function R(e,t={}){let n=[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,Buffer.from(e,`utf16le`).toString(`base64`)],{stdout:r,stderr:i}=await L(be(),n,{maxBuffer:t.maxBuffer??1024*1024,timeout:t.timeout,windowsHide:!0});return{stdout:String(r??``),stderr:String(i??``)}}async function xe(e){if(process.platform===`darwin`)return Se(e);if(!ie())return{available:!1,reason:`Native memory operations require Windows or macOS. Current platform: ${process.platform}`};if(!w())return{available:!1,reason:`koffi library not available. Install with: pnpm add koffi`};try{let{stdout:t}=await e(`powershell.exe -NoProfile -Command "([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"`,{timeout:5e3});if(t.trim().toLowerCase()!==`true`)return{available:!1,reason:`Native memory operations require Administrator privileges. Run as Administrator.`}}catch{return{available:!1,reason:`Failed to check Administrator privileges.`}}return{available:!0}}async function Se(e){try{(await import(`koffi`)).default.load(`/usr/lib/libSystem.B.dylib`).unload()}catch{return{available:!1,reason:`koffi library cannot load libSystem.B.dylib. Install koffi with: pnpm add koffi`}}let t=``;try{let{stdout:n}=await e(`csrutil status 2>&1 || true`,{timeout:5e3});t=n.trim()}catch{}return process.getuid&&process.getuid()!==0?{available:!1,reason:`macOS memory operations require root privileges for task_for_pid. Run with: sudo node <your-script>.${t?` SIP status: ${t}`:``}`}:{available:!0}}const Ce=_e(ve);function we(e,t,n,r,i=16777216){if(t.length===0||e.regionSize<t.length||i<=0)return[];let a=Math.max(t.length-1,0),o=Buffer.alloc(0),s=[];for(let c=0;c<e.regionSize;c+=i){let l=Math.min(i,e.regionSize-c),u=r(e.baseAddress+BigInt(c),l),d=o.length>0?Buffer.concat([o,u]):u,f=D(d,t,n);for(let t of f){let n=c+t-o.length;s.push(e.baseAddress+BigInt(n))}if(a===0||c+l>=e.regionSize){o=Buffer.alloc(0);continue}let p=Math.min(a,d.length);o=d.subarray(d.length-p)}return s}var Te=class{providerCache=null;get provider(){return this.providerCache||=se(),this.providerCache}set provider(e){this.providerCache=e}async checkAvailability(){return xe(Ce)}async readMemory(e,n,r){try{let t=BigInt(n.startsWith(`0x`)?n:`0x${n}`),i=this.provider.openProcess(e,!1);try{let{data:e}=this.provider.readMemory(i,t,r);return{success:!0,data:e.toString(`hex`).toUpperCase().match(/.{2}/g)?.join(` `)||``}}finally{this.provider.closeProcess(i)}}catch(i){return t.error(`Native memory read failed`,{pid:e,address:n,size:r,error:i instanceof Error?i.message:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}async writeMemory(e,n,r,i=`hex`){try{let t=BigInt(n.startsWith(`0x`)?n:`0x${n}`),a;a=i===`base64`?Buffer.from(r,`base64`):Buffer.from(r.replace(/\s/g,``),`hex`);let o=this.provider.openProcess(e,!0);try{let{bytesWritten:e}=this.provider.writeMemory(o,t,a);return{success:!0,bytesWritten:e}}finally{this.provider.closeProcess(o)}}catch(a){return t.error(`Native memory write failed`,{pid:e,address:n,encoding:i,dataLength:r.length,error:a instanceof Error?a.message:String(a)}),{success:!1,error:a instanceof Error?a.message:String(a)}}}async enumerateRegions(e){try{let t=this.provider.openProcess(e,!1),n=[];try{let e=0n,r=_;for(;e<r;){let r=this.provider.queryRegion(t,e);if(!r)break;n.push(Ee(r)),e=r.baseAddress+BigInt(r.size)}return{success:!0,regions:n}}finally{this.provider.closeProcess(t)}}catch(n){return t.error(`Native region enumeration failed`,{pid:e,error:n instanceof Error?n.message:String(n)}),{success:!1,error:n instanceof Error?n.message:String(n)}}}async checkMemoryProtection(e,n){try{let t=BigInt(n.startsWith(`0x`)?n:`0x${n}`),r=this.provider.openProcess(e,!1);try{let e=this.provider.queryRegion(r,t);return e?{success:!0,protection:De(e.protection),isWritable:e.isWritable,isReadable:e.isReadable,isExecutable:e.isExecutable,regionStart:`0x${e.baseAddress.toString(16).toUpperCase()}`,regionSize:e.size}:{success:!1,error:`Failed to query memory region`}}finally{this.provider.closeProcess(r)}}catch(r){return t.error(`Native protection check failed`,{pid:e,address:n,error:r instanceof Error?r.message:String(r)}),{success:!1,error:r instanceof Error?r.message:String(r)}}}async scanMemory(e,n,r=`hex`){try{let{patternBytes:t,mask:i}=ce(n,r);if(t.length===0)return{success:!1,addresses:[],error:`Invalid pattern`};let a=1e4,o=[],s=this.provider.openProcess(e,!1),c=[];try{let e=0n,n=_;for(;e<n;){let t=this.provider.queryRegion(s,e);if(!t)break;t.isReadable&&t.size>0&&t.size<=2**53-1&&o.push({baseAddress:t.baseAddress,regionSize:t.size}),e=t.baseAddress+BigInt(t.size)}let r=this.provider;c=await Promise.all(o.map(e=>ae(async()=>{try{return we(e,t,i,(e,t)=>r.readMemory(s,e,t).data)}catch{return[]}})))}finally{this.provider.closeProcess(s)}let l=[];for(let e of c){for(let t of e)if(l.push(`0x${t.toString(16).toUpperCase()}`),l.length>=a)break;if(l.length>=a)break}return{success:!0,addresses:l,stats:{patternLength:t.length,resultsFound:l.length}}}catch(i){return t.error(`Native memory scan failed`,{pid:e,patternType:r,patternLength:n.length,error:i instanceof Error?i.message:String(i)}),{success:!1,addresses:[],error:i instanceof Error?i.message:String(i)}}}async enumerateModules(e){try{let t=this.provider.openProcess(e,!1);try{return{success:!0,modules:this.provider.enumerateModules(t).map(e=>({name:e.name,baseAddress:`0x${e.baseAddress.toString(16).toUpperCase()}`,size:e.size}))}}finally{this.provider.closeProcess(t)}}catch(n){return t.error(`Native module enumeration failed`,{pid:e,error:n instanceof Error?n.message:String(n)}),{success:!1,error:n instanceof Error?n.message:String(n)}}}async injectDll(e,n){if(process.platform!==`win32`)return{success:!1,error:`DLL injection is only supported on Windows`};try{let{openProcessForMemory:t,CloseHandle:r,WriteProcessMemory:i,VirtualAllocEx:a,CreateRemoteThread:o,GetModuleHandle:s,GetProcAddress:c,PAGE:l,MEM:u}=await import(`./Win32API-DoP3MMHS.mjs`).then(e=>e.g),d=t(e,!0);try{let e=c(s(`kernel32.dll`),`LoadLibraryA`);if(!e)return{success:!1,error:`Failed to get LoadLibraryA address`};let t=Buffer.from(n+`\0`,`ascii`),f=a(d,0n,t.length,u.COMMIT|u.RESERVE,l.READWRITE);if(!f)return{success:!1,error:`Failed to allocate remote memory`};i(d,f,t);let{handle:p,threadId:m}=o(d,e,f);return p?(r(p),{success:!0,remoteThreadId:m}):{success:!1,error:`Failed to create remote thread`}}finally{r(d)}}catch(r){return t.error(`Native DLL injection failed`,{pid:e,dllPath:n,error:r instanceof Error?r.message:String(r)}),{success:!1,error:r instanceof Error?r.message:String(r)}}}async injectShellcode(e,n,r=`hex`){if(process.platform!==`win32`)return{success:!1,error:`Shellcode injection is only supported on Windows`};try{let t;t=r===`base64`?Buffer.from(n,`base64`):Buffer.from(n.replace(/\s/g,``),`hex`);let{openProcessForMemory:i,CloseHandle:a,WriteProcessMemory:o,VirtualAllocEx:s,VirtualProtectEx:c,CreateRemoteThread:l,PAGE:u,MEM:d}=await import(`./Win32API-DoP3MMHS.mjs`).then(e=>e.g),f=i(e,!0);try{let e=s(f,0n,t.length,d.COMMIT|d.RESERVE,u.READWRITE);if(!e)return{success:!1,error:`Failed to allocate remote memory`};o(f,e,t);let{success:n}=c(f,e,t.length,u.EXECUTE_READWRITE);if(!n)return{success:!1,error:`Failed to change memory protection`};let{handle:r,threadId:i}=l(f,e,0n);return r?(a(r),{success:!0,remoteThreadId:i}):{success:!1,error:`Failed to create remote thread`}}finally{a(f)}}catch(i){return t.error(`Native shellcode injection failed`,{pid:e,encoding:r,shellcodeLength:n.length,error:i instanceof Error?i.message:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}async checkDebugPort(e){if(process.platform!==`win32`)return{success:!1,error:`Debug port check is only supported on Windows`};try{let{openProcessForMemory:t,CloseHandle:n,NtQueryInformationProcess:r}=await import(`./Win32API-DoP3MMHS.mjs`).then(e=>e.g),i=t(e,!1);try{let{status:e,debugPort:t}=r(i,7);return e===0?{success:!0,isDebugged:t!==0}:{success:!1,error:`NtQueryInformationProcess failed with status 0x${e.toString(16)}`}}finally{n(i)}}catch(n){return t.error(`Native debug port check failed`,{pid:e,error:n instanceof Error?n.message:String(n)}),{success:!1,error:n instanceof Error?n.message:String(n)}}}};function Ee(e){return{baseAddress:`0x${e.baseAddress.toString(16).toUpperCase()}`,size:e.size,state:e.state.toUpperCase(),protection:De(e.protection),isReadable:e.isReadable,isWritable:e.isWritable,isExecutable:e.isExecutable,type:e.type.toUpperCase()}}function De(e){if(e===0)return`NOACCESS`;let t=[],n=(e&1)!=0,r=(e&2)!=0,i=(e&4)!=0,a=(e&8)!=0;return n&&r&&i?t.push(`RWX`):n&&i?t.push(`RX`):n&&r?t.push(`RW`):n?t.push(`R`):i&&t.push(`X`),a&&t.push(`GUARD`),t.join(` `)||`UNKNOWN`}const z=new Te;let B=null;function Oe(){if(B)return B;try{return B=ge(new URL(`.`,import.meta.url)),B}catch{return null}}var V=class{scriptCache=new Map;scriptsDir;constructor(){let e=Oe();e&&O(j(e,`native`,`scripts`))?this.scriptsDir=j(e,`native`,`scripts`):e&&O(j(e,`scripts`))?this.scriptsDir=j(e,`scripts`):O(j(process.cwd(),`dist`,`native`,`scripts`))?this.scriptsDir=j(process.cwd(),`dist`,`native`,`scripts`):O(j(process.cwd(),`src`,`native`,`scripts`))?this.scriptsDir=j(process.cwd(),`src`,`native`,`scripts`):this.scriptsDir=j(process.cwd(),`dist`,`native`,`scripts`)}async loadScript(e){if(this.scriptCache.has(e))return this.scriptCache.get(e);let t=de(),n=t===`win32`?`windows`:t===`darwin`?`macos`:`linux`,r=j(this.scriptsDir,n,e),i=await le.readFile(r,`utf-8`);return this.scriptCache.set(e,i),i}getScriptPath(e){let t=de(),n=t===`win32`?`windows`:t===`darwin`?`macos`:`linux`;return j(this.scriptsDir,n,e)}clearCache(){this.scriptCache.clear()}},ke=class{scriptLoader;browserSignatures=new Map([[`chrome`,{windowClasses:[`Chrome_WidgetWin_0`,`Chrome_WidgetWin_1`,`Chrome_WidgetWin_*`],processNames:[`chrome.exe`,`chrome`],mainWindowTitle:/.*- Google Chrome$/,debugPorts:[9222,9229,9333]}],[`edge`,{windowClasses:[`Edge_WidgetWin_0`,`Edge_WidgetWin_1`,`Edge_WidgetWin_*`],processNames:[`msedge.exe`,`msedge`],mainWindowTitle:/.*- Microsoft Edge$/,debugPorts:[9222,9229]}],[`firefox`,{windowClasses:[`MozillaWindowClass`],processNames:[`firefox.exe`,`firefox`],mainWindowTitle:/.*- Mozilla Firefox$/,debugPorts:[9222]}]]);constructor(){this.scriptLoader=new V}sanitizePsInput(e){return e.replace(/[`$"'{}();|<>@#%!\\\n\r]/g,``)}escapePowerShellSingleQuoted(e){return this.sanitizePsInput(e).replace(/'/g,`''`)}async discoverBrowsers(){let e=[];for(let[t,n]of this.browserSignatures){let r=await this.findBySignature(t,n);e.push(...r)}return e}async findBySignature(e,t){let n=[],r=new Set;for(let i of t.processNames){let t=await this.findByProcessName(i);for(let i of t)r.has(i.pid)||(r.add(i.pid),n.push({type:e,pid:i.pid,hwnd:i.hwnd,title:i.title}))}for(let i of t.windowClasses){let t=await this.findByWindowClass(i);for(let i of t)r.has(i.pid)||(r.add(i.pid),n.push({type:e,pid:i.pid,hwnd:i.hwnd,title:i.title}))}for(let e of n){let n=await this.detectDebugPort(e.pid,t.debugPorts);n&&(e.debugPort=n)}return n}async findByWindowClass(e){let t=this.scriptLoader.getScriptPath(`enum-windows-by-class.ps1`);try{let n=this.escapePowerShellSingleQuoted(e),{execFile:r}=await import(`child_process`),{promisify:i}=await import(`util`),{stdout:a}=await i(r)(`powershell.exe`,[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,t,`-ClassPattern`,n],{maxBuffer:1024*1024*10});return this.parseWindowsResult(a,e)}catch(t){return console.error(`Failed to find windows by class '${e}':`,t),[]}}async findByProcessName(e){try{let t=`$Pattern='${this.escapePowerShellSingleQuoted(e)}'; Get-Process -Name "*$Pattern*" -ErrorAction SilentlyContinueSelect-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64ConvertTo-Json -Compress`,{execFile:n}=await import(`child_process`),{promisify:r}=await import(`util`),{stdout:i}=await r(n)(`powershell.exe`,[`-NoProfile`,`-Command`,t],{maxBuffer:1024*1024*10});return this.parseProcessResult(i,e)}catch(t){return console.error(`Failed to find process by name '${e}':`,t),[]}}parseWindowsResult(e,t){let n=[];if(!e.trim()||e.trim()===`null`)return n;try{let t=JSON.parse(e.trim()),r=Array.isArray(t)?t:[t];for(let e of r){let t=`unknown`,r=e.Title||``;for(let[e,n]of this.browserSignatures)if(n.mainWindowTitle?.test(r)){t=e;break}if(t===`unknown`)for(let[n,r]of this.browserSignatures){for(let i of r.windowClasses){let r=i.replace(/\*/g,`.*`);if(new RegExp(r).test(e.ClassName||``)){t=n;break}}if(t!==`unknown`)break}n.push({type:t,pid:e.ProcessId,hwnd:e.Handle,title:e.Title})}}catch(e){console.error(`Failed to parse windows result:`,e)}return n}parseProcessResult(e,t){let n=[];if(!e.trim()||e.trim()===`null`)return n;try{let t=JSON.parse(e.trim()),r=Array.isArray(t)?t:[t];for(let e of r){let t=`unknown`,r=(e.ProcessName||``).toLowerCase();r.includes(`chrome`)?t=`chrome`:r.includes(`msedge`)||r.includes(`edge`)?t=`edge`:r.includes(`firefox`)&&(t=`firefox`),n.push({type:t,pid:e.Id,hwnd:e.MainWindowHandle?.toString(),title:e.MainWindowTitle})}}catch(e){console.error(`Failed to parse process result:`,e)}return n}async detectDebugPort(e,t){let n=await this.checkDebugPortFromCommandLine(e);if(n)return n;for(let n of t)if(await this.checkPort(e,n))return n;return null}async checkDebugPortFromCommandLine(e){let{execFile:t}=await import(`child_process`),{promisify:n}=await import(`util`),r=n(t);try{if(!Number.isFinite(e)||e<=0)return null;let{stdout:t}=await r(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-CimInstance Win32_Process -Filter "ProcessId = ${Math.trunc(e)}"Select-Object CommandLine, ParentProcessId | ConvertTo-Json -Compress`],{maxBuffer:1024*1024});if(!t.trim()||t.trim()===`null`)return null;let n=(JSON.parse(t.trim()).CommandLine||``).match(/--remote-debugging-port=(\d+)/);return n?.[1]?parseInt(n[1],10):null}catch{return null}}async checkPort(e,t){let{execFile:n}=await import(`child_process`),{promisify:r}=await import(`util`),i=r(n);try{if(!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)return!1;let{stdout:n}=await i(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-NetTCPConnection -OwningProcess ${Math.trunc(e)} -State Listen -ErrorAction SilentlyContinueSelect-Object LocalPort | ConvertTo-Json -Compress`],{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return!1;let r=JSON.parse(n.trim()),a=Array.isArray(r)?r:[r];for(let e of a)if(e.LocalPort===t)return!0;return!1}catch{return!1}}};function H(e,t){return t?typeof t==`string`?e.includes(t):t.test(e):!1}async function Ae(e,t){let n={rendererProcesses:[],utilityProcesses:[]};try{let r;if(e.processNamePattern instanceof RegExp){let n=await t.findProcesses(``),i=e.processNamePattern;r=n.filter(e=>i.test(e.name))}else{let n=e.processNamePattern||`chromium`;r=await t.findProcesses(n)}for(let e of r){let r=await t.getProcessCommandLine(e.pid);if(r?.commandLine){let t=r.commandLine.toLowerCase();t.includes(`--type=renderer`)?n.rendererProcesses.push({...e,...r}):t.includes(`--type=gpu-process`)?n.gpuProcess={...e,...r}:t.includes(`--type=utility`)?n.utilityProcesses.push({...e,...r}):t.includes(`--type=`)||(n.mainProcess={...e,...r})}else n.mainProcess||=e}let i=[n.mainProcess?.pid,...n.rendererProcesses.map(e=>e.pid)].filter(Boolean),a=t=>H(t.title,e.windowTitlePattern)||H(t.className,e.windowClassPattern);for(let e of i){let r=(await t.getProcessWindows(e)).find(a);if(r){n.targetWindow=r;break}}return t.logInfo(`Chromium processes found:`,{main:n.mainProcess?.pid,renderers:n.rendererProcesses.length,hasTargetWindow:!!n.targetWindow}),n}catch(e){return t.logError(`Failed to find Chromium processes:`,e),n}}const je={processNamePattern:/^(chromium|chrome|msedge)$/i,windowClassPattern:`Chrome_WidgetWin`},U=P(M);function Me(e){return String(e||``).replace(/[`$"'{}();|<>@#%!\\\n\r]/g,``)}function W(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}var Ne=class{powershellPath=`powershell.exe`;scriptLoader;browserDiscovery;processCache=new Map;constructor(){this.scriptLoader=new V,this.browserDiscovery=new ke,t.info(`ProcessManager initialized for Windows platform`)}async findProcesses(e){try{let n=Me(String(e||``).trim()),r=n.toLowerCase()||`*`,i=Date.now(),a=this.processCache.get(r);if(a&&a.expiresAt>i)return a.snapshot;let o;o=n?`Get-Process -Name "*${n.replace(/"/g,`""`)}*" -ErrorAction SilentlyContinue Select-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64 ConvertTo-Json -Compress`:`Get-Process -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64 | ConvertTo-Json -Compress`;let{stdout:s}=await U(`${this.powershellPath} -NoProfile -Command "${o}"`,{maxBuffer:S}),c=s.trim(),l=[];if(c&&c!==`null`){let e=JSON.parse(c),t=Array.isArray(e)?e:[e];for(let e of t)l.push({pid:e.Id,name:e.ProcessName,executablePath:e.Path})}let u=new Map;for(let e of l)u.set(e.pid,e);let d=this.computeProcessDiff(a?.byPid??new Map,u);this.processCache.set(r,{expiresAt:i+3e3,snapshot:l,byPid:u,lastDelta:d});let f=n.length>0?`'${n}'`:`all`;return t.info(`Found ${l.length} processes matching ${f}`),l}catch(n){return t.error(`Failed to find processes with pattern '${e}':`,n),[]}}computeProcessDiff(e,t){let n=[],r=[],i=[];for(let[r,a]of t){let t=e.get(r);if(!t){n.push(a);continue}(t.pid!==a.pid||t.name!==a.name||t.executablePath!==a.executablePath)&&i.push({before:t,after:a})}for(let[n,i]of e)t.has(n)||r.push(i);return{added:n,removed:r,changed:i}}async getProcessByPid(e){try{e=W(e);let t=`Get-Process -Id ${e} -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, Path, MainWindowTitle, MainWindowHandle, CPU, WorkingSet64, StartTime | ConvertTo-Json -Compress`,{stdout:n}=await U(`${this.powershellPath} -NoProfile -Command "${t}"`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return null;let r=JSON.parse(n.trim());return{pid:r.Id,name:r.ProcessName,executablePath:r.Path,windowTitle:r.MainWindowTitle,windowHandle:r.MainWindowHandle?.toString(),cpuUsage:r.CPU,memoryUsage:r.WorkingSet64}}catch(n){return t.error(`Failed to get process by PID ${e}:`,n),null}}async getProcessWindows(e){try{e=W(e);let t=await this.scriptLoader.getScriptPath(`enum-windows.ps1`),{stdout:n}=await U(`${this.powershellPath} -NoProfile -ExecutionPolicy Bypass -File "${t}" -TargetPid ${e}`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return[];let r=JSON.parse(n.trim()),i=[],a=Array.isArray(r)?r:[r];for(let e of a)i.push({handle:e.Handle,title:e.Title,className:e.ClassName,processId:e.ProcessId,threadId:0});return i}catch(n){return t.error(`Failed to get windows for PID ${e}:`,n),[]}}async findChromiumProcesses(e=je){return Ae(e,{findProcesses:e=>this.findProcesses(e),getProcessCommandLine:e=>this.getProcessCommandLine(e),getProcessWindows:e=>this.getProcessWindows(e),logInfo:(e,n)=>t.info(e,n),logError:(e,n)=>t.error(e,n)})}async findChromiumAppProcesses(){return this.findChromiumProcesses()}async getProcessCommandLine(e){try{e=W(e);let t=`Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}' | Select-Object CommandLine, ParentProcessId | ConvertTo-Json -Compress`,{stdout:n}=await U(`${this.powershellPath} -NoProfile -Command "${t}"`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return{};let r=JSON.parse(n.trim());return{commandLine:r.CommandLine,parentPid:r.ParentProcessId}}catch(n){return t.error(`Failed to get command line for PID ${e}:`,n),{}}}async checkDebugPort(e,n){try{e=W(e);let t=n?.commandLine??(await this.getProcessCommandLine(e)).commandLine;if(t){let e=t.match(/--remote-debugging-port=(\d+)/);if(e?.[1])return parseInt(e[1],10)}let r=`Get-NetTCPConnection -OwningProcess ${e} -State Listen -ErrorAction SilentlyContinueSelect-Object LocalPort | ConvertTo-Json -Compress`,{stdout:i}=await U(`${this.powershellPath} -NoProfile -Command "${r}"`,{maxBuffer:1024*1024});if(i.trim()&&i.trim()!==`null`){let e=JSON.parse(i.trim()),t=Array.isArray(e)?e:[e];for(let e of t)if(f.includes(e.LocalPort))return e.LocalPort}return null}catch(n){return t.error(`Failed to check debug port for PID ${e}:`,n),null}}async findPidByListeningPort(e){try{let t=`Get-NetTCPConnection -LocalPort ${e} -State Listen -ErrorAction SilentlyContinueSelect-Object -First 1 OwningProcess | ConvertTo-Json -Compress`,{stdout:n}=await U(`${this.powershellPath} -NoProfile -Command "${t}"`,{maxBuffer:1024*1024});if(!n.trim()||n.trim()===`null`)return null;let r=JSON.parse(n.trim()),i=Array.isArray(r)?r[0]:r,a=i?.OwningProcess??i?.owningProcess??i,o=Number(a);return Number.isFinite(o)&&o>0?o:null}catch{return null}}async launchWithDebug(e,n=x,r=[]){try{let i=N(e,[`--remote-debugging-port=${n}`,...r],{detached:!0,stdio:`ignore`});i.unref(),C.register(i);let a=i.pid||0,o=e.split(/[\\/]/).pop()||`unknown`,s=a>0?a:null;for(let r=0;r<ee;r++){let r=await this.findPidByListeningPort(n);if(r&&r>0&&(s=r),s&&s>0){let a=await this.getProcessByPid(s);if(a)return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,resolvedPid:s,executable:e}),a;if(r&&r===s)return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,resolvedPid:s,executable:e}),{pid:s,name:o,executablePath:e}}await new Promise(e=>setTimeout(e,te))}return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,resolvedPid:s,executable:e}),s&&s>0?{pid:s,name:o,executablePath:e}:null}catch(e){return t.error(`Failed to launch process with debug:`,e),null}}async injectDll(e,n){try{if(!Number.isFinite(e)||e<=0)return t.error(`Invalid PID for injectDll: ${e}`),!1;let r=this.scriptLoader.getScriptPath(`inject-dll.ps1`),i=Math.trunc(e),a=String(n).replace(/'/g,`''`);return await U(`${this.powershellPath} -NoProfile -ExecutionPolicy Bypass -File "${r}" -TargetPid ${i} -DllPath '${a}'`,{maxBuffer:1024*1024}),t.warn(`DLL injection is disabled for safety in this implementation`),!1}catch(e){return t.error(`DLL injection failed:`,e),!1}}async killProcess(e){try{if(!Number.isFinite(e)||e<=0)return t.error(`Invalid PID for killProcess: ${e}`),!1;let n=Math.trunc(e),r=`Stop-Process -Id ${n} -Force -ErrorAction SilentlyContinue; Write-Output "Process ${n} killed"`;return await U(`${this.powershellPath} -NoProfile -Command "${r}"`,{maxBuffer:1024*1024}),t.info(`Process ${n} killed successfully`),!0}catch(n){return t.error(`Failed to kill process ${e}:`,n),!1}}async discoverBrowsers(){try{let e=await this.browserDiscovery.discoverBrowsers();return t.info(`Discovered ${e.length} browser instances`),e}catch(e){return t.error(`Failed to discover browsers:`,e),[]}}async findBrowserByWindowClass(e){try{let n=await this.browserDiscovery.findByWindowClass(e);return t.info(`Found ${n.length} browsers matching window class '${e}'`),n}catch(n){return t.error(`Failed to find browser by window class '${e}':`,n),[]}}async findBrowserByProcessName(e){try{let n=await this.browserDiscovery.findByProcessName(e);return t.info(`Found ${n.length} browsers matching process name '${e}'`),n}catch(n){return t.error(`Failed to find browser by process name '${e}':`,n),[]}}async detectBrowserDebugPort(e,n){try{let r=n||f,i=await this.browserDiscovery.detectDebugPort(e,r);return i?t.info(`Detected debug port ${i} for process ${e}`):t.warn(`No debug port detected for process ${e}`),i}catch(n){return t.error(`Failed to detect debug port for PID ${e}:`,n),null}}};const G=P(M);function Pe(e){return String(e||``).replace(/[^\w\s.@/\-:,+]/g,``)}function K(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}var Fe=class{isWayland=!1;constructor(){this.detectDisplayServer(),t.info(`LinuxProcessManager initialized`,{displayServer:this.isWayland?`Wayland`:`X11`})}async detectDisplayServer(){try{let{stdout:e}=await G(`echo $XDG_SESSION_TYPE`);this.isWayland=e.trim()===`wayland`}catch{this.isWayland=!1}}async findProcesses(e){try{let{stdout:n}=await G(`ps aux | grep -i "${Pe(e)}" | grep -v grep || true`,{maxBuffer:S}),r=[],i=n.trim().split(`
2
+ `).filter(e=>e.trim());for(let e of i){let t=e.trim().split(/\s+/);if(t.length>=11){let e=parseInt(t[1]||`0`,10);if(isNaN(e))continue;let n=parseFloat(t[2]||`0`),i=parseFloat(t[3]||`0`),a=t.slice(10).join(` `);r.push({pid:e,name:t[10]||a.split(` `)[0]||`unknown`,commandLine:a,cpuUsage:n,memoryUsage:i*1024*1024})}}return t.info(`Found ${r.length} processes matching '${e}'`),r}catch(n){return t.error(`Failed to find processes with pattern '${e}':`,n),[]}}async getProcessByPid(e){try{e=K(e);let{stdout:t}=await G(`cat /proc/${e}/status 2>/dev/null || echo ""`),{stdout:n}=await G(`cat /proc/${e}/cmdline 2>/dev/null | tr '\0' ' ' || echo ""`),{stdout:r}=await G(`cat /proc/${e}/stat 2>/dev/null || echo ""`);if(!t.trim())return null;let i={};for(let e of t.split(`
3
+ `)){let[t,n]=e.split(`:`);t&&n&&(i[t.trim()]=n.trim())}let a=r.trim().split(` `),o=a.length>13?parseInt(a[13]||`0`,10):0,s=a.length>14?parseInt(a[14]||`0`,10):0;return{pid:e,name:i.Name||`unknown`,executablePath:await this.getProcessPath(e),commandLine:n.trim()||void 0,parentPid:i.PPid?parseInt(i.PPid,10):void 0,memoryUsage:i.VmRSS?parseInt(i.VmRSS.replace(/\D/g,``),10)*1024:void 0,cpuUsage:o+s}}catch(n){return t.error(`Failed to get process by PID ${e}:`,n),null}}async getProcessPath(e){try{e=K(e);let{stdout:t}=await G(`readlink -f /proc/${e}/exe 2>/dev/null || echo ""`);return t.trim()||void 0}catch{return}}async getProcessWindows(e){let n=[];try{if(e=K(e),this.isWayland){t.debug(`Attempting Wayland window enumeration via compositor-specific APIs`);try{let{stdout:t}=await G(`hyprctl clients -j 2>/dev/null`);if(t.trim()){let r=JSON.parse(t);for(let t of r)t.pid===e&&n.push({handle:t.address||t.window||`0`,title:t.title||``,className:t.class||``,processId:e,threadId:0});if(n.length>0)return n}}catch{}try{let{stdout:n}=await G(`gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Eval "global.get_window_actors().filter(w => w.meta_window.get_pid() === ${e}).map(w => w.meta_window.get_title() + '|' + w.meta_window.get_wm_class())" 2>/dev/null`);(n.includes(String(e))||n.includes(`,`))&&t.debug(`GNOME Wayland window query returned data, but reliable parsing is not yet implemented`)}catch{}}let{stdout:r}=await G(`which xdotool 2>/dev/null || echo ""`);if(!r.trim())return this.isWayland&&n.length===0?t.warn(`Wayland native enumeration failed and xdotool is missing. Install xdotool for XWayland fallback.`):this.isWayland||t.warn(`xdotool not found. Install it for window management: sudo apt-get install xdotool`),n;let{stdout:i}=await G(`xdotool search --all --pid ${e} 2>/dev/null || true`),a=i.trim().split(`
4
+ `).filter(e=>e.trim());for(let t of a)try{let{stdout:r}=await G(`xdotool getwindowname ${t} 2>/dev/null || echo ""`),{stdout:i}=await G(`xdotool getwindowclassname ${t} 2>/dev/null || echo ""`);n.push({handle:t,title:r.trim(),className:i.trim(),processId:e,threadId:0})}catch{}return n}catch(r){return t.error(`Failed to get windows for PID ${e}:`,r),n}}async findChromeProcesses(){let e={rendererProcesses:[],utilityProcesses:[]};try{let n=await this.findProcesses(`chrome`),r=await Promise.all(n.map(e=>this.getProcessByPid(e.pid)));for(let t=0;t<n.length;t++){let i=n[t],a=r[t];if(a?.commandLine){let t=a.commandLine.toLowerCase();t.includes(`--type=renderer`)?e.rendererProcesses.push({...i,...a}):t.includes(`--type=gpu-process`)?e.gpuProcess={...i,...a}:t.includes(`--type=utility`)?e.utilityProcesses.push({...i,...a}):t.includes(`--type=`)||(e.mainProcess={...i,...a})}else e.mainProcess||=i}let i=[e.mainProcess?.pid,...e.rendererProcesses.map(e=>e.pid)].filter(Boolean);for(let t of i){let n=(await this.getProcessWindows(t)).find(e=>e.title.includes(`Chrome`)||e.className.includes(`Chrome`)||e.title.includes(`Chromium`));if(n){e.targetWindow=n;break}}return t.info(`Chrome processes found:`,{main:e.mainProcess?.pid,renderers:e.rendererProcesses.length,hasTargetWindow:!!e.targetWindow}),e}catch(n){return t.error(`Failed to find Chrome processes:`,n),e}}async getProcessCommandLine(e){try{e=K(e);let{stdout:t}=await G(`cat /proc/${e}/cmdline 2>/dev/null | tr '\0' ' ' || echo ""`),{stdout:n}=await G(`cat /proc/${e}/status 2>/dev/null | grep PPid || echo ""`),r=n.match(/PPid:\s*(\d+)/);return{commandLine:t.trim()||void 0,parentPid:r?.[1]?parseInt(r[1],10):void 0}}catch(n){return t.error(`Failed to get command line for PID ${e}:`,n),{}}}async checkDebugPort(e,n){try{e=K(e);let t=n?.commandLine??(await this.getProcessCommandLine(e)).commandLine;if(t){let e=t.match(/--remote-debugging-port=(\d+)/);if(e?.[1])return parseInt(e[1],10)}let{stdout:r}=await G(`ss -tlnp 2>/dev/null | grep "pid=${e}" || netstat -tlnp 2>/dev/null | grep "${e}" || true`,{maxBuffer:1024*1024});for(let e of f)if(r.includes(`:${e}`))return e;return null}catch(n){return t.error(`Failed to check debug port for PID ${e}:`,n),null}}async launchWithDebug(e,n=x,r=[]){try{let i=N(e,[`--remote-debugging-port=${n}`,...r],{detached:!0,stdio:`ignore`});if(i.unref(),C.register(i),await new Promise(e=>setTimeout(e,y)),!i.pid)return t.error(`Failed to spawn process: PID is undefined for ${e}`),null;let a=await this.getProcessByPid(i.pid);return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,executable:e}),a}catch(e){return t.error(`Failed to launch process with debug:`,e),null}}async killProcess(e){try{return e=K(e),await G(`kill -9 ${e} 2>/dev/null || kill -15 ${e}`),t.info(`Process ${e} killed successfully`),!0}catch(n){return t.error(`Failed to kill process ${e}:`,n),!1}}isRunningOnWayland(){return this.isWayland}};const q=P(M),Ie=P(ye);function Le(e){return String(e||``).replace(/[^\w\s.@/\-:,+]/g,``)}function J(e){let t=Math.trunc(Number(e));if(!Number.isFinite(t)||t<=0)throw Error(`Invalid PID: ${e}`);return t}function Re(e,t){let n=e;for(let[e,r]of Object.entries(t)){let t=RegExp(`\\{\\{${e}\\}\\}`,`g`);n=n.replace(t,String(r))}return n}var ze=class{constructor(){t.info(`MacProcessManager initialized`)}async findProcesses(e){try{let{stdout:n}=await q(`ps aux | grep -i "${Le(e)}" | grep -v grep || true`,{maxBuffer:S}),r=[],i=n.trim().split(`
5
+ `).filter(e=>e.trim());for(let e of i){let t=e.trim().split(/\s+/);if(t.length>=11){let e=parseInt(t[1]||`0`,10);if(isNaN(e))continue;let n=parseFloat(t[2]||`0`),i=parseFloat(t[3]||`0`),a=t.slice(10).join(` `);r.push({pid:e,name:t[10]||a.split(` `)[0]||`unknown`,commandLine:a,cpuUsage:n,memoryUsage:i*1024*1024})}}return t.info(`Found ${r.length} processes matching '${e}'`),r}catch(n){return t.error(`Failed to find processes with pattern '${e}':`,n),[]}}async getProcessByPid(e){try{e=J(e);let{stdout:t}=await q(`ps -p ${e} -o pid,ppid,pcpu,pmem,comm,args 2>/dev/null || echo ""`),n=t.trim().split(`
6
+ `).filter(e=>e.trim());if(n.length<2)return null;let r=(n[1]||``).trim().split(/\s+/);return r.length>=6?{pid:parseInt(r[0]||`0`,10),parentPid:parseInt(r[1]||`0`,10),name:r[4]||`unknown`,executablePath:await this.getProcessPath(e),commandLine:r.slice(5).join(` `),cpuUsage:parseFloat(r[2]||`0`),memoryUsage:parseFloat(r[3]||`0`)*1024*1024}:null}catch(n){return t.error(`Failed to get process by PID ${e}:`,n),null}}async getProcessPath(e){try{e=J(e);let{stdout:t}=await q(`ps -p ${e} -o comm= 2>/dev/null || echo ""`);return t.trim()||void 0}catch{return}}async getProcessWindows(e){try{e=J(e);let t=await this.getProcessByPid(e);if(!t)return[];let{stdout:n}=await q(`osascript -e '${`
7
+ tell application "System Events"
8
+ set processList to {}
9
+ try
10
+ set targetProcess to first process whose unix id is ${e}
11
+ set procName to name of targetProcess
12
+ set windowList to {}
13
+
14
+ tell targetProcess
15
+ repeat with win in windows
16
+ set winInfo to {|
17
+ title:name of win,
18
+ className:procName,
19
+ processId:${e},
20
+ handle:"applescript-window"
21
+ |}
22
+ set end of windowList to winInfo
23
+ end repeat
24
+ end tell
25
+
26
+ return windowList
27
+ on error
28
+ return {}
29
+ end try
30
+ end tell
31
+ `.replace(/'/g,`'"'"'`)}' 2>/dev/null || echo "[]"`,{timeout:c}),r=[];if(n.trim()&&n.trim()!==`[]`){let i=n.match(/title:([^,}]+)/g);if(i)for(let n of i){let i=n.replace(`title:`,``).trim();r.push({handle:`mac-window-${e}`,title:i,className:t.name,processId:e,threadId:0})}}return r}catch(n){return t.error(`Failed to get windows for PID ${e}:`,n),[]}}async getProcessWindowsCG(e){try{e=J(e);let{stdout:t}=await Ie(`python3`,[`-c`,Re(await new V().loadScript(`process_list.py`),{PID:e})],{timeout:v*2,windowsHide:!0}),n=[];try{let e=JSON.parse(t.trim());for(let t of e)n.push({handle:t.handle,title:t.title,className:t.className,processId:t.processId,threadId:0,bounds:t.bounds?{x:t.bounds.X||0,y:t.bounds.Y||0,width:t.bounds.Width||0,height:t.bounds.Height||0}:void 0})}catch{}return n}catch(n){return t.error(`Failed to get windows via CoreGraphics for PID ${e}:`,n),[]}}async findChromeProcesses(){let e={rendererProcesses:[],utilityProcesses:[]};try{let n=await this.findProcesses(`chrome`),r=await Promise.all(n.map(e=>this.getProcessByPid(e.pid)));for(let t=0;t<n.length;t++){let i=n[t],a=r[t];if(a?.commandLine){let t=a.commandLine.toLowerCase();t.includes(`--type=renderer`)?e.rendererProcesses.push({...i,...a}):t.includes(`--type=gpu-process`)?e.gpuProcess={...i,...a}:t.includes(`--type=utility`)?e.utilityProcesses.push({...i,...a}):t.includes(`--type=`)||(e.mainProcess={...i,...a})}else e.mainProcess||=i}if(e.mainProcess){let t=await this.getProcessWindowsCG(e.mainProcess.pid);t.length>0&&(e.targetWindow=t[0])}return t.info(`Chrome processes found:`,{main:e.mainProcess?.pid,renderers:e.rendererProcesses.length,hasTargetWindow:!!e.targetWindow}),e}catch(n){return t.error(`Failed to find Chrome processes:`,n),e}}async getProcessCommandLine(e){try{e=J(e);let{stdout:t}=await q(`ps -p ${e} -o ppid=,args= 2>/dev/null || echo ""`),n=t.trim().split(/\s+/);return n.length>=2?{parentPid:parseInt(n[0]||`0`,10),commandLine:n.slice(1).join(` `)||void 0}:{}}catch(n){return t.error(`Failed to get command line for PID ${e}:`,n),{}}}async checkDebugPort(e,n){try{e=J(e);let t=n?.commandLine??(await this.getProcessCommandLine(e)).commandLine;if(t){let e=t.match(/--remote-debugging-port=(\d+)/);if(e?.[1])return parseInt(e[1],10)}let{stdout:r}=await q(`lsof -Pan -p ${e} -i 2>/dev/null | grep LISTEN || true`,{maxBuffer:1024*1024});for(let e of f)if(r.includes(`:${e}`))return e;return null}catch(n){return t.error(`Failed to check debug port for PID ${e}:`,n),null}}async launchWithDebug(e,n=x,r=[]){try{let i=N(e,[`--remote-debugging-port=${n}`,...r],{detached:!0,stdio:`ignore`});if(i.unref(),C.register(i),await new Promise(e=>setTimeout(e,y)),!i.pid)return t.error(`Failed to spawn process: PID is undefined for ${e}`),null;let a=await this.getProcessByPid(i.pid);return t.info(`Launched process with debug port ${n}:`,{pid:i.pid,executable:e}),a}catch(e){return t.error(`Failed to launch process with debug:`,e),null}}async killProcess(e){try{return e=J(e),await q(`kill -9 ${e} 2>/dev/null || kill -15 ${e}`),t.info(`Process ${e} killed successfully`),!0}catch(n){return t.error(`Failed to kill process ${e}:`,n),!1}}};const Be=/^(?:0x)?[0-9a-fA-F]{1,16}$/;async function Ve(e,n,r){try{let{stdout:t}=await R(`
32
+ Add-Type @"
33
+ using System;
34
+ using System.Runtime.InteropServices;
35
+ using System.ComponentModel;
36
+
37
+ public class MemoryReader {
38
+ [DllImport("kernel32.dll", SetLastError = true)]
39
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
40
+
41
+ [DllImport("kernel32.dll", SetLastError = true)]
42
+ public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int read);
43
+
44
+ [DllImport("kernel32.dll", SetLastError = true)]
45
+ public static extern bool CloseHandle(IntPtr handle);
46
+
47
+ const int PROCESS_VM_READ = 0x0010;
48
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
49
+
50
+ public static string ReadMemory(int pid, long address, int size) {
51
+ IntPtr hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid);
52
+ if (hProcess == IntPtr.Zero) {
53
+ int error = Marshal.GetLastWin32Error();
54
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
55
+ }
56
+
57
+ try {
58
+ byte[] buffer = new byte[size];
59
+ int bytesRead;
60
+ bool success = ReadProcessMemory(hProcess, (IntPtr)address, buffer, size, out bytesRead);
61
+
62
+ if (!success) {
63
+ int error = Marshal.GetLastWin32Error();
64
+ throw new Win32Exception(error, "Failed to read memory");
65
+ }
66
+
67
+ return BitConverter.ToString(buffer, 0, bytesRead).Replace("-", " ");
68
+ } finally {
69
+ CloseHandle(hProcess);
70
+ }
71
+ }
72
+ }
73
+ "@
74
+
75
+ try {
76
+ $result = [MemoryReader]::ReadMemory(${e}, ${n}, ${r})
77
+ @{ success = $true; data = $result } | ConvertTo-Json -Compress
78
+ } catch {
79
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
80
+ }
81
+ `,{maxBuffer:1024*1024*10}),i=t.trim();if(!i)throw Error(`PowerShell returned empty output`);let a=JSON.parse(i);return{success:a.success,data:a.data,error:a.error}}catch(e){return t.error(`Windows memory read failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed. Run as Administrator.`}}}let Y=null,He=!1;async function Ue(){if(He)return Y;try{let{createPlatformProvider:e}=await import(`./factory-BxNdBiZa.mjs`).then(e=>e.n),t=e();(await t.checkAvailability()).available&&(Y=t)}catch{}return He=!0,Y}function We(e,t){return e.subarray(0,t).toString(`hex`).toUpperCase().replace(/../g,`$& `)}async function Ge(e,n,r){try{let i=await Ue();if(i){let a=i.openProcess(e,!1);try{let e=i.readMemory(a,BigInt(n),r);return t.debug(`Native Linux memory read succeeded`),{success:!0,data:We(e.data,e.bytesRead).trim()}}finally{i.closeProcess(a)}}}catch(e){t.debug(`Native Linux read failed, falling back to dd:`,e)}try{let{stdout:t}=await I(`dd if=/proc/${e}/mem bs=1 skip=${n} count=${r} 2>/dev/null | xxd -p | tr -d '\\n' || echo ""`,{maxBuffer:1024*1024*10,timeout:h});return t.trim()?{success:!0,data:(t.trim().match(/.{1,2}/g)?.join(` `)||t.trim()).toUpperCase()}:{success:!1,error:`Failed to read memory. Requires ptrace access or root. Check kernel.yama.ptrace_scope if access denied.`}}catch(e){return t.error(`Linux memory read failed:`,e),{success:!1,error:`Memory read failed. Requires ptrace access or root (check kernel.yama.ptrace_scope).`}}}async function Ke(e,n,r,i){if(n===0)return{success:!1,error:`Invalid address: null pointer (0x0)`};if(r<=0||r>p)return{success:!1,error:`Invalid size: must be 1–${p} bytes`};let a=`0x${n.toString(16)}`;try{let{createPlatformProvider:i}=await import(`./factory-BxNdBiZa.mjs`).then(e=>e.n),a=i();if((await a.checkAvailability()).available){let i=a.openProcess(e,!1);try{let e=a.readMemory(i,BigInt(n),r),o=Array.from(e.data.subarray(0,e.bytesRead)).map(e=>e.toString(16).padStart(2,`0`).toUpperCase()).join(` `);return t.debug(`Native Mach memory read succeeded (zero-pause)`),{success:!0,data:o}}finally{a.closeProcess(i)}}}catch(e){t.debug(`Native Mach read failed, falling back to lldb:`,e)}let o=await i(e,a);if(!o.success)return{success:!1,error:`Cannot verify memory region: ${o.error}`};if(!o.isReadable)return{success:!1,error:`Address ${a} is not readable (protection: ${o.protection??`unknown`})`};let c=`/tmp/mread_${e}_${Date.now()}.bin`;try{let{stdout:t}=await I(`lldb --batch -p ${e} -o "memory read --outfile ${c} --binary ${a} -c ${r}" -o "process detach"`,{timeout:s,maxBuffer:1024*1024*10});if(!t.includes(`bytes written`))return{success:!1,error:`lldb memory read failed: ${(t.split(`
82
+ `).find(e=>e.includes(`error:`))??t).trim()}`};let n=await A.readFile(c);return{success:!0,data:Array.from(n).map(e=>e.toString(16).padStart(2,`0`).toUpperCase()).join(` `)}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{await A.unlink(c).catch(()=>{})}}async function qe(e,n,r,i,a){try{if(!Be.test(r))return{success:!1,error:`Invalid address format. Use hex like "0x12345678"`};let o=parseInt(r,16);if(isNaN(o))return{success:!1,error:`Invalid address format. Use hex like "0x12345678"`};if(i<=0||i>p)return{success:!1,error:`Read size must be 1–${p} bytes (${(p/1024/1024).toFixed(0)} MB)`};if(e===`win32`&&w())try{let e=await z.readMemory(n,r,i);if(e.success)return t.debug(`Native memory read succeeded`),e;t.warn(`Native memory read failed, falling back to PowerShell:`,e.error)}catch(e){t.warn(`Native memory read error, falling back to PowerShell:`,e)}switch(e){case`win32`:return Ve(n,o,i);case`linux`:return Ge(n,o,i);case`darwin`:return Ke(n,o,i,a);default:return{success:!1,error:`Memory operations not supported on platform: ${e}`}}}catch(e){return t.error(`Memory read failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Je(e,n,r){try{let{stdout:t}=await R(`
83
+ Add-Type @"
84
+ using System;
85
+ using System.Runtime.InteropServices;
86
+ using System.ComponentModel;
87
+
88
+ public class MemoryWriter {
89
+ [DllImport("kernel32.dll", SetLastError = true)]
90
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
91
+
92
+ [DllImport("kernel32.dll", SetLastError = true)]
93
+ public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int written);
94
+
95
+ [DllImport("kernel32.dll", SetLastError = true)]
96
+ public static extern bool CloseHandle(IntPtr handle);
97
+
98
+ const int PROCESS_VM_WRITE = 0x0020;
99
+ const int PROCESS_VM_OPERATION = 0x0008;
100
+
101
+ public static int WriteMemory(int pid, long address, string hexData) {
102
+ IntPtr hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, false, pid);
103
+ if (hProcess == IntPtr.Zero) {
104
+ int error = Marshal.GetLastWin32Error();
105
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
106
+ }
107
+
108
+ try {
109
+ byte[] buffer = new byte[hexData.Length / 2];
110
+ for (int i = 0; i < hexData.Length; i += 2) {
111
+ buffer[i / 2] = Convert.ToByte(hexData.Substring(i, 2), 16);
112
+ }
113
+
114
+ int bytesWritten;
115
+ bool success = WriteProcessMemory(hProcess, (IntPtr)address, buffer, buffer.Length, out bytesWritten);
116
+
117
+ if (!success) {
118
+ int error = Marshal.GetLastWin32Error();
119
+ throw new Win32Exception(error, "Failed to write memory");
120
+ }
121
+
122
+ return bytesWritten;
123
+ } finally {
124
+ CloseHandle(hProcess);
125
+ }
126
+ }
127
+ }
128
+ "@
129
+
130
+ try {
131
+ $bytesWritten = [MemoryWriter]::WriteMemory(${e}, ${n}, "${r.toString(`hex`).toUpperCase()}")
132
+ @{ success = $true; bytesWritten = $bytesWritten } | ConvertTo-Json -Compress
133
+ } catch {
134
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
135
+ }
136
+ `,{maxBuffer:1024*1024}),i=t.trim();if(!i)throw Error(`PowerShell returned empty output`);let a=JSON.parse(i);return{success:a.success,bytesWritten:a.bytesWritten,error:a.error}}catch(e){return t.error(`Windows memory write failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed. Run as Administrator.`}}}let X=null,Ye=!1;async function Xe(){if(Ye)return X;try{let{createPlatformProvider:e}=await import(`./factory-BxNdBiZa.mjs`).then(e=>e.n),t=e();(await t.checkAvailability()).available&&(X=t)}catch{}return Ye=!0,X}async function Ze(e,n,r){try{let i=await Xe();if(i){let a=i.openProcess(e,!0);try{let e=i.writeMemory(a,BigInt(n),r);return t.debug(`Native Linux memory write succeeded`),{success:!0,bytesWritten:e.bytesWritten}}finally{i.closeProcess(a)}}}catch(e){t.debug(`Native Linux write failed, falling back to dd:`,e)}try{let{stderr:t}=await I(`printf "${r.toString(`hex`)}" | xxd -r -p | dd of=/proc/${e}/mem bs=1 seek=${n} conv=notrunc`,{maxBuffer:1024*1024,timeout:ne});return t&&/error|denied|cannot/i.test(t)?{success:!1,error:`Memory write failed. Requires ptrace access or root. Check kernel.yama.ptrace_scope if access denied.`}:{success:!0,bytesWritten:r.length}}catch(e){return t.error(`Linux memory write failed:`,e),{success:!1,error:`Memory write failed. Requires ptrace access or root (check kernel.yama.ptrace_scope).`}}}async function Qe(e,n,i,a){if(n===0)return{success:!1,error:`Invalid address: null pointer (0x0)`};if(i.length===0||i.length>r)return{success:!1,error:`Invalid write size: must be 1–${r} bytes`};let o=`0x${n.toString(16)}`;try{let{createPlatformProvider:r}=await import(`./factory-BxNdBiZa.mjs`).then(e=>e.n),a=r();if((await a.checkAvailability()).available){let r=a.openProcess(e,!0);try{let e=a.writeMemory(r,BigInt(n),i);return t.debug(`Native Mach memory write succeeded (zero-pause)`),{success:!0,bytesWritten:e.bytesWritten}}finally{a.closeProcess(r)}}}catch(e){t.debug(`Native Mach write failed, falling back to lldb:`,e)}let s=await a(e,o);if(!s.success)return{success:!1,error:`Cannot verify memory region: ${s.error}`};if(!s.isWritable)return{success:!1,error:`Address ${o} is not writable (protection: ${s.protection??`unknown`})`};try{let{stdout:t}=await I(`lldb --batch -p ${e} -o "memory write ${o} ${Array.from(i).map(e=>`0x${e.toString(16).padStart(2,`0`)}`).join(` `)}" -o "process detach"`,{timeout:ne,maxBuffer:1024*1024});return t.includes(`error:`)?{success:!1,error:`lldb memory write failed: ${(t.split(`
137
+ `).find(e=>e.includes(`error:`))??t).trim()}`}:{success:!0,bytesWritten:i.length}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}const $e=/^(?:0x)?[0-9a-fA-F]{1,16}$/;async function et(e,n,i,a,o=`hex`,s){try{if(!$e.test(i))return{success:!1,error:`Invalid address format. Use hex like "0x12345678"`};let c=parseInt(i,16);if(isNaN(c))return{success:!1,error:`Invalid address format`};let l;try{if(o===`base64`)l=Buffer.from(a,`base64`);else{let e=a.replace(/\s/g,``);l=Buffer.from(e,`hex`)}}catch{return{success:!1,error:`Invalid ${o} data`}}if(l.length===0||l.length>r)return{success:!1,error:`Write size must be 1–${r} bytes (${(r/1024).toFixed(0)} KB)`};if(e===`win32`&&w())try{let e=await z.writeMemory(n,i,a,o);if(e.success)return t.debug(`Native memory write succeeded`),e;t.warn(`Native memory write failed, falling back to PowerShell:`,e.error)}catch(e){t.warn(`Native memory write error, falling back to PowerShell:`,e)}switch(e){case`win32`:return Je(n,c,l);case`linux`:return Ze(n,c,l);case`darwin`:return Qe(n,c,l,s);default:return{success:!1,error:`Memory operations not supported on platform: ${e}`}}}catch(e){return t.error(`Memory write failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}}const tt=1e3;async function nt(e,t,n){if(t.length>tt)return{success:!1,results:[],error:`Too many patches (${t.length}), max ${tt}`};let r=[];for(let i of t){let t=await n(e,i.address,i.data,i.encoding||`hex`);r.push({address:i.address,success:t.success,error:t.error})}let i=r.every(e=>e.success);return{success:i,results:r,error:i?void 0:`Failed to write ${r.filter(e=>!e.success).length} of ${r.length} patches`}}function rt(e,t){let n=[],r=[];switch(t){case`hex`:{let t=e.trim().split(/\s+/);for(let e of t)if(e===`??`||e===`**`||e===`?`)n.push(0),r.push(0);else{let t=parseInt(e,16);isNaN(t)||(n.push(t),r.push(1))}break}case`int32`:{let t=parseInt(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(4);e.writeInt32LE(t,0),n=Array.from(e),r=[1,1,1,1]}break}case`int64`:{let t=BigInt.asIntN(64,BigInt(e)),i=Buffer.allocUnsafe(8);i.writeBigInt64LE(t,0),n=Array.from(i),r=[1,1,1,1,1,1,1,1];break}case`float`:{let t=parseFloat(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(4);e.writeFloatLE(t,0),n=Array.from(e),r=[1,1,1,1]}break}case`double`:{let t=parseFloat(e);if(!isNaN(t)){let e=Buffer.allocUnsafe(8);e.writeDoubleLE(t,0),n=Array.from(e),r=[1,1,1,1,1,1,1,1]}break}case`string`:{let t=Buffer.from(e,`utf8`);n=Array.from(t),r=n.map(()=>1);break}}if(n.length===0)throw Error(`Invalid pattern`);return{patternBytes:n,mask:r}}function it(e,t){let n=[],r=[];switch(t){case`hex`:{let t=e.trim().split(/\s+/);for(let e of t)if(e===`??`||e===`?`||e===`**`)n.push(0),r.push(0);else{let t=parseInt(e,16);if(isNaN(t))throw Error(`Invalid hex byte: ${e}`);n.push(t),r.push(1)}if(!n.length)throw Error(`Pattern is empty`);break}case`int32`:{let t=parseInt(e);if(isNaN(t))throw Error(`Invalid int32 value`);let i=Buffer.allocUnsafe(4);i.writeInt32LE(t,0);let a=Array.from(i);n.push(...a),r.push(...a.map(()=>1));break}case`int64`:{let t=Buffer.allocUnsafe(8);t.writeBigInt64LE(BigInt.asIntN(64,BigInt(e)),0);let i=Array.from(t);n.push(...i),r.push(...i.map(()=>1));break}case`float`:{let t=parseFloat(e);if(isNaN(t))throw Error(`Invalid float value`);let i=Buffer.allocUnsafe(4);i.writeFloatLE(t,0);let a=Array.from(i);n.push(...a),r.push(...a.map(()=>1));break}case`double`:{let t=parseFloat(e);if(isNaN(t))throw Error(`Invalid double value`);let i=Buffer.allocUnsafe(8);i.writeDoubleLE(t,0);let a=Array.from(i);n.push(...a),r.push(...a.map(()=>1));break}case`string`:{let t=Array.from(Buffer.from(e,`utf8`));n.push(...t),r.push(...t.map(()=>1));break}default:throw Error(`Unsupported pattern type: ${t}`)}return{bytes:n,mask:r}}function at(e,t,n){let{patternBytes:r,mask:i}=rt(t,n);return`
138
+ Add-Type @"
139
+ using System;
140
+ using System.Runtime.InteropServices;
141
+ using System.Collections.Generic;
142
+ using System.ComponentModel;
143
+
144
+ public class MemoryScanner {
145
+ [DllImport("kernel32.dll", SetLastError = true)]
146
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
147
+
148
+ [DllImport("kernel32.dll", SetLastError = true)]
149
+ public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int read);
150
+
151
+ [DllImport("kernel32.dll", SetLastError = true)]
152
+ public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr addr, out MEMORY_BASIC_INFORMATION info, int size);
153
+
154
+ [DllImport("kernel32.dll", SetLastError = true)]
155
+ public static extern bool CloseHandle(IntPtr handle);
156
+
157
+ const int PROCESS_VM_READ = 0x0010;
158
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
159
+
160
+ [StructLayout(LayoutKind.Sequential)]
161
+ public struct MEMORY_BASIC_INFORMATION {
162
+ public IntPtr BaseAddress;
163
+ public IntPtr AllocationBase;
164
+ public uint AllocationProtect;
165
+ public IntPtr RegionSize;
166
+ public uint State;
167
+ public uint Protect;
168
+ public uint Type;
169
+ }
170
+
171
+ const uint MEM_COMMIT = 0x1000;
172
+ const uint PAGE_READONLY = 0x02;
173
+ const uint PAGE_READWRITE = 0x04;
174
+ const uint PAGE_WRITECOPY = 0x08;
175
+ const uint PAGE_EXECUTE_READ = 0x20;
176
+ const uint PAGE_EXECUTE_READWRITE = 0x40;
177
+
178
+ public static List<string> ScanMemory(int pid, byte[] pattern, byte[] mask, int maxResults = 10000) {
179
+ var results = new List<string>();
180
+ IntPtr hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid);
181
+ if (hProcess == IntPtr.Zero) {
182
+ int error = Marshal.GetLastWin32Error();
183
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
184
+ }
185
+
186
+ try {
187
+ IntPtr addr = IntPtr.Zero;
188
+ MEMORY_BASIC_INFORMATION info;
189
+ int infoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
190
+ int scannedRegions = 0;
191
+
192
+ while (VirtualQueryEx(hProcess, addr, out info, infoSize) == infoSize) {
193
+ scannedRegions++;
194
+ bool isReadable = (info.State == MEM_COMMIT) &&
195
+ ((info.Protect & PAGE_READONLY) != 0 ||
196
+ (info.Protect & PAGE_READWRITE) != 0 ||
197
+ (info.Protect & PAGE_WRITECOPY) != 0 ||
198
+ (info.Protect & PAGE_EXECUTE_READ) != 0 ||
199
+ (info.Protect & PAGE_EXECUTE_READWRITE) != 0);
200
+
201
+ if (isReadable && info.RegionSize.ToInt64() > 0 && info.RegionSize.ToInt64() < 1073741824) {
202
+ long regionSize = info.RegionSize.ToInt64();
203
+ if (regionSize > 16777216) regionSize = 16777216; // bound scan window per region (16MB)
204
+ byte[] buffer = new byte[(int)regionSize];
205
+ int bytesRead;
206
+
207
+ if (ReadProcessMemory(hProcess, info.BaseAddress, buffer, buffer.Length, out bytesRead)) {
208
+ for (int i = 0; i <= bytesRead - pattern.Length; i++) {
209
+ if (PatternMatch(buffer, i, pattern, mask)) {
210
+ long foundAddr = info.BaseAddress.ToInt64() + i;
211
+ results.Add("0x" + foundAddr.ToString("X"));
212
+ if (results.Count >= maxResults) break;
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ if (results.Count >= maxResults) break;
219
+ if (scannedRegions >= 50000) break;
220
+ long baseAddr = info.BaseAddress.ToInt64();
221
+ long regionSizeRaw = info.RegionSize.ToInt64();
222
+ if (regionSizeRaw <= 0) break;
223
+ long nextAddr = baseAddr + regionSizeRaw;
224
+ if (nextAddr <= baseAddr) break;
225
+ addr = new IntPtr(nextAddr);
226
+ if (addr.ToInt64() >= 0x7FFFFFFF0000) break;
227
+ }
228
+
229
+ return results;
230
+ } finally {
231
+ CloseHandle(hProcess);
232
+ }
233
+ }
234
+
235
+ private static bool PatternMatch(byte[] buffer, int offset, byte[] pattern, byte[] mask) {
236
+ for (int i = 0; i < pattern.Length; i++) {
237
+ if (mask[i] == 1 && buffer[offset + i] != pattern[i]) {
238
+ return false;
239
+ }
240
+ }
241
+ return true;
242
+ }
243
+ }
244
+ "@
245
+
246
+ try {
247
+ $patternBytes = @(${r.join(`,`)})
248
+ $maskBytes = @(${i.join(`,`)})
249
+ $results = [MemoryScanner]::ScanMemory(${e}, $patternBytes, $maskBytes, 1000)
250
+ @{
251
+ success = $true;
252
+ addresses = $results;
253
+ stats = @{
254
+ patternLength = $patternBytes.Length;
255
+ resultsFound = $results.Count
256
+ }
257
+ } | ConvertTo-Json -Compress
258
+ } catch {
259
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
260
+ }
261
+ `.trim()}async function ot(e,n,r){try{if(E())try{let i=await z.scanMemory(e,n,r);if(i.success)return i;t.warn(`Native Windows memory scan failed, falling back to PowerShell`,{pid:e,patternType:r,error:i.error,nativeAvailable:E()})}catch(n){t.warn(`Native Windows memory scan threw, falling back to PowerShell`,{pid:e,patternType:r,error:n instanceof Error?n.message:String(n),nativeAvailable:E()})}let{stdout:i,stderr:o}=await R(at(e,n,r),{maxBuffer:a,timeout:g});if(o&&o.includes(`Error`))return{success:!1,addresses:[],error:o};let s=i.trim();if(!s)throw Error(`PowerShell returned empty output`);let c=JSON.parse(s);return{success:c.success,addresses:c.addresses||[],error:c.error,stats:c.stats}}catch(e){return t.error(`Windows memory scan failed:`,e),{success:!1,addresses:[],error:e instanceof Error?e.message:`PowerShell execution failed. Run as Administrator.`}}}function st(e,t,n){let r=n;switch(r?.code){case`ENOENT`:case`ESRCH`:return`Process ${e} no longer exists or /proc/${e}/${t} is unavailable.`;case`EACCES`:case`EPERM`:return`Cannot access /proc/${e}/${t}. Requires root privileges or ptrace access.`;default:return r instanceof Error?r.message:String(n)}}async function ct(e,n,r){let i,a;try{let e=rt(n,r);i=e.patternBytes,a=e.mask}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:`Invalid pattern`}}try{let n;try{n=me(`/proc/${e}/maps`,`utf-8`)}catch(t){return{success:!1,addresses:[],error:st(e,`maps`,t)}}let r=T(n),o=Array.isArray(r)?r.filter(e=>e.permissions.read):[],s;try{s=pe(`/proc/${e}/mem`,`r`)}catch(t){return{success:!1,addresses:[],error:st(e,`mem`,t)}}let c=new Set,l=16*1024*1024,u=1e4,d=Math.max(i.length-1,0);try{for(let n of o){if(c.size>=u)break;if(n.end<=n.start)continue;let r=0n,o=Buffer.alloc(0),f=n.end-n.start;for(;r<f&&c.size<u;){let p=f-r,m=Number(p>BigInt(l)?BigInt(l):p),h=Buffer.allocUnsafe(m),g;try{g=he(s,h,0,m,n.start+r)}catch(i){let a=i;if(a?.code===`EIO`||a?.code===`EFAULT`||a?.code===`EACCES`||a?.code===`EPERM`){t.debug(`Skipping unreadable Linux memory region chunk`,{pid:e,start:`0x${n.start.toString(16)}`,offset:r.toString(),code:a.code});break}throw i}if(g<=0)break;let _=g===m?h:h.subarray(0,g),v=o.length>0?Buffer.concat([o,_]):_,ee=n.start+r-BigInt(o.length),y=BigInt(g),b=r+y>=f||g<m,x=b?0:Math.min(d,v.length),te=v.length-x,S=D(v,i,a);for(let e of S){if(!b&&e>=te)continue;let t=ee+BigInt(e);if(!(t<n.start||t>=n.end)&&(c.add(`0x${t.toString(16)}`),c.size>=u))break}if(o=x>0?v.subarray(v.length-x):Buffer.alloc(0),r+=y,g<m){t.debug(`Linux memory scan stopped after short read`,{pid:e,start:`0x${n.start.toString(16)}`,requested:m,bytesRead:g});break}}}}finally{fe(s)}let f=Array.from(c);return{success:!0,addresses:f,stats:{patternLength:i.length,resultsFound:f.length}}}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:String(e)}}}async function lt(e,n,r){let i,a;try{let e=it(n,r);i=e.bytes,a=e.mask}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:`Invalid pattern`}}try{let t=await ut(e,i,a);if(t)return t}catch(e){t.debug(`Native Mach scan failed, falling back to lldb:`,e)}return dt(e,i,a)}async function ut(e,n,r){let{createPlatformProvider:i}=await import(`./factory-BxNdBiZa.mjs`).then(e=>e.n),a=i();if(!(await a.checkAvailability()).available)return null;let o=a.openProcess(e,!1),s=[],c=1e3;try{let e=0n;for(let t=0;t<5e4&&s.length<c;t++){let t=a.queryRegion(o,e);if(!t)break;if(t.isReadable&&t.size>0&&t.size<=33554432)try{let e=D(a.readMemory(o,t.baseAddress,t.size).data,n,r);for(let n of e)if(s.push(`0x${(t.baseAddress+BigInt(n)).toString(16)}`),s.length>=c)break}catch{}if(e=t.baseAddress+BigInt(t.size),e<=t.baseAddress)break}}finally{a.closeProcess(o)}return t.debug(`Native Mach scan completed (zero-pause): ${s.length} results`),{success:!0,addresses:s,stats:{patternLength:n.length,resultsFound:s.length}}}async function dt(e,t,n){let r=t.map(e=>`0x${e.toString(16)}`).join(`,`),i=n.join(`,`),a=`${e}_${Date.now()}`,o=`/tmp/lldb_scan_${a}.py`,s=`/tmp/lldb_scan_${a}.txt`,c=`
262
+ import lldb, json, sys
263
+
264
+ def __lldb_init_module(debugger, internal_dict):
265
+ proc = debugger.GetSelectedTarget().GetProcess()
266
+ pat = bytes([${r}])
267
+ mask = [${i}]
268
+ results = []
269
+ rl = proc.GetMemoryRegions()
270
+ for i in range(rl.GetSize()):
271
+ info = lldb.SBMemoryRegionInfo()
272
+ rl.GetMemoryRegionAtIndex(i, info)
273
+ if not info.IsReadable():
274
+ continue
275
+ s = info.GetRegionBase()
276
+ sz = info.GetRegionEnd() - s
277
+ if sz > 32 * 1024 * 1024:
278
+ continue
279
+ err = lldb.SBError()
280
+ data = proc.ReadMemory(s, sz, err)
281
+ if not err.Success():
282
+ continue
283
+ n = len(pat)
284
+ for j in range(len(data) - n + 1):
285
+ match = True
286
+ for k in range(n):
287
+ if mask[k] == 1 and data[j+k] != pat[k]:
288
+ match = False
289
+ break
290
+ if match:
291
+ results.append(hex(s + j))
292
+ if len(results) >= 1000:
293
+ break
294
+ if len(results) >= 1000:
295
+ break
296
+ sys.stdout.write('SCAN_RESULT:' + json.dumps({
297
+ 'success': True,
298
+ 'addresses': results,
299
+ 'stats': {'patternLength': len(pat), 'resultsFound': len(results)}
300
+ }) + '\\n')
301
+ sys.stdout.flush()
302
+ `;await A.writeFile(o,c,`utf8`),await A.writeFile(s,`command script import ${o}\nprocess detach\n`,`utf8`);try{let{stdout:t}=await I(`lldb --batch -p ${e} --source ${s}`,{timeout:g,maxBuffer:1024*1024*5}),n=t.split(`
303
+ `).find(e=>e.startsWith(`SCAN_RESULT:`));if(!n)return{success:!1,addresses:[],error:`lldb scan returned no result. ${t.split(`
304
+ `).find(e=>e.includes(`error:`))??``}`.trim()};try{return JSON.parse(n.slice(12))}catch{let e=t.split(`
305
+ `).find(e=>e.includes(`error:`))??``;if(e)return{success:!1,addresses:[],error:e.trim()};throw Error(`Unexpected end of JSON input`)}}catch(e){return{success:!1,addresses:[],error:e instanceof Error?e.message:String(e)}}finally{await A.unlink(o).catch(()=>{}),await A.unlink(s).catch(()=>{})}}async function ft(e,n,r,i=`hex`,a=!1){let o=!1;try{switch(a&&(o=await ht(e,n),o?t.info(`Suspended process ${n} for consistent memory scan`):t.warn(`Could not suspend process ${n} — scanning unsuspended`)),e){case`win32`:return await ot(n,r,i);case`linux`:return await ct(n,r,i);case`darwin`:return await lt(n,r,i);default:return{success:!1,addresses:[],error:`Memory scan not supported on ${e}`}}}catch(e){return t.error(`Memory scan failed:`,e),{success:!1,addresses:[],error:e instanceof Error?e.message:String(e)}}finally{o&&(await gt(e,n),t.info(`Resumed process ${n} after memory scan`))}}async function pt(e,t,n,r=`hex`,i,a){let o=[];for(let e of n){let t=parseInt(e,16);isNaN(t)||o.push(t)}if(o.length===0)return{success:!1,addresses:[],error:`No valid addresses provided`};let s=await a(e,t,r);if(!s.success||s.addresses.length===0)return{success:!0,addresses:[],stats:{resultsFound:0,patternLength:t.length}};let c=[];for(let e of s.addresses){let t=parseInt(e,16);o.some(e=>Math.abs(e-t)<256)&&(c.includes(e)||c.push(e))}return{success:!0,addresses:c,stats:{resultsFound:c.length,patternLength:t.length}}}async function mt(e,t){let{machTaskSelf:n,taskForPid:r,machPortDeallocate:i,KERN:a}=await import(`./DarwinAPI-BuMPGzHm.mjs`).then(e=>e.t),o=n(),{kr:s,task:c}=r(o,e);if(s!==a.SUCCESS)return!1;try{return t(c)}finally{i(o,c)}}async function ht(e,n){try{switch(e){case`darwin`:{let{taskSuspend:e,KERN:t}=await import(`./DarwinAPI-BuMPGzHm.mjs`).then(e=>e.t);return mt(n,n=>e(n)===t.SUCCESS)}case`linux`:{let{execAsync:e}=await Promise.resolve().then(()=>F);return await e(`kill -STOP ${n}`,{timeout:m}),!0}case`win32`:{let{execAsync:e}=await Promise.resolve().then(()=>F);return await e(`powershell -NoProfile -Command "(Add-Type -MemberDefinition '[DllImport("ntdll.dll")] public static extern int NtSuspendProcess(IntPtr h);' -Name W -Namespace N -PassThru)::NtSuspendProcess((Get-Process -Id ${n}).Handle)"`,{timeout:l}),!0}default:return!1}}catch(e){return t.warn(`Failed to suspend process ${n}:`,e),!1}}async function gt(e,n){try{switch(e){case`darwin`:{let{taskResume:e}=await import(`./DarwinAPI-BuMPGzHm.mjs`).then(e=>e.t);await mt(n,t=>{e(t)});break}case`linux`:{let{execAsync:e}=await Promise.resolve().then(()=>F);await e(`kill -CONT ${n}`,{timeout:m});break}case`win32`:{let{execAsync:e}=await Promise.resolve().then(()=>F);await e(`powershell -NoProfile -Command "(Add-Type -MemberDefinition '[DllImport("ntdll.dll")] public static extern int NtResumeProcess(IntPtr h);' -Name W -Namespace N -PassThru)::NtResumeProcess((Get-Process -Id ${n}).Handle)"`,{timeout:l});break}}}catch(e){t.error(`CRITICAL: Failed to resume process ${n} — may need manual SIGCONT:`,e)}}function _t(e,t,n,r){return`
306
+ Add-Type @"
307
+ using System;
308
+ using System.Runtime.InteropServices;
309
+ using System.IO;
310
+ using System.ComponentModel;
311
+
312
+ public class MemoryDumper {
313
+ [DllImport("kernel32.dll", SetLastError = true)]
314
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
315
+
316
+ [DllImport("kernel32.dll", SetLastError = true)]
317
+ public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int read);
318
+
319
+ [DllImport("kernel32.dll", SetLastError = true)]
320
+ public static extern bool CloseHandle(IntPtr handle);
321
+
322
+ const int PROCESS_VM_READ = 0x0010;
323
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
324
+
325
+ public static string DumpMemory(int pid, long address, int size, string outputPath) {
326
+ IntPtr hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, pid);
327
+ if (hProcess == IntPtr.Zero) {
328
+ int error = Marshal.GetLastWin32Error();
329
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
330
+ }
331
+
332
+ try {
333
+ byte[] buffer = new byte[size];
334
+ int bytesRead;
335
+
336
+ if (!ReadProcessMemory(hProcess, (IntPtr)address, buffer, size, out bytesRead)) {
337
+ int error = Marshal.GetLastWin32Error();
338
+ throw new Win32Exception(error, "Failed to read memory");
339
+ }
340
+
341
+ File.WriteAllBytes(outputPath, buffer);
342
+ return "Dumped " + bytesRead + " bytes to " + outputPath;
343
+ } finally {
344
+ CloseHandle(hProcess);
345
+ }
346
+ }
347
+ }
348
+ "@
349
+
350
+ try {
351
+ $result = [MemoryDumper]::DumpMemory(${e}, ${t}, ${n}, "${r.replace(/\\/g,`\\\\`).replace(/"/g,'`"').replace(/\$/g,"`$")}")
352
+ @{ success = $true; message = $result } | ConvertTo-Json -Compress
353
+ } catch {
354
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
355
+ }
356
+ `.trim()}async function vt(e,n,r,i,a){if(e!==`win32`&&e!==`darwin`)return{success:!1,error:`Memory dump currently only implemented for Windows and macOS`};if(e===`darwin`){let e=parseInt(r,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};if(!Number.isInteger(n)||n<=0)return{success:!1,error:`Invalid pid`};if(!Number.isInteger(i)||i<=0)return{success:!1,error:`Invalid size`};let t=`0x${e.toString(16)}`;try{let{stdout:e}=await L(`lldb`,[`--batch`,`-p`,String(n),`-o`,`memory read --outfile ${a} --binary ${t} -c ${i}`,`-o`,`process detach`],{timeout:u,maxBuffer:1024*1024});return e.includes(`bytes written`)?{success:!0}:{success:!1,error:`lldb dump failed: ${(e.split(`
357
+ `).find(e=>e.includes(`error:`))??e).trim()}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}try{let e=parseInt(r,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};if(!Number.isInteger(n)||n<=0)return{success:!1,error:`Invalid pid`};if(!Number.isInteger(i)||i<=0)return{success:!1,error:`Invalid size`};let{stdout:t}=await R(_t(n,e,i,a),{maxBuffer:1024*1024,timeout:u}),o=t.trim();if(!o)throw Error(`PowerShell returned empty output`);let s=JSON.parse(o);return{success:s.success,error:s.error}}catch(e){return t.error(`Memory dump failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function yt(e){return`
358
+ Add-Type @"
359
+ using System;
360
+ using System.Runtime.InteropServices;
361
+ using System.Collections.Generic;
362
+ using System.ComponentModel;
363
+
364
+ public class RegionEnumerator {
365
+ [DllImport("kernel32.dll", SetLastError = true)]
366
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
367
+
368
+ [DllImport("kernel32.dll", SetLastError = true)]
369
+ public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr addr, out MEMORY_BASIC_INFORMATION info, int size);
370
+
371
+ [DllImport("kernel32.dll", SetLastError = true)]
372
+ public static extern bool CloseHandle(IntPtr handle);
373
+
374
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
375
+
376
+ [StructLayout(LayoutKind.Sequential)]
377
+ public struct MEMORY_BASIC_INFORMATION {
378
+ public IntPtr BaseAddress;
379
+ public IntPtr AllocationBase;
380
+ public uint AllocationProtect;
381
+ public IntPtr RegionSize;
382
+ public uint State;
383
+ public uint Protect;
384
+ public uint Type;
385
+ }
386
+
387
+ const uint MEM_COMMIT = 0x1000;
388
+ const uint MEM_FREE = 0x10000;
389
+ const uint MEM_RESERVE = 0x2000;
390
+ const uint PAGE_READONLY = 0x02;
391
+ const uint PAGE_READWRITE = 0x04;
392
+ const uint PAGE_WRITECOPY = 0x08;
393
+ const uint PAGE_EXECUTE = 0x10;
394
+ const uint PAGE_EXECUTE_READ = 0x20;
395
+ const uint PAGE_EXECUTE_READWRITE = 0x40;
396
+
397
+ public static List<object> EnumerateRegions(int pid) {
398
+ var regions = new List<object>();
399
+ IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
400
+ if (hProcess == IntPtr.Zero) {
401
+ int error = Marshal.GetLastWin32Error();
402
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
403
+ }
404
+
405
+ try {
406
+ IntPtr addr = IntPtr.Zero;
407
+ MEMORY_BASIC_INFORMATION info;
408
+ int infoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
409
+ int scannedRegions = 0;
410
+
411
+ while (VirtualQueryEx(hProcess, addr, out info, infoSize) == infoSize) {
412
+ scannedRegions++;
413
+ string state = info.State == MEM_COMMIT ?
414
+ "COMMIT" :
415
+ (info.State == MEM_RESERVE ? "RESERVE" : (info.State == MEM_FREE ? "FREE" : "UNKNOWN"));
416
+ string protect = GetProtectionString(info.Protect);
417
+ bool isReadable = (info.State == MEM_COMMIT) && ((info.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)) != 0);
418
+
419
+ regions.Add(new {
420
+ baseAddress = "0x" + info.BaseAddress.ToInt64().ToString("X"),
421
+ size = info.RegionSize.ToInt64(),
422
+ state = state,
423
+ protection = protect,
424
+ isReadable = isReadable,
425
+ type = info.Type == 0x1000000 ? "IMAGE" : (info.Type == 0x40000 ? "MAPPED" : "PRIVATE")
426
+ });
427
+
428
+ if (regions.Count >= 10000 || scannedRegions >= 50000) break;
429
+ long baseAddr = info.BaseAddress.ToInt64();
430
+ long regionSize = info.RegionSize.ToInt64();
431
+ if (regionSize <= 0) break;
432
+ long nextAddr = baseAddr + regionSize;
433
+ if (nextAddr <= baseAddr) break;
434
+ addr = new IntPtr(nextAddr);
435
+ if (addr.ToInt64() >= 0x7FFFFFFF0000) break;
436
+ }
437
+
438
+ return regions;
439
+ } finally {
440
+ CloseHandle(hProcess);
441
+ }
442
+ }
443
+
444
+ private static string GetProtectionString(uint protect) {
445
+ if (protect == 0) return "NOACCESS";
446
+ string s = "";
447
+ if ((protect & 0x100) != 0) s += "NOACCESS ";
448
+ if ((protect & PAGE_READONLY) != 0) s += "R ";
449
+ if ((protect & PAGE_READWRITE) != 0) s += "RW ";
450
+ if ((protect & PAGE_WRITECOPY) != 0) s += "W ";
451
+ if ((protect & PAGE_EXECUTE) != 0) s += "X ";
452
+ if ((protect & PAGE_EXECUTE_READ) != 0) s += "RX ";
453
+ if ((protect & PAGE_EXECUTE_READWRITE) != 0) s += "RWX ";
454
+ if ((protect & 0x100) != 0) s += "GUARD ";
455
+ return s.Trim();
456
+ }
457
+ }
458
+ "@
459
+
460
+ try {
461
+ $regions = [RegionEnumerator]::EnumerateRegions(${e})
462
+ @{ success = $true; regions = $regions; count = $regions.Count } | ConvertTo-Json -Compress -Depth 10
463
+ } catch {
464
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
465
+ }
466
+ `.trim()}async function bt(e,n){if(e===`linux`)try{return{success:!0,regions:T(ue(`/proc/${n}/maps`,`utf-8`)).filter(e=>e.permissions.read).map(e=>({baseAddress:`0x${e.start.toString(16)}`,size:Number(e.end-e.start),state:`COMMIT`,protection:oe(e.permissions),isReadable:!0,type:e.pathname||`anonymous`}))}}catch(e){return t.error(`Linux region enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}if(e!==`win32`&&e!==`darwin`)return{success:!1,error:`Region enumeration currently only implemented for Windows, Linux, and macOS`};if(e===`darwin`)try{let{stdout:e}=await I(`vmmap -v ${n}`,{timeout:i,maxBuffer:1024*1024*5}),t=[],r=/^(\S[^\t]*?)\s{2,}([0-9a-f]+)-([0-9a-f]+)\s+\[.*?\]\s+([a-z-]+)\/([a-z-]+)/;for(let n of e.split(`
467
+ `)){let e=n.match(r);if(!e)continue;let i=e[1],a=e[2],o=e[3],s=e[4],c=e[5],l=parseInt(a,16),u=parseInt(o,16);t.push({baseAddress:`0x${a}`,size:u-l,type:i.trim(),protect:s,maxProtect:c,isReadable:s.includes(`r`),isWritable:s.includes(`w`),isExecutable:s.includes(`x`)})}return{success:!0,regions:t}}catch(e){return t.error(`macOS region enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}if(E())try{let e=await z.enumerateRegions(n);if(e.success)return e;t.warn(`Native Windows region enumeration failed, falling back to PowerShell`,{pid:n,error:e.error,nativeAvailable:E()})}catch(e){t.warn(`Native Windows region enumeration threw, falling back to PowerShell`,{pid:n,error:e instanceof Error?e.message:String(e),nativeAvailable:E()})}try{let{stdout:e}=await R(yt(n),{maxBuffer:1024*1024*10,timeout:o}),t=e.trim();if(!t)throw Error(`PowerShell returned empty output`);let r=JSON.parse(t);return{success:r.success,regions:r.regions,error:r.error}}catch(e){return t.error(`Region enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function xt(e,t){return`
468
+ Add-Type @"
469
+ using System;
470
+ using System.Runtime.InteropServices;
471
+ using System.ComponentModel;
472
+
473
+ public class ProtectionChecker {
474
+ [DllImport("kernel32.dll", SetLastError = true)]
475
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
476
+
477
+ [DllImport("kernel32.dll", SetLastError = true)]
478
+ public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr addr, out MEMORY_BASIC_INFORMATION info, int size);
479
+
480
+ [DllImport("kernel32.dll", SetLastError = true)]
481
+ public static extern bool CloseHandle(IntPtr handle);
482
+
483
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
484
+
485
+ [StructLayout(LayoutKind.Sequential)]
486
+ public struct MEMORY_BASIC_INFORMATION {
487
+ public IntPtr BaseAddress;
488
+ public IntPtr AllocationBase;
489
+ public uint AllocationProtect;
490
+ public IntPtr RegionSize;
491
+ public uint State;
492
+ public uint Protect;
493
+ public uint Type;
494
+ }
495
+
496
+ const uint MEM_COMMIT = 0x1000;
497
+ const uint PAGE_NOACCESS = 0x01;
498
+ const uint PAGE_READONLY = 0x02;
499
+ const uint PAGE_READWRITE = 0x04;
500
+ const uint PAGE_WRITECOPY = 0x08;
501
+ const uint PAGE_EXECUTE = 0x10;
502
+ const uint PAGE_EXECUTE_READ = 0x20;
503
+ const uint PAGE_EXECUTE_READWRITE = 0x40;
504
+ const uint PAGE_EXECUTE_WRITECOPY = 0x80;
505
+ const uint PAGE_GUARD = 0x100;
506
+
507
+ public static object CheckProtection(int pid, long address) {
508
+ IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
509
+ if (hProcess == IntPtr.Zero) {
510
+ int error = Marshal.GetLastWin32Error();
511
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
512
+ }
513
+
514
+ try {
515
+ MEMORY_BASIC_INFORMATION info;
516
+ int infoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
517
+ int result = VirtualQueryEx(hProcess, (IntPtr)address, out info, infoSize);
518
+
519
+ if (result != infoSize) {
520
+ return new { success = false, error = "Failed to query memory region" };
521
+ }
522
+
523
+ if (info.State != MEM_COMMIT) {
524
+ return new {
525
+ success = true,
526
+ protection = "NOT_COMMITTED",
527
+ isWritable = false,
528
+ isReadable = false,
529
+ isExecutable = false,
530
+ regionStart = "0x" + info.BaseAddress.ToInt64().ToString("X"),
531
+ regionSize = info.RegionSize.ToInt64()
532
+ };
533
+ }
534
+
535
+ uint protect = info.Protect;
536
+ string protectionStr = "";
537
+ bool isWritable = false;
538
+ bool isReadable = false;
539
+ bool isExecutable = false;
540
+
541
+ if ((protect & PAGE_NOACCESS) != 0) protectionStr += "NOACCESS ";
542
+ if ((protect & PAGE_READONLY) != 0) { protectionStr += "R "; isReadable = true; }
543
+ if ((protect & PAGE_READWRITE) != 0) { protectionStr += "RW "; isReadable = true; isWritable = true; }
544
+ if ((protect & PAGE_WRITECOPY) != 0) { protectionStr += "WC "; isReadable = true; isWritable = true; }
545
+ if ((protect & PAGE_EXECUTE) != 0) { protectionStr += "X "; isExecutable = true; }
546
+ if ((protect & PAGE_EXECUTE_READ) != 0) { protectionStr += "RX "; isReadable = true; isExecutable = true; }
547
+ if ((protect & PAGE_EXECUTE_READWRITE) != 0) {
548
+ protectionStr += "RWX ";
549
+ isReadable = true;
550
+ isWritable = true;
551
+ isExecutable = true;
552
+ ;
553
+ }
554
+ if ((protect & PAGE_EXECUTE_WRITECOPY) != 0) {
555
+ protectionStr += "RWCX ";
556
+ isReadable = true;
557
+ isWritable = true;
558
+ isExecutable = true;
559
+ ;
560
+ }
561
+ if ((protect & PAGE_GUARD) != 0) protectionStr += "GUARD ";
562
+
563
+ return new {
564
+ success = true,
565
+ protection = protectionStr.Trim(),
566
+ isWritable = isWritable,
567
+ isReadable = isReadable,
568
+ isExecutable = isExecutable,
569
+ regionStart = "0x" + info.BaseAddress.ToInt64().ToString("X"),
570
+ regionSize = info.RegionSize.ToInt64()
571
+ };
572
+ } finally {
573
+ CloseHandle(hProcess);
574
+ }
575
+ }
576
+ }
577
+ "@
578
+
579
+ try {
580
+ $result = [ProtectionChecker]::CheckProtection(${e}, ${t})
581
+ $result | ConvertTo-Json -Compress
582
+ } catch {
583
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
584
+ }
585
+ `.trim()}async function Z(e,r,i){let a=BigInt(i.startsWith(`0x`)?i:`0x${i}`);if(e===`linux`)try{let e=T(await le.readFile(`/proc/${r}/maps`,`utf-8`)).find(e=>a>=e.start&&a<e.end);return e?{success:!0,protection:oe(e.permissions),isReadable:e.permissions.read,isWritable:e.permissions.write,isExecutable:e.permissions.exec,regionStart:`0x${e.start.toString(16)}`,regionSize:Number(e.end-e.start)}:{success:!1,error:`Address ${i} not found in any memory region`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}if(e===`darwin`){try{let{createPlatformProvider:e}=await import(`./factory-BxNdBiZa.mjs`).then(e=>e.n),t=e();if((await t.checkAvailability()).available){let e=t.openProcess(r,!1);try{let n=t.queryRegion(e,a);return n?{success:!0,protection:[n.isReadable?`r`:`-`,n.isWritable?`w`:`-`,n.isExecutable?`x`:`-`].join(``),isReadable:n.isReadable,isWritable:n.isWritable,isExecutable:n.isExecutable,regionStart:`0x${n.baseAddress.toString(16)}`,regionSize:n.size}:{success:!1,error:`Address ${i} not found in any memory region`}}finally{t.closeProcess(e)}}}catch{}try{let e=parseInt(i,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};let{stdout:t}=await I(`vmmap -v ${r}`,{timeout:n,maxBuffer:1024*1024*5}),a=/^(\S[^\t]*?)\s{2,}([0-9a-f]+)-([0-9a-f]+)\s+\[.*?\]\s+([a-z-]+)\/([a-z-]+)/;for(let n of t.split(`
586
+ `)){let t=n.match(a);if(!t)continue;let r=parseInt(t[2],16),i=parseInt(t[3],16);if(e>=r&&e<i){let e=t[4];return{success:!0,protection:e,isReadable:e.includes(`r`),isWritable:e.includes(`w`),isExecutable:e.includes(`x`),regionStart:`0x${t[2]}`,regionSize:i-r}}}return{success:!1,error:`Address ${i} not found in any memory region`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}if(E())try{let e=await z.checkMemoryProtection(r,i);if(e.success)return e;t.warn(`Native Windows memory protection check failed, falling back to PowerShell`,{pid:r,address:i,error:e.error,nativeAvailable:E()})}catch(e){t.warn(`Native Windows memory protection check threw, falling back to PowerShell`,{pid:r,address:i,error:e instanceof Error?e.message:String(e),nativeAvailable:E()})}try{let e=parseInt(i,16);if(isNaN(e))return{success:!1,error:`Invalid address format`};let{stdout:t}=await R(xt(r,e),{maxBuffer:1024*1024,timeout:re}),n=t.trim();if(!n)throw Error(`PowerShell returned empty output`);let a=JSON.parse(n);return{success:a.success,protection:a.protection,isWritable:a.isWritable,isReadable:a.isReadable,isExecutable:a.isExecutable,regionStart:a.regionStart,regionSize:a.regionSize,error:a.error}}catch(e){return t.error(`Memory protection check failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}async function St(e,n){if(e!==`win32`)return{success:!1,error:`Module enumeration currently only implemented for Windows`};try{let{stdout:e}=await R(`
587
+ Add-Type @"
588
+ using System;
589
+ using System.Runtime.InteropServices;
590
+ using System.Collections.Generic;
591
+ using System.ComponentModel;
592
+
593
+ public class ModuleEnumerator {
594
+ [DllImport("psapi.dll", SetLastError = true)]
595
+ public static extern bool EnumProcessModules(IntPtr hProcess, [Out] IntPtr[] lphModule, int cb, out int lpcbNeeded);
596
+
597
+ [DllImport("psapi.dll", SetLastError = true)]
598
+ public static extern int GetModuleBaseName(IntPtr hProcess, IntPtr hModule, [Out] System.Text.StringBuilder lpBaseName, int nSize);
599
+
600
+ [DllImport("psapi.dll", SetLastError = true)]
601
+ public static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out MODULEINFO lpmodinfo, int cb);
602
+
603
+ [DllImport("kernel32.dll", SetLastError = true)]
604
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
605
+
606
+ [DllImport("kernel32.dll", SetLastError = true)]
607
+ public static extern bool CloseHandle(IntPtr handle);
608
+
609
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
610
+ const int PROCESS_VM_READ = 0x0010;
611
+
612
+ [StructLayout(LayoutKind.Sequential)]
613
+ public struct MODULEINFO {
614
+ public IntPtr lpBaseOfDll;
615
+ public int SizeOfImage;
616
+ public IntPtr EntryPoint;
617
+ }
618
+
619
+ public static object Enumerate(int pid) {
620
+ IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
621
+ if (hProcess == IntPtr.Zero) {
622
+ int error = Marshal.GetLastWin32Error();
623
+ throw new Win32Exception(error, "Failed to open process");
624
+ }
625
+
626
+ try {
627
+ IntPtr[] modules = new IntPtr[1024];
628
+ int cbNeeded;
629
+
630
+ if (!EnumProcessModules(hProcess, modules, modules.Length * IntPtr.Size, out cbNeeded)) {
631
+ int error = Marshal.GetLastWin32Error();
632
+ throw new Win32Exception(error, "EnumProcessModules failed");
633
+ }
634
+
635
+ int numModules = cbNeeded / IntPtr.Size;
636
+ var result = new List<object>();
637
+
638
+ for (int i = 0; i < numModules; i++) {
639
+ System.Text.StringBuilder baseName = new System.Text.StringBuilder(256);
640
+ if (GetModuleBaseName(hProcess, modules[i], baseName, baseName.Capacity) > 0) {
641
+ MODULEINFO modInfo;
642
+ if (GetModuleInformation(hProcess, modules[i], out modInfo, Marshal.SizeOf(typeof(MODULEINFO)))) {
643
+ result.Add(new {
644
+ name = baseName.ToString(),
645
+ baseAddress = "0x" + modInfo.lpBaseOfDll.ToInt64().ToString("X"),
646
+ size = modInfo.SizeOfImage
647
+ });
648
+ }
649
+ }
650
+ }
651
+
652
+ return new { success = true, modules = result };
653
+ } finally {
654
+ CloseHandle(hProcess);
655
+ }
656
+ }
657
+ }
658
+ "@
659
+
660
+ try {
661
+ $result = [ModuleEnumerator]::Enumerate(${n})
662
+ $result | ConvertTo-Json -Compress -Depth 10
663
+ } catch {
664
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
665
+ }
666
+ `,{maxBuffer:1024*1024*10,timeout:o}),t=e.trim();if(!t)throw Error(`PowerShell returned empty output`);return JSON.parse(t)}catch(e){return t.error(`Module enumeration failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function Ct(e){if(/[`$"';|<>&()\\\n\r]/.test(e))throw Error(`Path contains unsafe characters: ${e}`)}function wt(e,t){return`
667
+ Add-Type @"
668
+ using System;
669
+ using System.Runtime.InteropServices;
670
+ using System.ComponentModel;
671
+ using System.IO;
672
+
673
+ public class DllInjector {
674
+ [DllImport("kernel32.dll", SetLastError = true)]
675
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
676
+
677
+ [DllImport("kernel32.dll", SetLastError = true)]
678
+ public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr addr, int size, int allocType, int protect);
679
+
680
+ [DllImport("kernel32.dll", SetLastError = true)]
681
+ public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int written);
682
+
683
+ [DllImport("kernel32.dll", SetLastError = true)]
684
+ public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr attr, int stackSize, IntPtr startAddr, IntPtr param, int flags, out int threadId);
685
+
686
+ [DllImport("kernel32.dll", SetLastError = true)]
687
+ public static extern IntPtr GetModuleHandle(string name);
688
+
689
+ [DllImport("kernel32.dll", SetLastError = true)]
690
+ public static extern IntPtr GetProcAddress(IntPtr hModule, string name);
691
+
692
+ [DllImport("kernel32.dll", SetLastError = true)]
693
+ public static extern bool CloseHandle(IntPtr handle);
694
+
695
+ [DllImport("kernel32.dll", SetLastError = true)]
696
+ public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr addr, int size, int freeType);
697
+
698
+ const int PROCESS_CREATE_THREAD = 0x0002;
699
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
700
+ const int PROCESS_VM_OPERATION = 0x0008;
701
+ const int PROCESS_VM_WRITE = 0x0020;
702
+ const int MEM_COMMIT = 0x1000;
703
+ const int MEM_RESERVE = 0x2000;
704
+ const int PAGE_READWRITE = 0x04;
705
+ const int MEM_RELEASE = 0x8000;
706
+
707
+ public static object Inject(int pid, string dllPath) {
708
+ if (!File.Exists(dllPath)) {
709
+ return new { success = false, error = "DLL not found: " + dllPath };
710
+ }
711
+
712
+ IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid);
713
+ if (hProcess == IntPtr.Zero) {
714
+ int error = Marshal.GetLastWin32Error();
715
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
716
+ }
717
+
718
+ try {
719
+ byte[] dllBytes = System.Text.Encoding.ASCII.GetBytes(dllPath + "\\0");
720
+ IntPtr remoteMem = VirtualAllocEx(hProcess, IntPtr.Zero, dllBytes.Length, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
721
+ if (remoteMem == IntPtr.Zero) {
722
+ int error = Marshal.GetLastWin32Error();
723
+ throw new Win32Exception(error, "Failed to allocate memory in target");
724
+ }
725
+
726
+ try {
727
+ int written;
728
+ if (!WriteProcessMemory(hProcess, remoteMem, dllBytes, dllBytes.Length, out written)) {
729
+ int error = Marshal.GetLastWin32Error();
730
+ throw new Win32Exception(error, "Failed to write DLL path to target");
731
+ }
732
+
733
+ IntPtr hKernel32 = GetModuleHandle("kernel32.dll");
734
+ IntPtr loadLibraryAddr = GetProcAddress(hKernel32, "LoadLibraryA");
735
+ if (loadLibraryAddr == IntPtr.Zero) {
736
+ throw new Exception("Failed to get LoadLibraryA address");
737
+ }
738
+
739
+ int threadId;
740
+ IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLibraryAddr, remoteMem, 0, out threadId);
741
+ if (hThread == IntPtr.Zero) {
742
+ int error = Marshal.GetLastWin32Error();
743
+ throw new Win32Exception(error, "Failed to create remote thread");
744
+ }
745
+
746
+ CloseHandle(hThread);
747
+ return new { success = true, remoteThreadId = threadId };
748
+ } finally {
749
+ VirtualFreeEx(hProcess, remoteMem, 0, MEM_RELEASE);
750
+ }
751
+ } finally {
752
+ CloseHandle(hProcess);
753
+ }
754
+ }
755
+ }
756
+ "@
757
+
758
+ try {
759
+ $result = [DllInjector]::Inject(${e}, "${t.replace(/\\/g,`\\\\`).replace(/"/g,'`"').replace(/`/g,"``").replace(/\$/g,"`$")}")
760
+ $result | ConvertTo-Json -Compress
761
+ } catch {
762
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
763
+ }
764
+ `.trim()}async function Tt(e,n,r){if(e===`linux`)try{Ct(r);let{stderr:e}=await I(`gdb -p ${n} -batch -ex "call (void*)dlopen(\\"${r}\\", 1)" -ex "quit"`,{timeout:d});if(e.includes(`Operation not permitted`)||e.includes(`ptrace:`))throw Error(`GDB injection failed (ptrace blocked): ${e}`);return{success:!0}}catch(e){return t.error(`Linux DLL injection failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}else if(e===`darwin`)try{Ct(r);let{stdout:e,stderr:t}=await I(`lldb --batch -p ${n} -o "expr (void*)dlopen(\\"${r}\\", 1)"`,{timeout:d});if(t.includes(`error:`)||e.includes(`error:`))throw Error(`LLDB injection failed: ${t||e}`);return{success:!0}}catch(e){return t.error(`macOS DLL injection failed:`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}else if(e!==`win32`)return{success:!1,error:`DLL injection not supported on this platform`};try{let{stdout:e}=await R(wt(n,r),{maxBuffer:1024*1024,timeout:d}),t=e.trim();if(!t)throw Error(`PowerShell returned empty output`);let i=JSON.parse(t);return{success:i.success,remoteThreadId:i.remoteThreadId,error:i.error}}catch(e){return t.error(`DLL injection failed:`,e),{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function Et(e,t){return`
765
+ Add-Type @"
766
+ using System;
767
+ using System.Runtime.InteropServices;
768
+ using System.ComponentModel;
769
+
770
+ public class ShellcodeInjector {
771
+ [DllImport("kernel32.dll", SetLastError = true)]
772
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
773
+
774
+ [DllImport("kernel32.dll", SetLastError = true)]
775
+ public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr addr, int size, int allocType, int protect);
776
+
777
+ [DllImport("kernel32.dll", SetLastError = true)]
778
+ public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr addr, byte[] buffer, int size, out int written);
779
+
780
+ [DllImport("kernel32.dll", SetLastError = true)]
781
+ public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr attr, int stackSize, IntPtr startAddr, IntPtr param, int flags, out int threadId);
782
+
783
+ [DllImport("kernel32.dll", SetLastError = true)]
784
+ public static extern bool CloseHandle(IntPtr handle);
785
+
786
+ [DllImport("kernel32.dll", SetLastError = true)]
787
+ public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr addr, int size, int newProtect, out int oldProtect);
788
+
789
+ const int PROCESS_CREATE_THREAD = 0x0002;
790
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
791
+ const int PROCESS_VM_OPERATION = 0x0008;
792
+ const int PROCESS_VM_WRITE = 0x0020;
793
+ const int MEM_COMMIT = 0x1000;
794
+ const int MEM_RESERVE = 0x2000;
795
+ const int PAGE_READWRITE = 0x04;
796
+ const int PAGE_EXECUTE_READWRITE = 0x40;
797
+
798
+ public static object Inject(int pid, byte[] shellcode) {
799
+ IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid);
800
+ if (hProcess == IntPtr.Zero) {
801
+ int error = Marshal.GetLastWin32Error();
802
+ throw new Win32Exception(error, "Failed to open process. Run as Administrator.");
803
+ }
804
+
805
+ try {
806
+ IntPtr remoteMem = VirtualAllocEx(hProcess, IntPtr.Zero, shellcode.Length, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
807
+ if (remoteMem == IntPtr.Zero) {
808
+ int error = Marshal.GetLastWin32Error();
809
+ throw new Win32Exception(error, "Failed to allocate memory in target");
810
+ }
811
+
812
+ try {
813
+ int written;
814
+ if (!WriteProcessMemory(hProcess, remoteMem, shellcode, shellcode.Length, out written)) {
815
+ int error = Marshal.GetLastWin32Error();
816
+ throw new Win32Exception(error, "Failed to write shellcode to target");
817
+ }
818
+
819
+ int oldProtect;
820
+ if (!VirtualProtectEx(hProcess, remoteMem, shellcode.Length, PAGE_EXECUTE_READWRITE, out oldProtect)) {
821
+ int error = Marshal.GetLastWin32Error();
822
+ throw new Win32Exception(error, "Failed to change memory protection to executable");
823
+ }
824
+
825
+ int threadId;
826
+ IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, remoteMem, IntPtr.Zero, 0, out threadId);
827
+ if (hThread == IntPtr.Zero) {
828
+ int error = Marshal.GetLastWin32Error();
829
+ throw new Win32Exception(error, "Failed to create remote thread");
830
+ }
831
+
832
+ CloseHandle(hThread);
833
+ return new { success = true, remoteThreadId = threadId };
834
+ } finally {
835
+ // Note: Memory is not freed to allow shellcode to execute
836
+ }
837
+ } finally {
838
+ CloseHandle(hProcess);
839
+ }
840
+ }
841
+ }
842
+ "@
843
+
844
+ try {
845
+ $shellcode = @(${Array.from(t).join(`,`)})
846
+ $result = [ShellcodeInjector]::Inject(${e}, $shellcode)
847
+ $result | ConvertTo-Json -Compress
848
+ } catch {
849
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
850
+ }
851
+ `.trim()}async function Dt(e,n,r,i=`hex`){try{let t;if(i===`base64`)t=Buffer.from(r,`base64`);else{let e=r.replace(/\s/g,``);t=Buffer.from(e,`hex`)}if(e===`linux`){let e=Array.from(t).map(e=>`\\x${e.toString(16).padStart(2,`0`)}`).join(``),r=`
852
+ import gdb
853
+ import sys
854
+
855
+ def inject():
856
+ try:
857
+ # mmap: PROT_READ|PROT_WRITE|PROT_EXEC (7), MAP_PRIVATE|MAP_ANONYMOUS (34)
858
+ mmap_res = gdb.parse_and_eval("(void*)mmap(0, ${t.length}, 7, 34, -1, 0)")
859
+ addr = int(mmap_res)
860
+ if addr == -1 or addr == 0:
861
+ print("ERROR_INJECT: mmap failed")
862
+ return
863
+
864
+ inf = gdb.selected_inferior()
865
+ inf.write_memory(addr, b"${e}")
866
+
867
+ # Call it directly (creates a crash potentially) or via pthread_create
868
+ # Let's use pthread_create
869
+ thread_t = gdb.parse_and_eval("(void*)malloc(8)")
870
+ res = gdb.parse_and_eval(f"(int)pthread_create({int(thread_t)}, 0, {addr}, 0)")
871
+
872
+ print(f"SUCCESS_INJECT: {int(res)}")
873
+ except Exception as e:
874
+ print(f"ERROR_INJECT: {str(e)}")
875
+
876
+ inject()
877
+ `,i=j(k(),`gdb_inject_${n}_${Date.now()}.py`);await A.writeFile(i,r,`utf8`);try{let{stdout:e,stderr:t}=await I(`gdb -p ${n} -batch -x ${i}`,{timeout:d});if(e.includes(`ERROR_INJECT:`)||t.includes(`ERROR_INJECT:`))throw Error(`GDB injection failed: ${e||t}`);return{success:!0}}finally{await A.unlink(i).catch(()=>{})}}else if(e===`darwin`){let e=Array.from(t).map(e=>e.toString()).join(`,`),r=`
878
+ import lldb
879
+ import sys
880
+
881
+ def __lldb_init_module(debugger, internal_dict):
882
+ try:
883
+ target = debugger.GetSelectedTarget()
884
+ process = target.GetProcess()
885
+
886
+ # mmap: PROT_READ|PROT_WRITE|PROT_EXEC (7), MAP_PRIVATE|MAP_ANON (4098 on macOS)
887
+ res = lldb.SBCommandReturnObject()
888
+ debugger.GetCommandInterpreter().HandleCommand("expr (void*)mmap(0, ${t.length}, 7, 4098, -1, 0)", res)
889
+
890
+ if not res.Succeeded():
891
+ print("ERROR_INJECT: " + res.GetError())
892
+ return
893
+
894
+ addr_str = res.GetOutput().split()[-1]
895
+ addr = int(addr_str, 16)
896
+
897
+ err = lldb.SBError()
898
+ bytes_data = bytes([${e}])
899
+ process.WriteMemory(addr, bytes_data, err)
900
+
901
+ if not err.Success():
902
+ print("ERROR_INJECT: write failed")
903
+ return
904
+
905
+ # create thread
906
+ res2 = lldb.SBCommandReturnObject()
907
+ debugger.GetCommandInterpreter().HandleCommand(f"expr (int)pthread_create((void*)malloc(8), 0, (void*){addr}, 0)", res2)
908
+
909
+ print("SUCCESS_INJECT")
910
+ except Exception as e:
911
+ print("ERROR_INJECT: " + str(e))
912
+ `,i=j(k(),`lldb_inject_${n}_${Date.now()}.py`),a=j(k(),`lldb_inject_cmd_${n}_${Date.now()}.txt`);await A.writeFile(i,r,`utf8`),await A.writeFile(a,`command script import ${i}\\nprocess detach\\n`,`utf8`);try{let{stdout:e}=await I(`lldb --batch -p ${n} --source ${a}`,{timeout:d});if(e.includes(`ERROR_INJECT:`))throw Error(`LLDB injection failed: ${e}`);return{success:!0}}finally{await A.unlink(i).catch(()=>{}),await A.unlink(a).catch(()=>{})}}else if(e!==`win32`)return{success:!1,error:`Shellcode injection not supported on this platform`};let{stdout:a}=await R(Et(n,t),{maxBuffer:1024*1024,timeout:d}),o=a.trim();if(!o)throw Error(`PowerShell returned empty output`);let s=JSON.parse(o);return{success:s.success,remoteThreadId:s.remoteThreadId,error:s.error}}catch(e){return t.error(`Shellcode injection failed:`,e),{success:!1,error:e instanceof Error?e.message:`Execution failed`}}}var Ot=class{activeMonitors=new Map;start(e,t,n=4,r=1e3,i,a){let o=`monitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=setInterval(async()=>{let r=this.activeMonitors.get(o);if(r&&!r.inFlight){r.inFlight=!0;try{let o=await i(e,t,n);o.success&&o.data&&r.lastValue!==o.data&&(a&&r.lastValue!==``&&a(r.lastValue,o.data),r.lastValue=o.data)}finally{r.inFlight=!1}}},r);return typeof s.unref==`function`&&s.unref(),this.activeMonitors.set(o,{pid:e,address:t,interval:r,lastValue:``,timer:s,inFlight:!1}),o}stop(e){let t=this.activeMonitors.get(e);return t?(clearInterval(t.timer),this.activeMonitors.delete(e),!0):!1}};const kt=b;let Q=null;function At(e,t){if(typeof e!=`object`||!e)return``;let n=e[t];return typeof n==`string`?n:``}function jt(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${At(e,`stderr`)}`.toLowerCase();return n.includes(`enoent`)||n.includes(`command not found`)||n.includes(`is not recognized as an internal or external command`)||n.includes(`cannot find`)&&n.includes(`powershell`)?`PowerShell is unavailable. Windows memory operations require powershell.exe to verify Administrator privileges.`:`PowerShell command execution failed while checking Administrator privileges: ${t}`}async function Mt(){try{let{stdout:e}=await R(`([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)`,{timeout:l}),t=e.trim().toLowerCase();return t===`true`?{available:!0}:t===`false`?{available:!1,reason:`Windows memory operations require Administrator privileges. Please run your terminal/IDE as Administrator and retry.`}:{available:!1,reason:`PowerShell command execution failed while checking Administrator privileges: unexpected output "${e.trim()} '(empty)'}".`}}catch(e){return{available:!1,reason:jt(e)}}}async function Nt(){let e=Date.now();if(Q&&Q.expiresAt>e)return Q.result;let t=await Mt();return Q={expiresAt:e+kt,result:t},t}async function Pt(e){switch(e){case`win32`:return Nt();case`linux`:try{let{stdout:e}=await I(`id -u`,{timeout:m});if(e.trim()===`0`)return{available:!0};try{return await I(`capsh --print 2>/dev/null | grep -q "cap_sys_ptrace"`,{timeout:m}),{available:!0}}catch{return{available:!1,reason:`Linux memory operations require root privileges or CAP_SYS_PTRACE capability. Run with sudo.`}}}catch{return{available:!1,reason:`Requires root privileges for /proc/pid/mem access. Run with sudo.`}}case`darwin`:try{return await I(`which lldb`,{timeout:m}),{available:!0,reason:process.getuid?.()===0?void 0:`Running without root — memory access works for own processes only. Use sudo for other processes.`}}catch{return{available:!1,reason:`lldb not found. Install Xcode Command Line Tools: xcode-select --install`}}default:return{available:!1,reason:`Platform ${e} not supported for memory operations.`}}}async function Ft(e,t){if(e!==`win32`)return{success:!1,error:`Debug port check currently only implemented for Windows`};try{let{stdout:e}=await R(`
913
+ Add-Type @"
914
+ using System;
915
+ using System.Runtime.InteropServices;
916
+ using System.ComponentModel;
917
+
918
+ public class DebugChecker {
919
+ [DllImport("ntdll.dll")]
920
+ public static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, out IntPtr processInformation, int processInformationLength, out int returnLength);
921
+
922
+ [DllImport("kernel32.dll", SetLastError = true)]
923
+ public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
924
+
925
+ [DllImport("kernel32.dll", SetLastError = true)]
926
+ public static extern bool CloseHandle(IntPtr handle);
927
+
928
+ const int PROCESS_QUERY_INFORMATION = 0x0400;
929
+ const int ProcessDebugPort = 7;
930
+
931
+ public static object Check(int pid) {
932
+ IntPtr hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
933
+ if (hProcess == IntPtr.Zero) {
934
+ int error = Marshal.GetLastWin32Error();
935
+ throw new Win32Exception(error, "Failed to open process");
936
+ }
937
+
938
+ try {
939
+ IntPtr debugPort;
940
+ int returnLength;
941
+ int status = NtQueryInformationProcess(hProcess, ProcessDebugPort, out debugPort, IntPtr.Size, out returnLength);
942
+
943
+ if (status != 0) {
944
+ return new { success = false, error = "NtQueryInformationProcess failed with status: 0x" + status.ToString("X") };
945
+ }
946
+
947
+ return new { success = true, isDebugged = debugPort != IntPtr.Zero };
948
+ } finally {
949
+ CloseHandle(hProcess);
950
+ }
951
+ }
952
+ }
953
+ "@
954
+
955
+ try {
956
+ $result = [DebugChecker]::Check(${t})
957
+ $result | ConvertTo-Json -Compress
958
+ } catch {
959
+ @{ success = $false; error = $_.Exception.Message } | ConvertTo-Json -Compress
960
+ }
961
+ `,{maxBuffer:1024*1024,timeout:l*2}),n=e.trim();if(!n)throw Error(`PowerShell returned empty output`);try{return JSON.parse(n)}catch{throw Error(`PowerShell returned empty output`)}}catch(e){return{success:!1,error:e instanceof Error?e.message:`PowerShell execution failed`}}}function It(){switch(process.platform){case`win32`:return`win32`;case`linux`:return`linux`;case`darwin`:return`darwin`;default:return`unknown`}}var Lt=class{platform;monitorManager=new Ot;constructor(){this.platform=It(),t.info(`MemoryManager initialized for platform: ${this.platform}`)}async readMemory(e,t,n){return qe(this.platform,e,t,n,(e,t)=>Z(this.platform,e,t))}async writeMemory(e,t,n,r=`hex`){return et(this.platform,e,t,n,r,(e,t)=>Z(this.platform,e,t))}async batchMemoryWrite(e,t){return nt(e,t,(e,t,n,r)=>this.writeMemory(e,t,n,r))}async scanMemory(e,t,n=`hex`,r=!1){return ft(this.platform,e,t,n,r)}async scanMemoryFiltered(e,t,n,r=`hex`){return pt(e,t,n,r,(e,t,n)=>this.readMemory(e,t,n),(e,t,n)=>this.scanMemory(e,t,n))}async dumpMemoryRegion(e,t,n,r){return vt(this.platform,e,t,n,r)}async enumerateRegions(e){return bt(this.platform,e)}async checkMemoryProtection(e,t){return Z(this.platform,e,t)}async enumerateModules(e){return St(this.platform,e)}async injectDll(e,t){return Tt(this.platform,e,t)}async injectShellcode(e,t,n=`hex`){return Dt(this.platform,e,t,n)}async checkDebugPort(e){return Ft(this.platform,e)}startMemoryMonitor(e,t,n=4,r=1e3,i){return this.monitorManager.start(e,t,n,r,(e,t,n)=>this.readMemory(e,t,n),i)}stopMemoryMonitor(e){return this.monitorManager.stop(e)}async checkAvailability(){return Pt(this.platform)}};function $(){let e=process.platform;switch(e){case`win32`:return`win32`;case`linux`:return`linux`;case`darwin`:return`darwin`;default:return t.warn(`Unsupported platform: ${e}`),`unknown`}}function Rt(){let e=$();switch(t.info(`Creating ProcessManager for platform: ${e}`),e){case`win32`:return new Ne;case`linux`:return new Fe;case`darwin`:return new ze;default:throw Error(`Unsupported platform: ${e}. ProcessManager requires Windows, Linux, or macOS.`)}}var zt=class{manager;platform;constructor(){this.platform=$(),this.manager=Rt()}getPlatform(){return this.platform}async findProcesses(e){return this.manager.findProcesses(e)}async getProcessByPid(e){return this.manager.getProcessByPid(e)}async getProcessWindows(e){return this.manager.getProcessWindows(e)}async checkDebugPort(e,t){return this.manager.checkDebugPort(e,t)}async launchWithDebug(e,t,n){return this.manager.launchWithDebug(e,t,n)}async killProcess(e){return this.manager.killProcess(e)}async getProcessCommandLine(e){return this.manager.getProcessCommandLine(e)}async findBrowserProcesses(e){return this.platform===`win32`?e?.processNamePattern||e?.windowClassPattern?this.manager.findChromiumProcesses({processNamePattern:e.processNamePattern,windowClassPattern:e.windowClassPattern}):this.manager.findChromiumAppProcesses():this.platform===`linux`||this.platform===`darwin`?this.manager.findChromeProcesses():null}};export{Lt as n,z as r,zt as t};