@jshookmcp/jshook 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -4
- package/README.zh.md +19 -4
- package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
- package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
- package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
- package/dist/CodeInjector-B099WO6x.mjs +1 -0
- package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
- package/dist/CpuEngine-BC8jayy9.mjs +1 -0
- package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
- package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
- package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
- package/dist/DetailedDataManager-Dgh402Gp.mjs +5 -0
- package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
- package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
- package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
- package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
- package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
- package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
- package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
- package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
- package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
- package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
- package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/MemoryController-CCsGuGJS.mjs +2 -0
- package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
- package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
- package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
- package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
- package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
- package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
- package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
- package/dist/{handlers-mPFiNPe8.mjs → QuickJSSandbox-CIde-jzG.mjs} +2 -5
- package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
- package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
- package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
- package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
- package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
- package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
- package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
- package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
- package/dist/ToolRouter.policy-Bgb3S8jc.mjs +4 -0
- package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
- package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
- package/dist/Win32API-G7QPyckq.mjs +1 -0
- package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
- package/dist/allocation-track-CiI-CnaI.mjs +1 -0
- package/dist/analysis-CojUzwX-.mjs +27 -0
- package/dist/antidebug-CgU84TE1.mjs +1 -0
- package/dist/apk-DrPBsOq8.mjs +1 -0
- package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
- package/dist/artifacts-Bx9GLx4J.mjs +1 -0
- package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
- package/dist/ast-utils-B9E5k_v1.mjs +1 -0
- package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
- package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
- package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
- package/dist/browser-QDUu5ML9.mjs +29 -0
- package/dist/{handlers-yo_xYzT8.mjs → canvas-g5kmLdY-.mjs} +1098 -24
- package/dist/{capabilities-CyXuKUl1.mjs → capabilities-DwzyxL2w.mjs} +1 -1
- package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
- package/dist/collector-Cld4i-E4.mjs +1 -0
- package/dist/config-5ODJ3Aj0.mjs +3 -0
- package/dist/constants-nvsLpSri.mjs +1 -0
- package/dist/coordination-C6y2gM9O.mjs +98 -0
- package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
- package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
- package/dist/debugger-C2SpiXoO.mjs +1 -0
- package/dist/definitions-0mtilYzG.mjs +1 -0
- package/dist/definitions-9csunmeX.mjs +1 -0
- package/dist/definitions-B11MudW_.mjs +1 -0
- package/dist/definitions-BKpRDjcI.mjs +1 -0
- package/dist/definitions-BXE3H4re.mjs +1 -0
- package/dist/definitions-BlPHe5DX.mjs +1 -0
- package/dist/definitions-Bob4XMxI.mjs +27 -0
- package/dist/definitions-BpIQN2nm.mjs +1 -0
- package/dist/definitions-BvolWeSu.mjs +1 -0
- package/dist/definitions-C-6j3Ejl.mjs +1 -0
- package/dist/definitions-C-AdFfFu.mjs +1 -0
- package/dist/definitions-CArdw_9T.mjs +1 -0
- package/dist/definitions-CCvIcRrT.mjs +1 -0
- package/dist/definitions-CJPE5PIl.mjs +1 -0
- package/dist/definitions-CbqeW06u.mjs +1 -0
- package/dist/definitions-Cexmkypg.mjs +1 -0
- package/dist/definitions-D1dxl8qt.mjs +1 -0
- package/dist/definitions-D3uT-ZbU.mjs +1 -0
- package/dist/definitions-DtOY5iUc.mjs +1 -0
- package/dist/{definitions-DxFNRQNK2.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
- package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/definitions-ihxOqOC4.mjs +1 -0
- package/dist/deopt-trace-qnAcC931.mjs +17 -0
- package/dist/disasm-DoxSucGp.mjs +1 -0
- package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
- package/dist/encoding-UMtwgy4M.mjs +2 -0
- package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
- package/dist/factory-BeND77hf.mjs +2 -0
- package/dist/graphql-CF7QKJME.mjs +68 -0
- package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
- package/dist/handlers--qCl9vNv.mjs +1 -0
- package/dist/handlers-BHIu1LqA.mjs +1 -0
- package/dist/{antidebug-7L3ygj_9.mjs → handlers-BQ4K8Jbr.mjs} +2 -2
- package/dist/handlers-BxQv-wtf.mjs +8 -0
- package/dist/handlers-ByYG27-5.mjs +1 -0
- package/dist/handlers-C0I9-BtX.mjs +5 -0
- package/dist/handlers-CL0Iokmw.mjs +1 -0
- package/dist/handlers-CNbhIdSK.mjs +4 -0
- package/dist/handlers-CnTTSJFs.mjs +109 -0
- package/dist/handlers-CoDx6akJ2.mjs +49 -0
- package/dist/{handlers-0yKLRIfo.mjs → handlers-DASJI0Pn.mjs} +1 -1
- package/dist/handlers-DRKMaA-_.mjs +74 -0
- package/dist/handlers-Dalu0olz.mjs +2 -0
- package/dist/handlers-KY0g31ny.mjs +9 -0
- package/dist/handlers-oGo60aVv.mjs +1 -0
- package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
- package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
- package/dist/{hooks-D4XLfgtV.mjs → hooks-COK3t5rT.mjs} +52 -33
- package/dist/index.mjs +11 -11
- package/dist/logger-BGCcd-jJ.mjs +1 -0
- package/dist/macro-nUYUjKNZ.mjs +2 -0
- package/dist/maintenance-CfnE7ZKU.mjs +4 -0
- package/dist/manifest-7EOTUc0D.mjs +1 -0
- package/dist/manifest-B5ujuQmf.mjs +1 -0
- package/dist/manifest-BErXl3zn.mjs +1 -0
- package/dist/manifest-BKA-mD3J.mjs +1 -0
- package/dist/manifest-BUXj23bX.mjs +1 -0
- package/dist/manifest-BfXt9cau.mjs +1 -0
- package/dist/manifest-Bx-tpURK.mjs +1 -0
- package/dist/manifest-C0owVAdq.mjs +1 -0
- package/dist/manifest-C5XqYc9o.mjs +1 -0
- package/dist/manifest-CVKzLjsA.mjs +1 -0
- package/dist/manifest-CaeFjdhj.mjs +1 -0
- package/dist/manifest-CegBgip0.mjs +1 -0
- package/dist/manifest-CoJHqlgS.mjs +1 -0
- package/dist/manifest-D0dbtDqd.mjs +1 -0
- package/dist/manifest-D5Gr8ujd.mjs +12 -0
- package/dist/manifest-D82z-5og.mjs +1 -0
- package/dist/manifest-DA2afIwh.mjs +1 -0
- package/dist/manifest-DAbiFP5o.mjs +1 -0
- package/dist/manifest-DEY0s1O72.mjs +1 -0
- package/dist/manifest-DTOqNqiA.mjs +1 -0
- package/dist/manifest-DZ6ELNgX.mjs +1 -0
- package/dist/manifest-DjHkjddT.mjs +1 -0
- package/dist/manifest-DocA_itf2.mjs +1 -0
- package/dist/manifest-Dpnhvfq0.mjs +1 -0
- package/dist/manifest-DucPMG_a.mjs +1 -0
- package/dist/manifest-Dw5yYEac.mjs +1 -0
- package/dist/manifest-Ic_Cg66S.mjs +1 -0
- package/dist/manifest-JHaG6GMN.mjs +1 -0
- package/dist/manifest-QdkIzmYM.mjs +1 -0
- package/dist/manifest-YZqaCe25.mjs +1 -0
- package/dist/manifest-f0lUeXwq.mjs +1 -0
- package/dist/manifest-h-Ebisf8.mjs +1 -0
- package/dist/manifest-oOfTymBS.mjs +1 -0
- package/dist/manifest-qXqrO6KC.mjs +2 -0
- package/dist/mapsParser-DrJoeC0c.mjs +1 -0
- package/dist/modules-CC_ADmwi.mjs +333 -0
- package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
- package/dist/native-D9ouskXO.mjs +961 -0
- package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
- package/dist/network-C5Y-S87J.mjs +7 -0
- package/dist/one-gadget-CiWFE17F.mjs +1 -0
- package/dist/outputPaths-CHtELDyi.mjs +1 -0
- package/dist/parse-args-B6dwWc9k.mjs +1 -0
- package/dist/platform-BIXgJaM3.mjs +94 -0
- package/dist/process-aDIfLC0v.mjs +6 -0
- package/dist/proxy-DsHsQ1I4.mjs +2 -0
- package/dist/registry-7h8jJ9y9.mjs +1 -0
- package/dist/{registry-DH4sc1dt.mjs → registry-DJDnkQW2.mjs} +1 -1
- package/dist/response-R8ghbZSb.mjs +1 -0
- package/dist/retry-policy-DtYv0kDi.mjs +1 -0
- package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
- package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
- package/dist/search-defaults-BBRJNAzC.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/server/search/EmbeddingWorker.d.mts +1 -0
- package/dist/server/search/EmbeddingWorker.mjs +1 -0
- package/dist/shared-BKtWZDGN.mjs +1 -0
- package/dist/sourcemap-2VIeVeKw.mjs +3 -0
- package/dist/streaming-DkpE3GGU.mjs +15 -0
- package/dist/syscall-DGZoYM_U.mjs +1 -0
- package/dist/transform-BJqsBC_-.mjs +105 -0
- package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
- package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
- package/dist/types-CWSvzmIh.mjs +1 -0
- package/dist/v8-inspector-CTJo08-K.mjs +297 -0
- package/dist/wasm-DX4Qm2Vs.mjs +235 -0
- package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
- package/dist/webgpu-D4-DxbxZ.mjs +6 -0
- package/dist/workflow-DHktRNF2.mjs +108 -0
- package/package.json +33 -27
- package/dist/AntiCheatDetector-B6d4Qe9D.mjs +0 -1
- package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
- package/dist/ConsoleMonitor-CxDJV15E.mjs +0 -306
- package/dist/DOMInspector-C19J4zeq.mjs +0 -95
- package/dist/DarwinAPI-ZfQdpLNI.mjs +0 -1
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
- package/dist/ExtensionManager-BD724zkO.mjs +0 -1
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +0 -1
- package/dist/FingerprintManager-DT0EAUEo.mjs +0 -1
- package/dist/HardwareBreakpoint-BUfPdp0f.mjs +0 -1
- package/dist/HeapAnalyzer-B_aqY8oj.mjs +0 -1
- package/dist/InstrumentationSession-D_G1ZPyd.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
- package/dist/MemoryController-X1XNSn1n.mjs +0 -2
- package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
- package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
- package/dist/PEAnalyzer-yWQaGrcx.mjs +0 -1
- package/dist/PageController-Dfsm1_o7.mjs +0 -1
- package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
- package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
- package/dist/ProcessRegistry-C-bN48oR.mjs +0 -1
- package/dist/ReverseEvidenceGraph-BhSYYdiI.mjs +0 -2
- package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
- package/dist/Speedhack-yseDPSZ9.mjs +0 -1
- package/dist/StructureAnalyzer-C5lpuZkg.mjs +0 -2
- package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
- package/dist/ToolRegistry-C5oB8KP8.mjs +0 -1
- package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
- package/dist/TraceRecorder-BiJWBXHX.mjs +0 -272
- package/dist/VersionDetector-CHT36Az0.mjs +0 -9
- package/dist/Win32API-eUCF57l_.mjs +0 -1
- package/dist/WorkflowEngine-D876meOO.mjs +0 -1
- package/dist/analysis-D4swdMvq.mjs +0 -6
- package/dist/apk-packer-BqXcInnX.mjs +0 -1
- package/dist/artifactRetention-BCPQASm7.mjs +0 -1
- package/dist/artifacts-CkodUM4j.mjs +0 -1
- package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
- package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
- package/dist/boringssl-inspector-BBaJwwkU.mjs +0 -2
- package/dist/browser-Qqco2rOT.mjs +0 -11
- package/dist/collector-Bpl6qy2L.mjs +0 -1
- package/dist/constants-BYj8Xek8.mjs +0 -1
- package/dist/coordination-CWXW1o8K.mjs +0 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/debugger-DyALjYMk.mjs +0 -1
- package/dist/definitions-BWxBke3r.mjs +0 -1
- package/dist/definitions-BYwATKc-.mjs +0 -1
- package/dist/definitions-B_83XfNQ.mjs +0 -1
- package/dist/definitions-Bf3H1EwV.mjs +0 -1
- package/dist/definitions-BftdXgXI.mjs +0 -1
- package/dist/definitions-Bio5XJYy.mjs +0 -1
- package/dist/definitions-C3qNgSn1.mjs +0 -1
- package/dist/definitions-CB6vmOer.mjs +0 -1
- package/dist/definitions-CMZRSy3k.mjs +0 -1
- package/dist/definitions-CQd7yCQH.mjs +0 -1
- package/dist/definitions-CT8ln6GQ.mjs +0 -1
- package/dist/definitions-D4g-MS10.mjs +0 -1
- package/dist/definitions-D5wl_8HN.mjs +0 -1
- package/dist/definitions-DAQm1Xar.mjs +0 -1
- package/dist/definitions-DP1vgxEY.mjs +0 -1
- package/dist/definitions-Ibci7e_L.mjs +0 -1
- package/dist/definitions-OeLvmlQy.mjs +0 -1
- package/dist/definitions-RZYGD_Ey.mjs +0 -1
- package/dist/definitions-Tls8c0A0.mjs +0 -1
- package/dist/definitions-bybDvnG0.mjs +0 -26
- package/dist/definitions-l7TjdE6V.mjs +0 -1
- package/dist/encoding-ycOaz8Vr.mjs +0 -2
- package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
- package/dist/factory-CKr4fAE1.mjs +0 -1
- package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
- package/dist/graphql-B2TiPEow.mjs +0 -62
- package/dist/handlers-8zN_vBIz.mjs +0 -1
- package/dist/handlers-B62K4FTc.mjs +0 -1
- package/dist/handlers-BpDlVVVU.mjs +0 -1
- package/dist/handlers-CMJK7m1c.mjs +0 -31
- package/dist/handlers-D2ZOul9p.mjs +0 -54
- package/dist/handlers-D5E40ssn.mjs +0 -5
- package/dist/handlers-DGbdQAgD.mjs +0 -4
- package/dist/handlers-DHO3rjsW.mjs +0 -1
- package/dist/handlers-FJ80VzUI.mjs +0 -2
- package/dist/handlers-VHWrxbM_.mjs +0 -1
- package/dist/handlers-l8QIKqBj.mjs +0 -2
- package/dist/handlers.impl-D9Hh8Bgl.mjs +0 -1
- package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
- package/dist/logger-sBC6IdRT.mjs +0 -1
- package/dist/maintenance-BUpIukhg.mjs +0 -1
- package/dist/manifest-0Jpt_AQa.mjs +0 -1
- package/dist/manifest-B3fZbSWR.mjs +0 -1
- package/dist/manifest-B7NB2rh2.mjs +0 -1
- package/dist/manifest-BDi4nbH1.mjs +0 -1
- package/dist/manifest-BLDfkE7n.mjs +0 -1
- package/dist/manifest-BcXbB4gf.mjs +0 -1
- package/dist/manifest-Bdnc_vrc.mjs +0 -1
- package/dist/manifest-BuYKgCnp.mjs +0 -1
- package/dist/manifest-CBfNnGPV.mjs +0 -1
- package/dist/manifest-CPS1Xv69.mjs +0 -1
- package/dist/manifest-CQH9FhwI.mjs +0 -1
- package/dist/manifest-CRryuZF4.mjs +0 -1
- package/dist/manifest-CctIumog.mjs +0 -1
- package/dist/manifest-CvTe5ZGV2.mjs +0 -1
- package/dist/manifest-D-5GH0DV.mjs +0 -1
- package/dist/manifest-D3Ssf3IC.mjs +0 -1
- package/dist/manifest-D5ck3NvC.mjs +0 -1
- package/dist/manifest-D9jUUJAu.mjs +0 -1
- package/dist/manifest-DCx6w2XV.mjs +0 -1
- package/dist/manifest-DG19q-Ld.mjs +0 -1
- package/dist/manifest-DLMlD0Zc.mjs +0 -1
- package/dist/manifest-DYpn8w_h.mjs +0 -1
- package/dist/manifest-DYzWI8Xs.mjs +0 -1
- package/dist/manifest-D_obs5F4.mjs +0 -1
- package/dist/manifest-DujQqEQR.mjs +0 -2
- package/dist/manifest-DwL2ik8P.mjs +0 -1
- package/dist/manifest-ItF5P8A12.mjs +0 -1
- package/dist/manifest-KZphqIyX.mjs +0 -1
- package/dist/manifest-LG42zPLY2.mjs +0 -1
- package/dist/manifest-LLdI5m4T.mjs +0 -1
- package/dist/manifest-QYbQXJn0.mjs +0 -1
- package/dist/manifest-RcpX_MyZ.mjs +0 -123
- package/dist/manifest-YgVd8Sgz.mjs +0 -1
- package/dist/manifest-Zy7Odg5J.mjs +0 -1
- package/dist/manifest-ff1H7Pdp.mjs +0 -1
- package/dist/manifest-iuhF6pTL2.mjs +0 -1
- package/dist/manifest-nXHmtMSp2.mjs +0 -1
- package/dist/manifest-xWfu6iLo.mjs +0 -1
- package/dist/manifest-yC16OhL2.mjs +0 -1
- package/dist/manifest-ztWJoXy4.mjs +0 -1
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
- package/dist/modules-BPBcSaM-.mjs +0 -333
- package/dist/mojo-ipc-BhwsdVUW.mjs +0 -9
- package/dist/native-j8l473zn.mjs +0 -961
- package/dist/network-T0VRwNPd.mjs +0 -7
- package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
- package/dist/parse-args-Bw413PlW.mjs +0 -1
- package/dist/platform-CzaQtISh.mjs +0 -93
- package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
- package/dist/process-CWhsCWrf.mjs +0 -2
- package/dist/proxy-DZFlDsG3.mjs +0 -2
- package/dist/renderer-pid-9tJnZ_9N.mjs +0 -1
- package/dist/response-C7rKQst4.mjs +0 -1
- package/dist/search-defaults-lYBVn_3L.mjs +0 -1
- package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
- package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
- package/dist/streaming-BcJ0B6ao.mjs +0 -1
- package/dist/transform-DOxzeWPB.mjs +0 -103
- package/dist/types-D9EiE5o9.mjs +0 -1
- package/dist/wasm-CZ_HTfKR.mjs +0 -174
- package/dist/webcrack-C1iYG_EX.mjs +0 -46
- package/dist/workflow-BdwQmARn.mjs +0 -101
- /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
- /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
- /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
- /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
- /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
- /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
- /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
- /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
- /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
- /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
- /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
- /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import{t as e}from"./logger-BGCcd-jJ.mjs";import{Dt as t,Et as n,Ot as r,_t as i,b as a,gt as o,v as s,y as c}from"./constants-nvsLpSri.mjs";import{n as l,r as u}from"./response-R8ghbZSb.mjs";import{d}from"./ensure-browser-core-BP70x0TB.mjs";import"./JScramblerDeobfuscator-NVR5VatT.mjs";import"./PackerDeobfuscator-BpwGjxDL.mjs";import"./VMDeobfuscator-BHtkV850.mjs";import{c as f,i as p,l as m,n as h,r as g,s as _,t as v,u as y}from"./parse-args-B6dwWc9k.mjs";import{r as b}from"./ResponseBuilder-BLicSCjn.mjs";import"./definitions-BXE3H4re.mjs";import{i as x,n as S,r as ee,t as te}from"./CodeAnalyzerDataFlow-a-NkwcaG.mjs";import{a as C,i as w,n as T,r as E}from"./ast-utils-B9E5k_v1.mjs";import{i as ne,n as re,r as ie,t as D}from"./ast-bridge-BlOrmVAv.mjs";import*as O from"@babel/parser";import k from"@babel/traverse";import ae from"@babel/generator";import*as A from"@babel/types";function oe(t){e.info(`Derotating string array...`);try{let n=O.parse(t,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=0;return k(n,{CallExpression(t){if(!A.isFunctionExpression(t.node.callee)&&!A.isArrowFunctionExpression(t.node.callee))return;let n=t.node.callee;if(!A.isFunctionExpression(n)||!A.isBlockStatement(n.body))return;let i=n.body.body.some(e=>A.isWhileStatement(e)),a=JSON.stringify(n.body).includes(`push`)&&JSON.stringify(n.body).includes(`shift`);i&&a&&(e.debug(`Found string array rotation IIFE`),t.remove(),r++)}}),r>0?(e.info(`Removed ${r} string array rotation functions`),ae(n,{comments:!0,compact:!1}).code):t}catch(n){return e.error(`Failed to derotate string array:`,n),t}}function j(t,n){let r=t.code;return typeof r!=`string`||r.trim().length===0?(e.warn(`${n} called without valid code argument`),null):r}function M(e){let t={},n=h(e,`unpack`),r=h(e,`unminify`),i=h(e,`jsx`),a=h(e,`mangle`),o=h(e,`forceOutput`),s=h(e,`includeModuleCode`),c=f(e,`outputDir`),l=p(e,`maxBundleModules`);return n!==void 0&&(t.unpack=n),r!==void 0&&(t.unminify=r),i!==void 0&&(t.jsx=i),a!==void 0&&(t.mangle=a),o!==void 0&&(t.forceOutput=o),s!==void 0&&(t.includeModuleCode=s),c?.trim()&&(t.outputDir=c),l!==void 0&&(t.maxBundleModules=l),Array.isArray(e.mappings)&&(t.mappings=e.mappings.filter(e=>typeof e==`object`&&!!e&&typeof e.path==`string`&&typeof e.pattern==`string`)),t}async function se(e,t,n,r,i,a){let o=j(e,`deobfuscate`);if(!o)return l({success:!1,error:`code is required and must be a non-empty string`});let s=g(e,`engine`,new Set([`auto`,`webcrack`,`jscrambler`,`packer`,`vm`]),`auto`);if(s===`jscrambler`)return l(await r.deobfuscate({code:o}));if(s===`packer`)return l(await i.deobfuscate(o));if(s===`vm`){let e=a.detectVMProtection(o);return e.detected?l({...await a.deobfuscateVM(o,{type:e.type,instructionCount:e.instructionCount}),detection:e}):l({success:!1,error:`No VM protection detected in the provided code`,detection:e})}if(s===`webcrack`)return l(await n.deobfuscate({code:o,...M(e),...typeof e.detectOnly==`boolean`?{detectOnly:e.detectOnly}:{}}));let c=await t.deobfuscate({code:o,...M(e)});return c&&typeof c==`object`&&`success`in c&&c.success===!1&&!(`error`in c)?l({...c,error:c.reason||`deobfuscation failed`}):l(c)}async function ce(e){let t=j(e,`webcrack_unpack`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=await x(t,{unpack:h(e,`unpack`,!0),unminify:h(e,`unminify`,!0),jsx:h(e,`jsx`,!0),mangle:h(e,`mangle`,!1),...M(e)});return n.applied?l({success:!0,code:n.code,bundle:n.bundle,savedTo:n.savedTo,savedArtifacts:n.savedArtifacts,optionsUsed:n.optionsUsed,engine:`webcrack`}):l({success:!1,error:n.reason||`webcrack execution failed`,optionsUsed:n.optionsUsed,engine:`webcrack`})}async function le(e){let t=f(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=p(e,`maxReplacements`,200),r=h(e,`removeRotation`,!0),i=r?oe(t):t,a=new Map,o;try{o=E(i,{plugins:[`jsx`,`typescript`]})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}C(o,{VariableDeclarator(e){if(!e.isVariableDeclarator())return;let t=e.node;if(!w.isIdentifier(t.id)||!w.isArrayExpression(t.init))return;let n=[];for(let e of t.init.elements){if(!w.isStringLiteral(e))return;n.push(e.value)}a.set(t.id.name,n)}});let s=[],c=0;return C(o,{CallExpression(e){if(c>=n){e.stop();return}if(!e.isCallExpression())return;let r=e.node;if(!w.isIdentifier(r.callee))return;let i=r.callee.name,o=a.get(i);if(!o||r.arguments.length!==1)return;let l=r.arguments[0];if(!w.isNumericLiteral(l)&&!w.isStringLiteral(l))return;let u=w.isNumericLiteral(l)?l.value:l.value.startsWith(`0x`)?Number.parseInt(l.value,16):Number(l.value);if(!Number.isInteger(u)||u<0||u>=o.length)return;let d=o[u];if(typeof d!=`string`)return;let f=t.slice(r.start??0,r.end??0);s.push({arrayName:i,index:u,value:d,original:f}),e.replaceWith(w.stringLiteral(d)),c+=1}}),l({success:!0,code:T(o,{retainLines:!0}),replacedCount:c,arraysFound:a.size,rotationRemoved:r&&i!==t,replacements:s})}const ue=[{type:`for-switch`,test:/for.*switch/s},{type:`while-switch`,test:/while.*switch/s},{type:`if-else-chain`,test:/if\s*\(\s*\w+\s*===?\s*\w+/}];function de(e){for(let t of ue)if(t.test.test(e))return t.type;return`switch`}function N(e){let t=new Map;for(let n of e){let e=n.type||`unknown`;t.set(e,(t.get(e)||0)+1)}return Object.fromEntries(t)}function P(e){let{code:t,extractBytecode:n,mapOpcodes:r,vmResult:i}=e;if(!i.isJSVMP)return{success:!0,isVM:!1,message:`No VM/JSVMP patterns detected.`};let a={isVM:!0,vmType:i.vmType,dispatchType:de(t),complexity:i.vmFeatures?.complexity,instructionCount:i.vmFeatures?.instructionCount,interpreterLocation:i.vmFeatures?.interpreterLocation};return n&&i.instructions&&(a.bytecode=i.instructions),r&&i.instructions&&(a.opcodeDistribution=N(i.instructions),a.suggestedStrategy=i.vmFeatures?.complexity===`high`?`Use js_symbolic_execute_jsvmp with these instructions for high-complexity VMs`:`Use standard deobfuscation pipeline (js_deobfuscate_pipeline)`),{success:!0,analysis:a}}function F(e,t){let n=e.code;return typeof n!=`string`||n.trim().length===0?null:n}async function I(e,t){let n=F(e,`js_deobfuscate_jsvmp`);if(!n)return l({success:!1,error:`code is required and must be a non-empty string`});let r=h(e,`detectOnly`,!1),i=await t.deobfuscate({code:n,aggressive:h(e,`aggressive`,!1),extractInstructions:h(e,`extractInstructions`,!0),timeout:p(e,`timeout`,3e4)});return l(r?{success:!0,isJSVMP:i.isJSVMP,vmType:i.vmType,vmFeatures:i.vmFeatures,confidence:i.confidence,instructionCount:i.instructions?.length}:{success:i.isJSVMP,isJSVMP:i.isJSVMP,vmType:i.vmType,vmFeatures:i.vmFeatures,instructions:i.instructions,deobfuscatedCode:i.deobfuscatedCode,confidence:i.confidence,warnings:i.warnings,unresolvedParts:i.unresolvedParts,stats:i.stats})}async function L(e,t){let n=F(e,`js_analyze_vm`);if(!n)return l({success:!1,error:`code is required`});let r=h(e,`extractBytecode`,!0);return l(P({code:n,extractBytecode:r,mapOpcodes:h(e,`mapOpcodes`,!0),vmResult:await t.deobfuscate({code:n,aggressive:!1,extractInstructions:r,timeout:15e3})}))}const R=new Set([`call`,`apply`]);async function z(e){let t=f(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=f(e,`nodeType`);if(!n)return l({success:!1,error:`nodeType is required`});let r=p(e,`maxResults`,50),i=f(e,`filter`),a;if(i)try{a=JSON.parse(i)}catch{return l({success:!1,error:`filter must be valid JSON`})}let o;try{o=E(t,{plugins:[`jsx`,`typescript`]})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let s=[],c=n;function u(e){if(!a)return!0;for(let[t,n]of Object.entries(a)){let r=t.split(`.`),i=e;for(let e of r){if(typeof i!=`object`||!i)return!1;i=i[e]}if(String(i)!==String(n))return!1}return!0}function d(e){let t={};for(let n of Object.keys(e)){if(n===`type`||n===`start`||n===`end`||n===`loc`||n===`range`)continue;let r=e[n];r==null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t[n]=r:Array.isArray(r)&&r.length<=5?t[n]=r.map(e=>typeof e==`object`&&e&&`type`in e?{type:e.type}:e):typeof r==`object`&&r&&`type`in r&&(t[n]={type:r.type})}return t}return C(o,{enter(e){let n=e.node;n.type===c&&u(n)&&(s.push({type:n.type,start:n.start??-1,end:n.end??-1,code:t.slice(n.start??0,n.end??0),properties:d(n)}),s.length>=r&&e.stop())}}),l({success:!0,matches:s,total:s.length,nodeType:n})}async function B(e){let t=f(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n;try{n=E(t,{sourceType:`unambiguous`})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let r=h(e,`removeDispatcher`,!0),i=V(t);if(i.code!==t)try{n=E(i.code,{sourceType:`unambiguous`})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let a=0,o=new Set;return C(n,{WhileStatement:e=>{if(!e.isWhileStatement())return;let t=e.node,n=t.test;if(n.type!==`BooleanLiteral`||n.value!==!0)return;let r=t.body;if(r.type!==`BlockStatement`)return;let i=r.body.find(e=>e.type===`SwitchStatement`);if(!i)return;let s=i.discriminant;if(s.type!==`MemberExpression`||!s.computed)return;let c=s.object;if(c.type!==`Identifier`)return;let l=c.name,u,d=s.property;if(d.type===`Identifier`?u=d.name:d.type===`UpdateExpression`&&d.argument.type===`Identifier`&&(u=d.argument.name),!u)return;let f=i.cases;if(f.length===0)return;let p=new Map;for(let e of f)!e.test||e.test.type!==`StringLiteral`||p.set(e.test.value,e.consequent);let m=e.scope.getBinding(l),h=e.scope.getBinding(u);if(!m||!h)return;let g=H(e,l);if(!g)return;let _=[];if(g.type===`ArrayExpression`)for(let e of g.elements)e&&e.type===`StringLiteral`&&_.push(e.value);else if(g.type===`CallExpression`&&g.callee.type===`MemberExpression`&&g.callee.property.type===`Identifier`&&g.callee.property.name===`split`&&g.arguments[0]?.type===`StringLiteral`){let e=g.arguments[0].value,t=g.callee.object;t.type===`StringLiteral`&&_.push(...t.value.split(e))}if(_.length===0)return;let v=[];for(let e of _){let t=p.get(e);if(t)for(let e of t)e.type!==`BreakStatement`&&e.type!==`ContinueStatement`&&v.push(e)}e.replaceWith(w.blockStatement(v)),o.add(m.identifier),o.add(h.identifier),a++}}),r&&o.size>0&&C(n,{VariableDeclarator(e){if(!e.isVariableDeclarator())return;let t=e.node;if(t.id.type===`Identifier`&&o.has(t.id)){let t=e.parent;if(t.type===`VariableDeclaration`&&t.declarations.length===1){let t=e.parentPath;t&&t.remove()}else e.remove()}}}),l({success:!0,code:T(n,{retainLines:!0}),flattenedCount:a,dispatchersRemoved:r?o.size:0,helperTransforms:i.transforms})}function V(e){let t=e,n=[];return t=t.replace(/(\b[a-zA-Z_$][\w$]*)\[['"]([a-zA-Z_$][\w$]*)['"]\]\(([^)]*)\)/g,(e,t,r,i)=>R.has(r)?(n.push(`helper-member-call`),`${t}.${r}(${i})`):e),{code:t,transforms:n}}function H(e,t){let n=e.scope.getBinding(t);if(!n?.path.isVariableDeclarator())return null;let r=n.path.node.init;if(r)return r;let i=n.path.parentPath;if(!i.isVariableDeclaration())return null;let a=i.getAllNextSiblings();for(let e of a){if(!e.isExpressionStatement())continue;let n=e.node.expression;if(!(!w.isAssignmentExpression(n)||n.operator!==`=`||!w.isIdentifier(n.left,{name:t})))return n.right}return null}var U=class{symbolCounter=0;pathCounter=0;async execute(i){let a=Date.now(),{code:o,maxPaths:s=t,maxDepth:c=n,timeout:l=r,enableConstraintSolving:u=!1}=i;e.info(` ...`);let d=[],f=[],p=[],m=[];try{let t=O.parse(o,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),n=[{state:{pc:0,stack:[],registers:new Map,memory:new Map,pathConstraints:[]},depth:0}];for(;n.length>0&&d.length<s;){if(Date.now()-a>l){m.push(`Symbolic execution timed out`);break}let{state:e,depth:r}=n.pop();if(r>=c){m.push(`Max depth reached: ${c}`);continue}let i=this.executeStep(e,t);for(let e of i)if(this.isTerminalState(e)){let t=this.createPath(e);d.push(t),this.collectSymbolicValues(e,f),this.collectConstraints(e,p)}else n.push({state:e,depth:r+1})}u&&await this.solveConstraints(d,m);let r=this.calculateCoverage(d,t),i=Date.now()-a;return e.info(`Symbolic execution complete in ${i}ms`),e.info(` : ${d.length}`),e.info(` : ${(r*100).toFixed(1)}%`),{paths:d,coverage:r,symbolicValues:f,constraints:p,warnings:m,stats:{totalPaths:d.length,feasiblePaths:d.filter(e=>e.isFeasible).length,infeasiblePaths:d.filter(e=>!e.isFeasible).length,executionTime:i}}}catch(t){throw e.error(``,t),t}}executeStep(e,t){let n=[],r=null,i=0;if(k(t,{enter(t){i===e.pc&&(r=t.node,t.stop()),i++}}),!r)return[];if(A.isVariableDeclaration(r)){let t=this.cloneState(e);r.declarations.forEach(e=>{if(A.isIdentifier(e.id)){let n=e.id.name,r=this.createSymbolicValue(`unknown`,n,n);t.memory.set(n,r)}}),t.pc++,n.push(t)}else if(A.isIfStatement(r)){let t=this.cloneState(e),i=this.cloneState(e),a=r,o=this.nodeToString(a.test);t.pathConstraints.push({type:`custom`,expression:o,description:``}),i.pathConstraints.push({type:`custom`,expression:`!(${o})`,description:``}),t.pc++,i.pc++,n.push(t,i)}else if(A.isWhileStatement(r)||A.isForStatement(r)){let t=this.cloneState(e),r=this.cloneState(e);t.pc++,r.pc+=2,n.push(t,r)}else if(A.isAssignmentExpression(r)){let t=this.cloneState(e),i=r;if(A.isIdentifier(i.left)){let e=i.left.name,n=this.nodeToString(i.right),r=this.createSymbolicValue(`unknown`,n,n);t.memory.set(e,r)}t.pc++,n.push(t)}else{let t=this.cloneState(e);t.pc++,n.push(t)}return n}nodeToString(e){return A.isIdentifier(e)?e.name:A.isNumericLiteral(e)?String(e.value):A.isStringLiteral(e)?`"${e.value}"`:A.isBinaryExpression(e)?`${this.nodeToString(e.left)} ${e.operator} ${this.nodeToString(e.right)}`:A.isUnaryExpression(e)?`${e.operator}${this.nodeToString(e.argument)}`:`[Complex Expression]`}isTerminalState(e){return e.pc>1e3||e.pathConstraints.length>50||e.stack.length===0&&e.memory.size===0}createPath(e){let t=`path-${this.pathCounter++}`,n=this.calculatePathCoverage(e);return{id:t,states:[e],constraints:[...e.pathConstraints],isFeasible:this.checkPathFeasibility(e.pathConstraints),coverage:n}}calculatePathCoverage(e){return Math.min(e.pc/100,1)}checkPathFeasibility(e){let t=new Set;for(let n of e){let e=n.expression;if(t.has(`!(${e})`))return!1;t.add(e)}return!0}collectSymbolicValues(e,t){let n=new Set;for(let r of e.stack)n.has(r.id)||(t.push(r),n.add(r.id));for(let r of e.registers.values())n.has(r.id)||(t.push(r),n.add(r.id));for(let r of e.memory.values())n.has(r.id)||(t.push(r),n.add(r.id))}collectConstraints(e,t){let n=new Set;for(let r of e.pathConstraints){let e=`${r.type}:${r.expression}`;n.has(e)||(t.push(r),n.add(e))}let r=[...e.stack,...Array.from(e.registers.values()),...Array.from(e.memory.values())];for(let e of r)for(let r of e.constraints){let e=`${r.type}:${r.expression}`;n.has(e)||(t.push(r),n.add(e))}}async solveConstraints(t,n){e.info(` ...`),await this.solveConstraintsZ3(t,n)||this.solveConstraintsLegacy(t,n),e.info(`Path analysis complete, feasible paths: ${t.filter(e=>e.isFeasible).length}/${t.length}`)}async solveConstraintsZ3(t,n){if(ie())return!1;let r=!1;return!(await ne(async i=>{let a=new i.Context(`main`),{Solver:o,And:s}=a;for(let r of t){if(r.constraints.length===0){r.isFeasible=!0;continue}try{let e=new o;e.set(`timeout`,5e3);let t=[];for(let e of r.constraints){let n=W(e.expression),r=re(e.expression,i,a,n.map(e=>({name:e,type:`int`})));t.push(r)}let c;c=t.length===1?t[0]:s(...t),e.add(c);let l=await e.check();if(l===`unsat`)r.isFeasible=!1,n.push(` ${r.id} UNSAT (Z3)`);else if(l===`sat`){r.isFeasible=!0;try{let t=e.model();if(t){let e=new Set;for(let t of r.constraints)for(let n of W(t.expression))e.add(n);for(let i of e){let e=a.Int.const(i),o=t.eval(e);if(o){let e=(o.ast,String(o));n.push(` ${r.id}: ${i} = ${e}`)}}}}catch{}}else r.isFeasible=this.simpleSMTSolver(r.constraints).satisfiable}catch(t){t instanceof D?(r.isFeasible=this.simpleSMTSolver(r.constraints).satisfiable,n.push(` ${r.id} ${t.nodeType}: ${t.message} (fell back to regex)`)):(e.warn(`[symbolic] Z3 path analysis failed for ${r.id}:`,t),r.isFeasible=this.simpleSMTSolver(r.constraints).satisfiable)}}return r=!0,!0})===null||!r)}solveConstraintsLegacy(e,t){for(let n of e){if(n.constraints.length===0){n.isFeasible=!0;continue}let e=this.simpleSMTSolver(n.constraints);e.satisfiable?n.isFeasible=!0:(n.isFeasible=!1,t.push(` ${n.id} (legacy regex): ${e.reason}`))}}simpleSMTSolver(e){let t=e.filter(e=>e.type===`range`||e.type===`inequality`);for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let r=t[e],i=t[n];if(!(!r||!i)&&this.areContradictory(r.expression,i.expression))return{satisfiable:!1,reason:`: ${r.expression} ${i.expression}`}}return{satisfiable:!0}}areContradictory(e,t){let n=/(\w+)\s*>\s*(\d+)/,r=/(\w+)\s*<\s*(\d+)/,i=e.match(n),a=t.match(r);return i&&a&&i[1]===a[1]&&i[2]&&a[2]?parseInt(i[2],10)>=parseInt(a[2],10):!1}calculateCoverage(e,t){let n=0;if(k(t,{Statement(){n++}}),n===0)return 0;let r=new Set;for(let t of e)for(let e of t.states)r.add(e.pc);return r.size/n}cloneState(e){return{pc:e.pc,stack:[...e.stack],registers:new Map(e.registers),memory:new Map(e.memory),pathConstraints:[...e.pathConstraints]}}createSymbolicValue(e,t,n){return{id:`sym-${this.symbolCounter++}`,type:e,name:t,constraints:[],source:n}}addConstraint(e,t,n,r){e.constraints.push({type:t,expression:n,description:r})}};function W(e){let t=new Set,n=e.matchAll(/[a-zA-Z_][a-zA-Z0-9_]*/g),r=new Set([`true`,`false`,`null`,`undefined`,`void`,`typeof`,`NaN`,`Infinity`,`if`,`else`,`while`,`for`,`switch`,`case`,`break`,`continue`,`return`,`new`,`function`]);for(let e of n){let n=e[0];r.has(n)||t.add(n)}return[...t]}var fe=class extends U{async executeJSVMP(t){let n=Date.now(),{instructions:r,vmType:a=`custom`,maxSteps:s=o,timeout:c=i}=t;e.info(` JSVMP...`),e.info(` : ${r.length}`),e.info(`VM type detected: ${a}`);let l=[],u=[];try{let t={pc:0,stack:[],registers:new Map,memory:new Map,pathConstraints:[]},i=0;for(;t.pc<r.length&&i<s;){if(Date.now()-n>c){l.push(`JSVMP`);break}let e=r[t.pc];if(!e){l.push(`: PC=${t.pc}`);break}if(u.push(this.cloneStateInternal(t)),t=this.executeInstruction(t,e,r),e.opcode===255)break;i++}let a=this.inferLogic(u,r),o=this.collectAllConstraints(u),d=this.calculateConfidence(u,r),f=Date.now()-n;return e.info(`JSVMP symbolic execution complete in ${f}ms`),e.info(` : ${i}`),e.info(` : ${(d*100).toFixed(1)}%`),{finalState:t,executionTrace:u,inferredLogic:a,constraints:o,confidence:d,warnings:l}}catch(t){throw e.error(`JSVMP`,t),t}}executeInstruction(t,n,r){let i=this.cloneStateInternal(t);switch(n.opcode){case 1:this.executePush(i,n.operands[0]);break;case 2:this.executePop(i);break;case 16:this.executeAdd(i);break;case 17:this.executeSub(i);break;case 18:this.executeMul(i);break;case 19:this.executeDiv(i);break;case 20:this.executeMod(i);break;case 32:this.executeAnd(i);break;case 33:this.executeOr(i);break;case 34:this.executeNot(i);break;case 35:this.executeXor(i);break;case 48:this.executeEq(i);break;case 49:this.executeNe(i);break;case 50:this.executeLt(i);break;case 51:this.executeLe(i);break;case 52:this.executeGt(i);break;case 53:this.executeGe(i);break;case 66:return this.executeJnz(i,this.asNumberOperand(n.operands[0])),i;case 68:return i.pc=r.length,i;case 3:this.executeDup(i);break;case 82:return this.executePush(i,n.operands[0]),i.pc++,i;case 80:this.executeLoad(i,this.asStringOperand(n.operands[0]));break;case 81:this.executeStore(i,this.asStringOperand(n.operands[0]));break;case 64:return i.pc=this.asNumberOperand(n.operands[0]),i;case 65:return this.executeJZ(i,this.asNumberOperand(n.operands[0])),i;case 67:this.executeCall(i,this.asStringOperand(n.operands[0]));break;default:e.warn(`: 0x${n.opcode.toString(16)}`)}return i.pc++,i}executePush(e,t){let n=this.createSymbolicValue(`unknown`,`const_${t}`,String(t));n.possibleValues=[t],e.stack.push(n)}asNumberOperand(e){return e}asStringOperand(e){return e}executePop(e){return e.stack.pop()}executeAdd(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} + ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} + ${t.name}`,``),e.stack.push(r)}}executeSub(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} - ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} - ${t.name}`,``),e.stack.push(r)}}executeMul(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} * ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} * ${t.name}`,``),e.stack.push(r)}}executeDiv(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} / ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} / ${t.name}`,``),e.stack.push(r)}}executeMod(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} % ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} % ${t.name}`,``),e.stack.push(r)}}executeAnd(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} && ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} && ${t.name}`,``),e.stack.push(r)}}executeOr(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} || ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} || ${t.name}`,``),e.stack.push(r)}}executeNot(e){let t=e.stack.pop();if(t){let n=this.createSymbolicValue(`boolean`,`!${t.name}`);this.addConstraint(n,`custom`,`${n.name} = !${t.name}`,``),e.stack.push(n)}}executeXor(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} ^ ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} ^ ${t.name}`,``),e.stack.push(r)}}executeEq(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} === ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} === ${t.name}`,``),e.stack.push(r)}}executeNe(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} !== ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} !== ${t.name}`,``),e.stack.push(r)}}executeLt(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} < ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} < ${t.name}`,``),e.stack.push(r)}}executeLe(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} <= ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} <= ${t.name}`,``),e.stack.push(r)}}executeGt(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} > ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} > ${t.name}`,``),e.stack.push(r)}}executeGe(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} >= ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} >= ${t.name}`,``),e.stack.push(r)}}executeJnz(e,t){let n=e.stack.pop();if(n){let r={type:`inequality`,expression:`${n.name} != 0`,description:``};e.pathConstraints.push(r),e.pc=t}}executeDup(e){let t=e.stack[e.stack.length-1];if(t){let n=this.createSymbolicValue(t.type,t.name,t.source);n.constraints=[...t.constraints],t.possibleValues&&(n.possibleValues=[...t.possibleValues]),e.stack.push(n)}}executeLoad(e,t){let n=e.memory.get(t);if(n)e.stack.push(n);else{let n=this.createSymbolicValue(`unknown`,t,t);e.stack.push(n)}}executeStore(e,t){let n=e.stack.pop();n&&e.memory.set(t,n)}executeJZ(e,t){let n=e.stack.pop();if(n){let r={type:`equality`,expression:`${n.name} == 0`,description:``};e.pathConstraints.push(r),e.pc=t}}executeCall(t,n){e.info(` : ${n}`)}inferLogic(e,t){let n=[];for(let r=0;r<Math.min(e.length,10);r++){let i=e[r];if(!i)continue;let a=t[i.pc];a&&n.push(`${a.opcode}(${a.operands.join(`, `)}) at ${a.location}`)}return n.join(`
|
|
2
|
+
`)||``}collectAllConstraints(e){let t=[];for(let n of e){t.push(...n.pathConstraints);for(let e of n.stack)t.push(...e.constraints)}return t}calculateConfidence(e,t){let n=e.length/t.length;return Math.min(n,1)}cloneStateInternal(e){return{pc:e.pc,stack:[...e.stack],registers:new Map(e.registers),memory:new Map(e.memory),pathConstraints:[...e.pathConstraints]}}};async function pe(e){let t=y(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=p(e,`maxPaths`),r=p(e,`maxDepth`),i=p(e,`timeout`),a=h(e,`enableConstraintSolving`,!1);return b(async()=>await new U().execute({code:t,...n===void 0?{}:{maxPaths:n},...r===void 0?{}:{maxDepth:r},...i===void 0?{}:{timeout:i},enableConstraintSolving:a}))}async function me(e){let t=v(e,`instructions`);if(!t)return l({success:!1,error:`instructions array is required (from js_analyze_vm output)`});let n=f(e,`vmType`),r=p(e,`maxSteps`),i=p(e,`timeout`);return b(async()=>await new fe().executeJSVMP({instructions:t,...n?{vmType:n}:{},...r===void 0?{}:{maxSteps:r},...i===void 0?{}:{timeout:i}}))}const he=new Set([`structure`,`business`,`security`,`all`]);function G(e,t){let n=e.code;return typeof n!=`string`||n.trim().length===0?null:n}async function ge(e,t){let n=G(e,`understand_code`);return l(n?await t.understand({code:n,context:_(e,`context`),focus:g(e,`focus`,he,`all`)}):{success:!1,error:`code is required and must be a non-empty string`})}async function _e(e,t){let n=G(e,`detect_crypto`);return l(n?await t.detect({code:n}):{success:!1,error:`code is required and must be a non-empty string`})}async function ve(e,t){let n=G(e,`detect_obfuscation`);if(!n)return l({success:!1,error:`code is required and must be a non-empty string`});let r=h(e,`generateReport`,!0),i=t.detect(n);if(!r)return l(i);let a=t.generateReport(i);return u(`${JSON.stringify(i,null,2)}\n\n${a}`)}const ye=new Set([`=`,`(`,`[`,`,`,`;`,`{`,`!`,`&`,`|`,`?`,`:`,`~`,`^`,`+`,`-`,`*`,`%`,`<`,`>`,`
|
|
3
|
+
`]);function K(e){return new RegExp(e.source,e.flags)}function be(e){if(e.length===0)return[];let t=[],n=e.toSorted((e,t)=>e.start-t.start||e.end-t.end);for(let e of n){let n=t[t.length-1];if(!n||e.start>n.end){t.push({...e});continue}n.end=Math.max(n.end,e.end)}return t}function xe(e){try{let t=O.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),n=[],r=(e,t)=>{typeof e==`number`&&typeof t==`number`&&t>e&&n.push({start:e,end:t})},i=Array.isArray(t.comments)?t.comments:[];for(let e of i)r(e.start,e.end);return k(t,{StringLiteral(e){r(e.node.start,e.node.end),e.skip()},TemplateElement(e){r(e.node.start,e.node.end),e.skip()},RegExpLiteral(e){r(e.node.start,e.node.end),e.skip()}}),be(n)}catch{return null}}function Se(e){let t=e[e.length-2];if(typeof t==`number`)return t;let n=e[e.length-3];return typeof n==`number`?n:null}function Ce(e,t){let n=t-1;for(;n>=0&&(e[n]===` `||e[n]===` `||e[n]===`\r`);)n--;if(n<0)return!0;let r=e[n];if(ye.has(r))return!0;if(r!==`)`)return!1;let i=1,a=n-1;for(;a>=0&&i>0;)e[a]===`)`&&i++,e[a]===`(`&&i--,a--;for(a--;a>=0&&(e[a]===` `||e[a]===` `);)a--;let o=``;for(;a>=0&&/[a-z]/.test(e[a]);)o=e[a]+o,a--;return[`if`,`while`,`for`,`switch`,`return`,`typeof`,`void`,`in`,`of`,`case`].includes(o)}function we(e,t){let n=null,r=!1,i=!1,a=!1;for(let o=0;o<t;o++){let s=e[o];if(r){s===`*`&&e[o+1]===`/`&&(r=!1,o++);continue}if(i){s===`
|
|
4
|
+
`&&(i=!1);continue}if(a){if(s===`\\`){o++;continue}if(s===`/`){for(a=!1,o++;o<t&&/[gimsuy]/.test(e[o]);)o++;continue}if(s===`[`){for(o++;o<t&&e[o]!==`]`;)e[o]===`\\`&&o++,o++;continue}continue}if(n){if(s===`\\`){o++;continue}s===n&&(n=null);continue}if(s===`/`&&e[o+1]===`/`){i=!0,o++;continue}if(s===`/`&&e[o+1]===`*`){r=!0,o++;continue}if(s===`/`&&Ce(e,o)){a=!0;continue}(s===`'`||s===`"`||s==="`")&&(n=s)}return n!==null||r||i||a}function q(e,t,n){let r=e=>e.replace(K(t),n),i=xe(e);if(i===null)return e.replace(K(t),(...t)=>{let r=typeof t[0]==`string`?t[0]:``,i=Se(t);return i!==null&&we(e,i)?r:typeof n==`string`?n:n(r,...t.slice(1))});if(i.length===0)return r(e);let a=``,o=0;for(let t of i)o<t.start&&(a+=r(e.slice(o,t.start))),a+=e.slice(t.start,t.end),o=t.end;return o<e.length&&(a+=r(e.slice(o))),a}const Te=/\b(-?\d+(?:\.\d+)?)\s*([+\-%*/])\s*(-?\d+(?:\.\d+)?)\b/g,Ee=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*/g,De=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*else\s*\{([^}]*)\}/g,Oe=/if\s*\(\s*true\s*\)\s*\{([^}]*)\}\s*(?:else\s*\{[^}]*\}\s*)?/g,ke=/var\s+([A-Za-z_$]\w*)\s*=\s*['"]([^'"]+)['"]\.split\(['"]\|['"]\)\s*;\s*var\s+(\w+)\s*=\s*0\s*;\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\s*\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,Ae=/var\s+([A-Za-z_$]\w*)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\];\s*var\s+(\w+)\s*=\s*(\d+);\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,je=/['"]([^'"]*)['"]\s*\+\s*['"]([^'"]*)['"]/g;function J(e,t,n){for(let r=t;r>=0&&r<e.length;r+=n){let t=e[r];if(t&&!/\s/.test(t))return t}return``}function Me(e,t){let n=t.toSorted((e,t)=>t.start-e.start||t.end-e.end),r=e;for(let e of n)r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`;return r}function Y(e,t){let n=t.get(e.node.name);if(!n)return null;let r=e.scope.getBinding(e.node.name);if(!r||!A.isVariableDeclarator(r.path.node)||!A.isIdentifier(r.path.node.id)||!t.has(r.path.node.id.name))return null;let i=r.identifier===e.node,a=e.isReferencedIdentifier(),o=e.key===`left`&&e.parentPath.isAssignmentExpression(),s=e.key===`left`&&(e.parentPath.isForInStatement()||e.parentPath.isForOfStatement()),c=e.key===`argument`&&e.parentPath.isUpdateExpression();return!i&&!a&&!o&&!s&&!c?null:n}function Ne(e,t){try{let n=O.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=new Map;return k(n,{ObjectProperty(e){if(!e.node.shorthand||!A.isIdentifier(e.node.key)||!A.isIdentifier(e.node.value))return;let n=e.get(`value`);if(!n.isIdentifier())return;let i=Y(n,t),{start:a,end:o}=e.node;!i||a==null||o!=null&&(r.set(`${a}:${o}`,{start:a,end:o,text:`${e.node.key.name}: ${i}`}),e.skip())},Identifier(e){let n=Y(e,t),{start:i,end:a}=e.node;!n||i==null||a!=null&&r.set(`${i}:${a}`,{start:i,end:a,text:n})}}),r.size===0?e:Me(e,[...r.values()])}catch{return null}}function Pe(e){let t=e;return t=q(t,Te,(e,t,n,r)=>{let i=Number(t),a=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a))return e;let o=null;return n===`+`?o=i+a:n===`-`?o=i-a:n===`*`?o=i*a:n===`/`&&a!==0?o=i/a:n===`%`&&a!==0&&(o=i%a),o===null||!Number.isFinite(o)?e:String(Number.isInteger(o)?o:Number(o.toFixed(12)))}),t=q(t,je,(e,t,n)=>JSON.stringify(`${t}${n}`)),t=q(t,/--(\d)/g,(e,t)=>t),t=q(t,/\+\s*(\d+(?:\.\d+)?)/g,(e,t)=>t),t=q(t,/\b0x([0-9a-fA-F]{2,8})\b/g,(e,t)=>{let n=Number.parseInt(t,16);return Number.isFinite(n)?String(n):e}),t}function Fe(e){let t=e;return t=q(t,De,(e,t)=>t),t=q(t,Ee,``),t=q(t,Oe,(e,t)=>t),t=q(t,/\btrue\s*\?\s*([^:]+)\s*:\s*([^,;)\]}]+)/g,(e,t)=>t),t=q(t,/\bfalse\s*\?\s*[^:]+\s*:\s*([^,;)}\]]+)/g,(e,t)=>t),t=q(t,/if\s*\([^)]*\)\s*\{\s*\}\s*/g,``),t}function Ie(e){let t=e;return t=q(t,ke,(e,t,n,r,i)=>{let a=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,o=new Map,s;for(;(s=a.exec(i))!==null;){let e=s[1],t=(s[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&o.set(e,t)}let c=n.split(`|`).map(e=>e.trim()).map(e=>o.get(e)).filter(e=>!!e).join(`
|
|
5
|
+
`);return c.length>0?c:e}),t=q(t,Ae,(e,t,n,r,i,a)=>{let o=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,s=new Map,c;for(;(c=o.exec(a))!==null;){let e=c[1],t=(c[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&s.set(e,t)}let l=n.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``).trim()).map(e=>s.get(e)).filter(e=>!!e).join(`
|
|
6
|
+
`);return l.length>0?l:e}),t}function Le(e){let t=new Set,n=/\b(?:var|let|const)\s+([A-Za-z_$]\w{0,3})\b/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];e&&(e.length<=2||e.startsWith(`_0x`)||e.startsWith(`_`))&&t.add(e)}if(t.size===0)return{code:e,count:0};let i=new Map,a=1;for(let e of t)i.set(e,`var_${a}`),a++;let o=Ne(e,i);if(o!==null)return{code:o,count:o===e?0:i.size};let s=e.replace(RegExp(`\\b(${[...t].map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b`,`g`),(e,t,n,r)=>{let a=i.get(t);if(!a)return e;let o=n>0?r[n-1]:``,s=J(r,n-1,-1),c=J(r,n+e.length,1);return o===`.`||o===`'`||o===`"`||o==="`"||o===`$`||(s===`{`||s===`,`)&&(c===`:`||c===`(`)?e:a});return{code:s,count:s===e?0:i.size}}const Re={"<":(e,t)=>e<t,">":(e,t)=>e>t,"<=":(e,t)=>e<=t,"<==":(e,t)=>e<=t,">=":(e,t)=>e>=t,">==":(e,t)=>e>=t,"==":(e,t)=>e===t,"===":(e,t)=>e===t,"!=":(e,t)=>e!==t,"!==":(e,t)=>e!==t},ze=[{pattern:`jsfuck`,regex:/\[!\[\]\]\[\(['"]\)constructor['"]\)\]\(!!\[\]\+\[\]\)\(\)/g,replacement:`"function Boolean() { [native code] }"`},{pattern:`jsfuck`,regex:/!!\[\]\+\[\]/g,replacement:`"true"`},{pattern:`jsfuck`,regex:/!\[\]\+\[\]/g,replacement:`"false"`},{pattern:`jsfuck`,regex:/\+!!\[\]/g,replacement:`1`},{pattern:`jsfuck`,regex:/\[\]\+\[\]/g,replacement:`""`},{pattern:`jsfuck`,regex:/\+\[\]/g,replacement:`0`}],Be=[{pattern:`boolean-literal`,regex:/!!\[\]/g,replacement:`true`},{pattern:`boolean-literal`,regex:/!\[\]/g,replacement:`false`},{pattern:`undefined-literal`,regex:/void\s+0/g,replacement:`undefined`}],Ve={pattern:`opaque-truthy`,regex:/!0x0\b|!\b0(?![.\d])/g,replacement:`true`},He=[{pattern:`type-coercion`,regex:/typeof\s+undefined\s*===?\s*["']undefined["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+null\s*===?\s*["']object["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+NaN\s*===?\s*["']number["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*==\s*undefined/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*===\s*undefined/g,replacement:`false`},{pattern:`type-coercion`,regex:/NaN\s*===?\s*NaN/g,replacement:`false`}],Ue=/if\s*\(\s*(-?\d+(?:\.\d+)?)\s*([<>!=]+)\s*(-?\d+(?:\.\d+)?)\s*\)/g,We=/!\s*(-?\d+(?:\.\d+)?)(?![.\d\s\w])/g,Ge=/(?:var|let|const)\s+(\w+)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\]/g;function X(e,t,n,r){return e.solved.push({pattern:t,original:n,result:r}),r}function Z(e,t){for(let n of t)e.output=q(e.output,n.regex,t=>X(e,n.pattern,t,n.replacement))}function Ke(e){e.output=q(e.output,Ue,(t,n,r,i)=>{if(e.iterations>=e.maxIterations)return t;let a=Re[r];if(!a)return t;e.iterations+=1;let o=a(Number(n),Number(i));return X(e,`constant-comparison`,t,String(o)),e.replaceInPlace?`/* ${t} => ${o} */ if (${o})`:`if (${o})`})}function qe(e){e.output=q(e.output,We,(t,n)=>{let r=Number(n);return r===0||!Number.isFinite(r)?t:X(e,`opaque-falsy`,t,`false`)})}function Je(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ye(e){let t=new Map;return q(e,Ge,(e,n,r)=>{let i=r.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``));return t.set(n,i),e}),t}function Xe(e){let t=Ye(e.output);if(t.size!==0)for(let[n,r]of t){let t=RegExp(`${Je(n)}\\(['"]?(0x[0-9a-fA-F]+|\\d+)['"]?\\)`,`g`);e.output=q(e.output,t,(t,n)=>{if(e.iterations>=e.maxIterations)return t;let i=n.startsWith(`0x`)?Number.parseInt(n,16):Number(n);return i<0||i>=r.length?t:(e.iterations+=1,X(e,`string-array-access`,t,JSON.stringify(r[i])))})}}function Ze(e){let t={output:e.code,solved:[],replaceInPlace:e.replaceInPlace,maxIterations:e.maxIterations,iterations:0};return Ke(t),Z(t,ze),Z(t,Be),Z(t,[Ve]),qe(t),Xe(t),Z(t,He),{success:!0,solvedCount:t.solved.length,solved:t.solved,transformedCode:e.replaceInPlace?t.output:void 0}}function Q(e,t){let n=e.code;return typeof n!=`string`||n.trim().length===0?null:n}async function Qe(e){let t=Q(e,`js_deobfuscate_pipeline`);if(!t)return l({success:!1,error:`code is required`});let n=h(e,`useWebcrack`,!0),r=h(e,`aggressive`,!1),i=h(e,`humanize`,!0),a=h(e,`returnStageDetails`,!1),o=Date.now(),s=t,c=[],u=Pe(s);u!==s&&(s=u,c.push(`constant_fold`));let d=Fe(s);d!==s&&(s=d,c.push(`dead_code_remove`));let f=s,p=!1,m,g;if(n)try{let e=await x(s,{unminify:!0,unpack:!0});e.applied?(f=e.code,p=!0):m=e.reason?`webcrack stage did not apply: ${e.reason}`:`webcrack stage did not apply any transformation.`}catch(e){g=e instanceof Error?e.message:String(e)}if(r){let e=Ie(f);e!==f&&(f=e)}let _=f,v=0;if(i){let e=Le(_);e.code!==_&&(_=e.code,v=e.count)}let y=Date.now()-o,b=t.length>0?1-_.length/t.length:0,S={success:!m&&!g,deobfuscatedCode:_,...m?{warning:m}:{},...g?{error:`webcrack stage failed: ${g}`}:{},stats:{originalSize:t.length,finalSize:_.length,reductionRate:Math.round(b*1e3)/10,processingTimeMs:y,stages:{preprocessor:{transforms:c,sizeAfter:s.length},deobfuscator:{webcrackApplied:p,sizeAfter:f.length,...m?{warning:m}:{},...g?{error:g}:{}},humanizer:{renameCount:v,sizeAfter:_.length}}}};return a&&(S.stageDetails={preprocessed:s.substring(0,5e3),deobfuscated:f.substring(0,5e3)}),l(S)}async function $e(e){let t=Q(e,`js_solve_constraints`);return l(t?Ze({code:t,replaceInPlace:h(e,`replaceInPlace`,!0),maxIterations:p(e,`maxIterations`,100)}):{success:!1,error:`code is required`})}const et=new Set([`summary`,`priority`,`incremental`,`full`]);var tt=class{collector;scriptManager;constructor(e){this.collector=e.collector,this.scriptManager=e.scriptManager}async handleCollectCode(t){let n=h(t,`returnSummaryOnly`,!1),r=g(t,`smartMode`,et),i=a,o=e=>e.slice(0,i).map(e=>({url:e.url,type:e.type,size:e.size,sizeKB:(e.size/1024).toFixed(2),truncated:e.metadata?.truncated||!1,preview:`${e.content.substring(0,200)}...`})),u=e=>{let t=(Array.isArray(e.summaries)&&e.summaries.length>0?e.summaries:o(e.files)).slice(0,i),n=Array.isArray(e.summaries)?e.summaries.length:e.files.length,r=e.totalSize>0?e.totalSize:Array.isArray(e.summaries)?e.summaries.reduce((e,t)=>e+(typeof t.size==`number`?t.size:0),0):e.files.reduce((e,t)=>e+t.size,0);return{totalSize:r,totalSizeKB:(r/1024).toFixed(2),filesCount:n,summarizedFiles:t.length,omittedFiles:Math.max(0,n-t.length),collectTime:e.collectTime,summary:t}};r||=`summary`;let d=await this.collector.collect({url:y(t,`url`),includeInline:h(t,`includeInline`),includeExternal:h(t,`includeExternal`),includeDynamic:h(t,`includeDynamic`),smartMode:r,compress:h(t,`compress`),maxTotalSize:p(t,`maxTotalSize`),maxFileSize:t.maxFileSize?p(t,`maxFileSize`,0)*1024:void 0,priorities:t.priorities});if(n)return l({mode:`summary`,...u(d),hint:`Use get_script_source for specific files.`});let f=s,m=c,_=Buffer.byteLength(JSON.stringify(d),`utf8`);return d.totalSize>f||_>m?(e.warn(`Collected code is too large (collected=${(d.totalSize/1024).toFixed(2)}KB, response=${(_/1024).toFixed(2)}KB), returning summary mode.`),l({warning:`Code size exceeds safe response threshold; summary returned.`,...u(d),estimatedResponseSize:_,estimatedResponseSizeKB:(_/1024).toFixed(2),recommendations:[`Use get_script_source for targeted files.`,`Use more specific priority filters.`,`Use smartMode=summary for initial reconnaissance.`]})):l(d)}async handleSearchInScripts(e){await this.scriptManager.init();let t=f(e,`keyword`);if(!t)return l({success:!1,error:`keyword is required`});let n=p(e,`maxMatches`,100),r=h(e,`returnSummary`,!1),i=p(e,`maxContextSize`,5e4),a=await this.scriptManager.searchInScripts(t,{isRegex:h(e,`isRegex`),caseSensitive:h(e,`caseSensitive`),contextLines:p(e,`contextLines`),maxMatches:n}),o=JSON.stringify(a).length;if(r||o>i){let t=a.matches??[];return l({success:!0,keyword:e.keyword,totalMatches:t.length,resultSize:o,resultSizeKB:(o/1024).toFixed(2),truncated:o>i,reason:o>i?`Result too large (${(o/1024).toFixed(2)}KB > ${(i/1024).toFixed(2)}KB)`:`Summary mode enabled`,matchesSummary:t.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url,line:e.line,preview:`${(e.context??``).substring(0,100)}...`})),recommendations:[`Use more specific keywords.`,`Reduce maxMatches (current: ${n}).`,`Use get_script_source for targeted file retrieval.`]})}return l(a)}async handleExtractFunctionTree(e){let t=f(e,`scriptId`),n=f(e,`functionName`);if(!t)return l({success:!1,error:`scriptId is required`,hint:`Use get_all_scripts() to list available scripts and their scriptIds`});if(!n)return l({success:!1,error:`functionName is required`,hint:`Specify the name of the function to extract`});await this.scriptManager.init();let r=await this.scriptManager.getAllScripts();if(!r.some(e=>String(e.scriptId)===String(t))){let e=r.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url?.substring(0,80)}));return l({success:!1,error:`Script not found: ${t}`,hint:`The specified scriptId does not exist. Use get_all_scripts() to list available scripts.`,availableScripts:e.length>0?e:`No scripts loaded. Navigate to a page first.`,totalScripts:r.length})}try{return l({success:!0,...await this.scriptManager.extractFunctionTree(t,n,{maxDepth:p(e,`maxDepth`),maxSize:p(e,`maxSize`),includeComments:h(e,`includeComments`)})})}catch(e){return l({success:!1,error:e instanceof Error?e.message:String(e),hint:`Make sure the function name exists in the specified script`})}}},$=class{collector;scriptManager;constructor(e){this.collector=e.collector,this.scriptManager=e.scriptManager}async handleClearCollectedData(){return b(async()=>(await this.collector.clearAllData(),this.scriptManager.clear(),{message:`All collected data cleared.`,cleared:{fileCache:!0,compressionCache:!0,collectedUrls:!0,scriptManager:!0}}))}async handleGetCollectionStats(){return b(async()=>{let e=await this.collector.getAllStats();return{stats:e,summary:{totalCachedFiles:e.cache.memoryEntries+e.cache.diskEntries,totalCacheSize:`${(e.cache.totalSize/1024).toFixed(2)} KB`,compressionRatio:`${e.compression.averageRatio.toFixed(1)}%`,cacheHitRate:e.compression.cacheHits>0?`${(e.compression.cacheHits/(e.compression.cacheHits+e.compression.cacheMisses)*100).toFixed(1)}%`:`0%`,collectedUrls:e.collector.collectedUrls}}})}};const nt=new Set([`function`,`xhr`,`fetch`,`websocket`,`localstorage`,`cookie`]),rt=new Set([`log`,`block`,`modify`]);async function it(e,t){let n=y(e,`action`);switch(n){case`create`:return l(await t.createHook({target:y(e,`target`),type:g(e,`type`,nt)??`function`,action:g(e,`hookAction`,rt,`log`),customCode:f(e,`customCode`)}));case`list`:return l({hooks:t.getAllHooks()});case`records`:return l({records:t.getHookRecords(y(e,`hookId`))});case`clear`:return t.clearHookRecords(f(e,`hookId`)),l({success:!0,message:`Hook records cleared`});default:return l({success:!1,message:`Unknown hook action: ${n}. Valid actions: create, list, records, clear`})}}async function at(t,n){let r=f(n,`searchKeyword`,``),i=h(n,`forceRequireAll`,!!r),a=Math.min(p(n,`maxResults`,20),100);return b(async()=>{let n=await d(await t.getActivePage(),async e=>{let t=window,n=null;typeof t.__webpack_require__==`function`&&(n=t.__webpack_require__);let r=Object.keys(t).filter(e=>e.startsWith(`webpackChunk`)||e.startsWith(`webpackJsonp`)),i=new Set;for(let e of r){let n=t[e];if(!Array.isArray(n))continue;let r=n;if(r.m&&typeof r.m==`object`)for(let e of Object.keys(r.m))i.add(e);for(let e of n)if(Array.isArray(e)&&e[1]&&typeof e[1]==`object`)for(let t of Object.keys(e[1]))i.add(t)}if(typeof t.__webpack_modules__==`object`&&t.__webpack_modules__)for(let e of Object.keys(t.__webpack_modules__))i.add(e);if(!n)for(let e of r){let r=t[e];if(r?.m&&typeof r.m==`object`){let e=r.m;n=t=>{try{let n=e[t];return typeof n==`function`?n():n}catch{return}};break}}let a=Array.from(i);if(!e.forceRequireAll||!n)return{total:a.length,requireFound:!!n,chunkKeys:r,moduleIds:a.slice(0,200),matches:[]};let o=n,s=[];for(let t of a){if(s.length>=e.maxResults)break;try{let n=o(t);if(n==null)continue;let r;try{r=JSON.stringify(n)}catch{r=String(n)}(!e.searchKeyword||r.toLowerCase().includes(e.searchKeyword.toLowerCase()))&&s.push({id:t,preview:r.slice(0,600)})}catch{}}return{total:a.length,requireFound:!0,chunkKeys:r,moduleIds:a.slice(0,200),matches:s}},{searchKeyword:r,forceRequireAll:i,maxResults:a});return e.info(`webpack_enumerate: found ${n.total} modules, ${n.matches.length} matches`),n})}async function ot(e,t){return at(e,t)}async function st(e,t={}){let n=_(t,`vulnerability`);if(!n||typeof n.type!=`string`||typeof n.description!=`string`)return l({success:!1,error:`vulnerability is required with at least type and description fields`});if(!e.isSamplingSupported())return l({success:!1,error:`Sampling not supported by this client`,hint:`The connected MCP client does not support LLM sampling. Try using Claude Desktop or another sampling-capable client.`});let r=g(t,`targetPlatform`,new Set([`browser`,`nodejs`,`electron`,`android`,`ios`,`unknown`]),`unknown`),i=m(t,`mitigations`);try{let t=ct(n,r,i),a=await e.sampleText({systemPrompt:`You are an exploit development expert. Suggest exploitation primitives and attack chains. Output only valid JSON. NEVER generate executable payloads.`,userMessage:t,maxTokens:3072,temperature:.3,modelHint:`sonnet`});if(!a)return l({success:!1,error:`Exploit suggestion failed: LLM returned null`});let o=lt(a);if(!o)return l({success:!1,error:`Exploit suggestion failed: Invalid LLM response format`});let s=o.suggestions.filter(e=>e.confidence>=.6);return l({success:!0,suggestions:s,totalSuggestions:o.suggestions.length,filtered:o.suggestions.length-s.length})}catch(e){return l({success:!1,error:`Exploit suggestion failed: ${e instanceof Error?e.message:String(e)}`})}}function ct(e,t,n){let r=n.length>0?`\n\nKnown mitigations: ${n.join(`, `)}`:``;return`Given this vulnerability, suggest exploitation primitives and attack chains. Output ONLY valid JSON:
|
|
7
|
+
{
|
|
8
|
+
"suggestions": [
|
|
9
|
+
{
|
|
10
|
+
"primitive": "<exploit type>",
|
|
11
|
+
"confidence": <0.0-1.0>,
|
|
12
|
+
"steps": ["<step 1>", "<step 2>", ...],
|
|
13
|
+
"references": ["<CVE-2025-1234>", "<URL>", ...],
|
|
14
|
+
"requiredConditions": ["<condition 1>", ...],
|
|
15
|
+
"difficulty": "trivial|moderate|hard|expert"
|
|
16
|
+
}
|
|
17
|
+
]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
Vulnerability:
|
|
21
|
+
- Type: ${e.type}
|
|
22
|
+
- Description: ${e.description}
|
|
23
|
+
- Severity: ${e.severity||`unknown`}
|
|
24
|
+
|
|
25
|
+
Target platform: ${t}${r}
|
|
26
|
+
|
|
27
|
+
IMPORTANT: Provide theoretical exploitation steps only. Do NOT generate executable payloads.`}function lt(e){try{let t=e.match(/\{[\s\S]*\}/);if(!t)return null;let n=JSON.parse(t[0]);return Array.isArray(n.suggestions)?{suggestions:n.suggestions}:null}catch{return null}}async function ut(e){let t=f(e,`code`);return!t||t.trim().length===0?l({success:!1,error:`code is required and must be a non-empty string`}):l({success:!0,...await te(t)})}async function dt(e){let t=f(e,`code`);if(!t||t.trim().length===0)return l({success:!1,error:`code is required and must be a non-empty string`});let n=S(t,{});return l({success:!0,risks:n,riskCount:n.length,severities:{critical:n.filter(e=>e.severity===`critical`).length,high:n.filter(e=>e.severity===`high`).length,medium:n.filter(e=>e.severity===`medium`).length,low:n.filter(e=>e.severity===`low`).length}})}var ft=class{collector;scriptManager;deobfuscator;advancedDeobfuscator;obfuscationDetector;analyzer;cryptoDetector;hookManager;samplingBridge;jsvmpDeobfuscator;jscramblerDeobfuscator;packerDeobfuscator;vmDeobfuscator;collectionHandlers;dataManagementHandlers;constructor(e){this.collector=e.collector,this.scriptManager=e.scriptManager,this.deobfuscator=e.deobfuscator,this.advancedDeobfuscator=e.advancedDeobfuscator,this.obfuscationDetector=e.obfuscationDetector,this.analyzer=e.analyzer,this.cryptoDetector=e.cryptoDetector,this.hookManager=e.hookManager,this.samplingBridge=e.samplingBridge,this.jsvmpDeobfuscator=new ee,this.jscramblerDeobfuscator=e.jscramblerDeobfuscator,this.packerDeobfuscator=e.packerDeobfuscator,this.vmDeobfuscator=e.vmDeobfuscator,this.collectionHandlers=new tt({collector:this.collector,scriptManager:this.scriptManager}),this.dataManagementHandlers=new $({collector:this.collector,scriptManager:this.scriptManager})}async handleCollectCode(e){return this.collectionHandlers.handleCollectCode(e)}async handleSearchInScripts(e){return this.collectionHandlers.handleSearchInScripts(e)}async handleExtractFunctionTree(e){return this.collectionHandlers.handleExtractFunctionTree(e)}async handleDeobfuscate(e){return se(e,this.deobfuscator,this.advancedDeobfuscator,this.jscramblerDeobfuscator,this.packerDeobfuscator,this.vmDeobfuscator)}async handleWebcrackUnpack(e){return ce(e)}async handleAnalysisDecodeStringArray(e){return le(e)}async handleUnderstandCode(e){return ge(e,this.analyzer)}async handleDetectCrypto(e){return _e(e,this.cryptoDetector)}async handleDetectObfuscation(e){return ve(e,this.obfuscationDetector)}async handleJsDeobfuscateJsvmp(e){return I(e,this.jsvmpDeobfuscator)}async handleJsAnalyzeVm(e){return L(e,this.jsvmpDeobfuscator)}async handleJsDeobfuscatePipeline(e){return Qe(e)}async handleJsSolveConstraints(e){return $e(e)}async handleAnalysisAstMatch(e){return z(e)}async handleAnalysisDeflatControlFlow(e){return B(e)}async handleJsSymbolicExecute(e){return pe(e)}async handleJsSymbolicExecuteJsvmp(e){return me(e)}async handleManageHooks(e){return it(e,this.hookManager)}async handleWebpackEnumerate(e){return ot(this.collector,e)}async handleClearCollectedData(){return this.dataManagementHandlers.handleClearCollectedData()}async handleGetCollectionStats(){return this.dataManagementHandlers.handleGetCollectionStats()}async handleAiSuggestExploits(e){return st(this.samplingBridge,e)}async handleAnalysisDataFlow(e){return ut(e)}async handleAnalysisSecurityScan(e){return dt(e)}};export{ft as CoreAnalysisHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./definitions-aeRd5DAR.mjs";import{t as e}from"./handlers-BQ4K8Jbr.mjs";export{e as AntiDebugToolHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./ToolError-g3rjWzhx.mjs";import{open as t}from"yauzl";const n=/^lib\/arm64-v8a\/(lib[^/]+\.so)$/i;async function r(r){if(!r||r.length===0)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);return new Promise((a,o)=>{t(r,{lazyEntries:!0,autoClose:!0},(t,s)=>{if(t||!s){o(new e(`VALIDATION`,`Failed to open APK as ZIP: ${t?.message??`unknown`}`,{details:{apkPath:r},cause:t??void 0}));return}let c=s,l=[],u=t=>{let a=n.exec(t.fileName);if(!a){c.readEntry();return}let s=a[1];c.openReadStream(t,(t,n)=>{if(t||!n){p(),c.close(),o(new e(`RUNTIME`,`Failed to read ${s}: ${t?.message??`unknown`}`,{details:{apkPath:r,name:s},cause:t??void 0}));return}i(n,268435456).then(e=>{l.push({name:s,bytes:e}),c.readEntry()},t=>{p(),c.close(),o(new e(`RUNTIME`,`Reading ${s} failed: ${t.message}`,{details:{apkPath:r,name:s},cause:t}))})})},d=()=>{p(),a(l)},f=t=>{p(),c.close(),o(new e(`RUNTIME`,`ZIP read failed: ${t.message}`,{details:{apkPath:r},cause:t}))};function p(){c.removeListener(`entry`,u),c.removeListener(`end`,d),c.removeListener(`error`,f)}c.on(`entry`,u),c.on(`end`,d),c.on(`error`,f),c.readEntry()})})}function i(e,t){return new Promise((n,r)=>{let i=[],a=0;e.on(`data`,n=>{if(a+=n.length,a>t){e.destroy(),r(Error(`extracted .so exceeds ${t} bytes`));return}i.push(n)}),e.on(`end`,()=>n(Uint8Array.from(Buffer.concat(i)))),e.on(`error`,r)})}export{r as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-BGCcd-jJ.mjs";import{Va as t,fa as n,pa as r}from"./constants-nvsLpSri.mjs";import{t as i}from"./config-5ODJ3Aj0.mjs";import{i as a,n as o}from"./outputPaths-CHtELDyi.mjs";import{n as s,r as c}from"./artifacts-Bx9GLx4J.mjs";import{join as l,resolve as u}from"node:path";import{readdir as d,rm as f,stat as p}from"node:fs/promises";var m=class n{static instance;MAX_TOKENS=t;WARNING_THRESHOLDS=[.8,.9,.95];BYTES_PER_TOKEN=4;AUTO_CLEANUP_THRESHOLD=.9;AUTO_CLEANUP_REARM_THRESHOLD=.8;HISTORY_RETENTION=300*1e3;currentUsage=0;toolCallHistory=[];warnings=new Set;sessionStartTime=Date.now();trackingEnabled=!0;autoCleanupArmed=!0;MAX_ESTIMATION_DEPTH=4;MAX_ESTIMATION_ARRAY_ITEMS=50;MAX_ESTIMATION_OBJECT_KEYS=50;MAX_ESTIMATION_STRING_LENGTH=2e3;MAX_ESTIMATION_BYTES=256*1024;externalCleanupFn=null;constructor(){e.info(`TokenBudgetManager initialized`)}static getInstance(){return this.instance||=new n,this.instance}setExternalCleanup(e){this.externalCleanupFn=e}recordToolCall(t,n,r){if(this.trackingEnabled)try{let i=this.calculateSize(n),a=this.calculateSize(r),o=i+a,s=this.estimateTokens(o);this.currentUsage+=s;let c={toolName:t,timestamp:Date.now(),requestSize:i,responseSize:a,estimatedTokens:s,cumulativeTokens:this.currentUsage};this.toolCallHistory.push(c),e.debug(`Token usage: ${this.currentUsage}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%) | Tool: ${t} | Size: ${(o/1024).toFixed(1)}KB | Tokens: ${s}`),this.checkWarnings(),this.shouldAutoCleanup()&&this.autoCleanup()}catch(t){e.error(`Failed to record tool call:`,t)}}isRecord(e){return typeof e==`object`&&!!e}hasDetailedSummarySize(e){if(!this.isRecord(e)||!(`detailId`in e))return!1;let t=e.summary;if(!this.isRecord(t))return!1;let{size:n}=t;return typeof n==`number`&&Number.isFinite(n)&&n>0}tryEstimateMcpEnvelope(e){if(!this.isRecord(e))return null;let t=e.content;if(!Array.isArray(t)||t.length===0)return null;let n=t[0];if(!this.isRecord(n)||n.type!==`text`||typeof n.text!=`string`)return null;let r=n.text,i=r.length>this.MAX_ESTIMATION_STRING_LENGTH?`${r.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)}...[truncated:${r.length}]`:r,a=42+(e.isError===!0?14:0),o=Buffer.byteLength(i,`utf8`);return Math.min(a+o,this.MAX_ESTIMATION_BYTES)}calculateSize(t){try{if(this.hasDetailedSummarySize(t))return Math.min(t.summary.size,this.MAX_ESTIMATION_BYTES);let e=this.tryEstimateMcpEnvelope(t);if(e!==null)return e;let n=this.normalizeForSizeEstimate(t,0,new WeakSet),r=JSON.stringify(n);return r?Math.min(Buffer.byteLength(r,`utf8`),this.MAX_ESTIMATION_BYTES):0}catch(t){return e.warn(`Failed to calculate data size:`,t),0}}normalizeForSizeEstimate(e,t,n){if(e==null)return e;let r=typeof e;if(r===`boolean`||r===`number`)return e;if(r===`string`){let t=e;if(t.length<=this.MAX_ESTIMATION_STRING_LENGTH)return t;let n=`...[truncated:${t.length}]`,r=Math.max(this.MAX_ESTIMATION_STRING_LENGTH-n.length,0);return`${t.slice(0,r)}${n}`}if(r===`bigint`||r===`symbol`)return e.toString();if(r===`function`)return`[Function]`;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack?.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)};if(Buffer.isBuffer(e))return`[Buffer:${e.byteLength}]`;if(t>=this.MAX_ESTIMATION_DEPTH)return Array.isArray(e)?`[Array:${e.length}]`:`[Object]`;if(Array.isArray(e)){let r=e.slice(0,this.MAX_ESTIMATION_ARRAY_ITEMS).map(e=>this.normalizeForSizeEstimate(e,t+1,n));return e.length>this.MAX_ESTIMATION_ARRAY_ITEMS&&r.push(`[truncated:${e.length-this.MAX_ESTIMATION_ARRAY_ITEMS}]`),r}if(r===`object`){if(!this.isRecord(e))return`[Object]`;if(n.has(e))return`[Circular]`;n.add(e);let r=Object.entries(e),i=r.slice(0,this.MAX_ESTIMATION_OBJECT_KEYS),a={};for(let[e,r]of i)a[e]=this.normalizeForSizeEstimate(r,t+1,n);return r.length>this.MAX_ESTIMATION_OBJECT_KEYS&&(a.__truncatedKeys=r.length-this.MAX_ESTIMATION_OBJECT_KEYS),a}return String(e)}estimateTokens(e){return Math.ceil(e/this.BYTES_PER_TOKEN)}getUsagePercentage(){return Math.round(this.currentUsage/this.MAX_TOKENS*100)}checkWarnings(){let e=this.currentUsage/this.MAX_TOKENS;for(let t of this.WARNING_THRESHOLDS)e>=t&&!this.warnings.has(t)&&(this.emitWarning(t),this.warnings.add(t))}emitWarning(t){let n=Math.round(t*100),r=this.MAX_TOKENS-this.currentUsage;e.warn(`Token Budget Warning: ${n}% used! (${this.currentUsage}/${this.MAX_TOKENS}, ${r} tokens remaining)`),t>=.95?e.warn(`CRITICAL: Consider clearing caches or starting a new session.`):t>=.9?e.warn(`HIGH: Auto-cleanup will trigger soon. Consider using summary modes.`):t>=.8&&e.warn(`MODERATE: Monitor usage. Use get_token_budget_stats for details.`)}shouldAutoCleanup(){let e=this.currentUsage/this.MAX_TOKENS;return e<this.AUTO_CLEANUP_REARM_THRESHOLD&&(this.autoCleanupArmed=!0),this.autoCleanupArmed&&e>=this.AUTO_CLEANUP_THRESHOLD}autoCleanup(){this.autoCleanupArmed=!1,e.info(`Auto-cleanup triggered at 90% usage.`);let t=this.currentUsage;if(this.externalCleanupFn)try{this.externalCleanupFn(),e.info(`External cleanup callback invoked`)}catch(t){e.warn(`External cleanup callback failed:`,t)}let n=Date.now()-this.HISTORY_RETENTION,r=this.toolCallHistory.length;this.toolCallHistory=this.toolCallHistory.filter(e=>e.timestamp>n);let i=r-this.toolCallHistory.length;e.info(`Removed ${i} old tool call records`),this.recalculateUsage();let a=this.currentUsage,o=t-a,s=Math.round(o/this.MAX_TOKENS*100);e.info(`Cleanup complete. Freed ${o} tokens (${s}%). Usage: ${a}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%)`);let c=a/this.MAX_TOKENS;c<this.AUTO_CLEANUP_REARM_THRESHOLD&&(this.autoCleanupArmed=!0),this.warnings=new Set(Array.from(this.warnings).filter(e=>c>=e))}recalculateUsage(){this.currentUsage=this.toolCallHistory.reduce((e,t)=>e+t.estimatedTokens,0)}getStats(){let e=new Map;for(let t of this.toolCallHistory){let n=e.get(t.toolName)||0;e.set(t.toolName,n+t.estimatedTokens)}let t=Array.from(e.entries()).map(([e,t])=>({tool:e,tokens:t,percentage:Math.round(t/this.currentUsage*100)})).toSorted((e,t)=>t.tokens-e.tokens).slice(0,10),n=this.generateSuggestions(t),r=this.toolCallHistory.slice(-20);return{currentUsage:this.currentUsage,maxTokens:this.MAX_TOKENS,usagePercentage:this.getUsagePercentage(),toolCallCount:this.toolCallHistory.length,topTools:t,warnings:Array.from(this.warnings).map(e=>Math.round(e*100)),recentCalls:r,suggestions:n,sessionStartTime:this.sessionStartTime}}generateSuggestions(e){let t=[],n=this.currentUsage/this.MAX_TOKENS;n>=.95?t.push(` CRITICAL: Clear all caches immediately or start a new session`):n>=.9?t.push(`HIGH: Auto-cleanup triggered. Consider manual cleanup for better control`):n>=.8&&t.push(`MODERATE: Monitor usage closely. Use summary modes for large data`);for(let{tool:n,percentage:r}of e)r>30&&(n.includes(`collect_code`)?t.push(` ${n} uses ${r}% tokens. Try smartMode="summary" or "priority"`):n.includes(`get_script_source`)?t.push(` ${n} uses ${r}% tokens. Try preview=true first`):n.includes(`network_get_requests`)?t.push(` ${n} uses ${r}% tokens. Reduce limit or use filters`):n.includes(`page_evaluate`)&&t.push(` ${n} uses ${r}% tokens. Query specific properties instead of full objects`));return t.length===0&&t.push(` Token usage is healthy. Continue monitoring.`),t}manualCleanup(){e.info(`Manual cleanup requested.`),this.autoCleanup()}setTrackingEnabled(t){this.trackingEnabled!==t&&(this.trackingEnabled=t,e.warn(`Token budget tracking ${t?`enabled`:`disabled`}`))}isTrackingEnabled(){return this.trackingEnabled}reset(){e.info(`Resetting token budget...`),this.currentUsage=0,this.toolCallHistory=[],this.warnings.clear(),this.autoCleanupArmed=!0,this.sessionStartTime=Date.now(),e.info(`Token budget reset complete`)}},h=class t{static instance;GLOBAL_MAX_SIZE=n;LOW_HIT_RATE_THRESHOLD=r;caches=new Map;constructor(){e.info(`UnifiedCacheManager initialized`)}static getInstance(){return this.instance||=new t,this.instance}registerCache(t){this.caches.set(t.name,t),e.info(`Registered cache: ${t.name}`)}unregisterCache(t){this.caches.delete(t),e.info(`Unregistered cache: ${t}`)}async getGlobalStats(){let{caches:e,totalSize:t,hitRate:n}=await this.getFilteredStats(()=>!0),r=e.reduce((e,t)=>e+t.entries,0),i=this.generateRecommendations(t,n,e);return{totalEntries:r,totalSize:t,totalSizeMB:(t/1024/1024).toFixed(2),hitRate:n,caches:e,recommendations:i}}async getFilteredStats(t){let n=0,r=0,i=0,a=[];for(let[o,s]of this.caches)if(t(o))try{let e=await s.getStats();n+=e.size,r+=e.hits||0,i+=e.misses||0,a.push({name:o,entries:e.entries,size:e.size,sizeMB:(e.size/1024/1024).toFixed(2),hitRate:e.hitRate,ttl:e.ttl})}catch(t){e.error(`Failed to get stats for cache ${o}:`,t)}let o=r+i>0?r/(r+i):0;return{caches:a,totalSize:n,hitRate:o}}async smartCleanup(t,n){let r=n?.namespaces,i=e=>!r||r.length===0||r.includes(e),a=t||this.GLOBAL_MAX_SIZE*.7,o=(await this.getFilteredStats(i)).totalSize;if(o<=a)return e.info(`No cleanup needed`),{before:o,after:o,freed:0,freedPercentage:0};e.info(`Smart cleanup: current ${(o/1024/1024).toFixed(2)}MB, target ${(a/1024/1024).toFixed(2)}MB`+(r&&r.length>0?` (namespaces: ${r.join(`, `)})`:``)),await this.cleanupExpired(i);let s=await this.getFilteredStats(i);if(s.totalSize<=a||(await this.cleanupLowHitRate(i),s=await this.getFilteredStats(i),s.totalSize<=a))return this.calculateCleanupResult(o,s.totalSize);await this.cleanupLargeItems(i);let c=await this.getFilteredStats(i);return this.calculateCleanupResult(o,c.totalSize)}async cleanupExpired(t){e.info(`Cleaning up expired data...`);for(let[n,r]of this.caches)if(t(n)&&r.cleanup)try{await r.cleanup(),e.debug(`Cleaned up expired data in ${n}`)}catch(t){e.error(`Failed to cleanup ${n}:`,t)}}async cleanupLowHitRate(t){e.info(`Cleaning up low hit rate caches...`);let n=await this.getFilteredStats(t),r=n.hitRate;for(let t of n.caches)if(t.hitRate!==void 0&&t.hitRate<r*this.LOW_HIT_RATE_THRESHOLD){let n=this.caches.get(t.name);if(n?.clear)try{await n.clear(),e.info(`Cleared low hit rate cache: ${t.name} (${(t.hitRate*100).toFixed(1)}%)`)}catch(n){e.error(`Failed to clear ${t.name}:`,n)}}}async cleanupLargeItems(t){e.info(`Cleaning up large caches...`);let n=(await this.getFilteredStats(t)).caches.toSorted((e,t)=>t.size-e.size);for(let t of n.slice(0,2)){let n=this.caches.get(t.name);if(n?.clear)try{await n.clear(),e.info(`Cleared large cache: ${t.name} (${t.sizeMB}MB)`)}catch(n){e.error(`Failed to clear ${t.name}:`,n)}}}calculateCleanupResult(t,n){let r=t-n,i=Math.round(r/this.GLOBAL_MAX_SIZE*100);return e.info(`Cleanup complete! Freed ${(r/1024/1024).toFixed(2)}MB (${i}%). Usage: ${(n/1024/1024).toFixed(2)}MB/${(this.GLOBAL_MAX_SIZE/1024/1024).toFixed(0)}MB`),{before:t,after:n,freed:r,freedPercentage:i}}async clearAll(){e.info(`Clearing all caches...`);for(let[t,n]of this.caches)if(n.clear)try{await n.clear(),e.info(`Cleared cache: ${t}`)}catch(n){e.error(`Failed to clear ${t}:`,n)}e.success(`All caches cleared`)}async preheat(t){e.info(`Preheating cache for ${t.length} URLs...`),e.info(`Cache preheat completed`)}generateRecommendations(e,t,n){let r=[],i=e/this.GLOBAL_MAX_SIZE;i>=.9?r.push(` CRITICAL: Cache size at 90%. Run smart_cache_cleanup immediately!`):i>=.7?r.push(`WARNING: Cache size at 70%. Consider cleanup soon.`):i>=.5&&r.push(`INFO: Cache size at 50%. Monitor usage.`),t<.3?r.push(` Low cache hit rate (<30%). Consider adjusting TTL or cache strategy.`):t>.7&&r.push(` Good cache hit rate (>70%). Cache is working well.`);for(let t of n){let n=t.size/e;n>.5&&r.push(` ${t.name} uses ${Math.round(n*100)}% of total cache. Consider cleanup.`),t.hitRate!==void 0&&t.hitRate<.2&&r.push(` ${t.name} has low hit rate (${(t.hitRate*100).toFixed(1)}%). Consider disabling or adjusting.`)}return r.length===0&&r.push(` Cache health is good. No action needed.`),r}};const g=Object.freeze([`wasm`,`traces`,`profiles`,`dumps`,`reports`,`har`,`captures`,`sessions`,`offloaded`,`tmp`,`heap-snapshots`]);function _(e=process.env){let t=Math.max(0,parseInt(e.MCP_ARTIFACT_RETENTION_DAYS??`0`,10)||0),n=Math.max(0,parseInt(e.MCP_ARTIFACT_MAX_TOTAL_MB??`0`,10)||0),r=Math.max(0,parseInt(e.MCP_ARTIFACT_CLEANUP_INTERVAL_MINUTES??`0`,10)||0),i=[`1`,`true`].includes((e.MCP_ARTIFACT_CLEANUP_ON_START??``).toLowerCase());return{enabled:t>0||n>0,retentionDays:t,maxTotalBytes:n*1024*1024,cleanupOnStart:i,cleanupIntervalMinutes:r}}async function v(e){let t=_(),n={...t,retentionDays:e?.retentionDays??t.retentionDays,maxTotalBytes:e?.maxTotalBytes??t.maxTotalBytes},r=e?.now??Date.now(),i=e?.dryRun??!1,o=x(e?.categories),s=x(e?.excludeCategories),c=e?.directories??b({categories:o,excludeCategories:s}),l=n.retentionDays>0?r-n.retentionDays*864e5:0,u=0,d=0,p=0,m=0,h=0,g=[],v=[],y=a(),w=[];function T(e){w.push(f(e,{force:!0}).then(()=>void 0).catch(()=>void 0))}for(let e of c)await S(e,y,l,i,e=>{u++,l>0&&e.mtimeMs<l?(d++,p+=e.size,m+=e.size,v.length<20&&v.push(e.relativePath),i||T(e.path)):g.push(e)});if(n.maxTotalBytes>0){let e=g.reduce((e,t)=>e+t.size,0);if(e>n.maxTotalBytes){g.sort((e,t)=>e.mtimeMs-t.mtimeMs);let t=0;for(;t<g.length&&e>n.maxTotalBytes;){let n=g[t];e-=n.size,d++,p+=n.size,h+=n.size,v.length<20&&v.push(n.relativePath),i||T(n.path),t++}g.splice(0,t)}}return i||(await Promise.all(w),await Promise.all(c.map(e=>C(e)))),{success:!0,scannedFiles:u,removedFiles:d,removedBytes:p,removedByAge:m,removedBySize:h,remainingFiles:g.length,remainingBytes:g.reduce((e,t)=>e+t.size,0),dryRun:i,directories:c,...o.length>0?{categories:o}:{},...s.length>0?{excludeCategories:s}:{},removedSample:v,config:n}}function y(){let t=_();if(!t.enabled||t.cleanupIntervalMinutes<=0)return null;let n=setInterval(()=>{v().then(t=>{t.removedFiles>0&&e.info(`[artifacts] retention cleanup removed ${t.removedFiles} files (${t.removedBytes} bytes)`)}).catch(t=>{e.warn(`[artifacts] retention cleanup failed`,t)})},t.cleanupIntervalMinutes*60*1e3);return n.unref(),()=>clearInterval(n)}function b(e){if((e?.categories?.length??0)>0||(e?.excludeCategories?.length??0)>0){let t=e?.categories&&e.categories.length>0?e.categories:[...g],n=new Set(e?.excludeCategories??[]);return t.filter(e=>!n.has(e)).map(e=>s(e))}let t=a(),n=u(process.cwd(),`debugger-sessions`),r=u(t,`debugger-sessions`),l=new Set([c(),i().paths.screenshotDir,o(),n,r]);for(let e of g)l.add(s(e));return[...l]}function x(e){if(!e||e.length===0)return[];let t=new Set(g),n=[];for(let r of e)t.has(r)&&!n.includes(r)&&n.push(r);return n}async function S(e,t,n,r,i){let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=l(e,o.name);if(o.isDirectory())await S(a,t,n,r,i);else if(o.isFile()){let e;try{e=await p(a)}catch{continue}i({path:a,relativePath:w(t,a),size:e.size,mtimeMs:e.mtimeMs})}}}async function C(e){let t;try{t=await d(e,{withFileTypes:!0})}catch{return}await Promise.all(t.filter(e=>e.isDirectory()).map(t=>C(l(e,t.name))));try{(await d(e)).length===0&&await f(e,{recursive:!0,force:!0})}catch{}}function w(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^[\\/]/,``).replace(/\\/g,`/`):t.replace(/\\/g,`/`)}export{m as a,h as i,_ as n,y as r,v as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{i as t}from"./outputPaths-CHtELDyi.mjs";import{isAbsolute as n,normalize as r,relative as i,resolve as a,sep as o}from"node:path";import{mkdir as s}from"node:fs/promises";var c=e({getArtifactDir:()=>f,getArtifactsRoot:()=>d,resolveArtifactPath:()=>u});const l=`artifacts`;async function u(e){let{category:c,toolName:u,target:d,ext:f,customDir:m}=e,h=t(),g=m?a(h,m):a(h,l,c),_=i(r(h),r(g));if(_===`..`||_.startsWith(`..${o}`)||n(_))throw Error(`Path traversal blocked: artifact directory "${m}" escapes project root`);await s(g,{recursive:!0});let v=new Date().toISOString().replace(/[:.]/g,`-`).replace(`T`,`_`).slice(0,19),y=Math.random().toString(36).substring(2,8),b=a(g,`${p(u)}${d?`-${p(d)}`:``}-${v}-${y}.${f.replace(/^\./,``)}`);return{absolutePath:b,displayPath:i(h,b).replace(/\\/g,`/`)}}function d(){return a(t(),l)}function f(e){return a(t(),l,e)}function p(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_|_$/g,``).substring(0,60)}export{u as i,f as n,d as r,c as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-BGCcd-jJ.mjs";import{At as t,jt as n}from"./constants-nvsLpSri.mjs";import{parseExpression as r}from"@babel/parser";import*as i from"@babel/types";import{init as a}from"z3-solver";let o=null,s=!1,c=Promise.resolve();function l(){return s}function u(){return!t||s?Promise.resolve(null):(o||=f(a()).then(t=>(e.info(`[z3] WASM initialized`),t)).catch(t=>(s=!0,e.warn(`[z3] init failed, falling back to legacy solvers: ${m(t)}`),null)),o)}async function d(t,n){let r=await u();if(!r)return null;let i,a=new Promise(e=>{i=e}),o=c;c=a,await o;try{return await p(t(r),n)}catch(t){return e.warn(`[z3] withZ3 callback failed: ${m(t)}`),null}finally{i()}}function f(e){return new Promise((t,r)=>{let i=setTimeout(()=>{r(Error(`Z3 init timed out after ${n}ms`))},n);e.then(e=>{clearTimeout(i),t(e)},e=>{clearTimeout(i),r(e)})})}function p(e,t){return!t||t<=0?e:new Promise((n,r)=>{let i=setTimeout(()=>{r(Error(`Z3 call timed out after ${t}ms`))},t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}function m(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}var h=class extends Error{nodeType;constructor(e,t){super(e),this.nodeType=t,this.name=`AstBridgeError`}};function g(e,t,n,i){return y(r(e,{sourceType:`unambiguous`,errorRecovery:!1}),n,_(n,i))}function _(e,t){let n={int:new Map,bitvec:new Map,real:new Map,bool:new Map};for(let r of t)switch(r.type){case`int`:n.int.set(r.name,e.Int.const(r.name));break;case`bitvec`:n.bitvec.set(r.name,e.BitVec.const(r.name,r.bits??64));break;case`real`:n.real.set(r.name,e.Real.const(r.name));break;case`bool`:n.bool.set(r.name,e.Bool.const(r.name));break}return n}function v(e,t){return e.int.get(t)??e.bitvec.get(t)??e.real.get(t)??e.bool.get(t)??null}function y(e,t,n){if(i.isNumericLiteral(e))return t.Int.val(e.value);if(i.isBooleanLiteral(e))return t.Bool.val(e.value);if(i.isIdentifier(e)){let t=v(n,e.name);if(t===null)throw new h(`Undeclared variable: ${e.name}`,e.type);return t}if(i.isParenthesizedExpression(e))return y(e.expression,t,n);if(i.isUnaryExpression(e)){let r=y(e.argument,t,n);if(e.operator===`!`)return x(r,`not`);if(e.operator===`-`)return x(r,`neg`);if(e.operator===`+`)return r;throw new h(`Unsupported unary operator: ${e.operator}`,e.type)}if(i.isBinaryExpression(e)){let r=y(e.left,t,n),i=y(e.right,t,n);switch(e.operator){case`+`:return b(r,`add`,i);case`-`:return b(r,`sub`,i);case`*`:return b(r,`mul`,i);case`/`:return b(r,`div`,i);case`%`:return b(r,`mod`,i);case`<`:return b(r,`lt`,i);case`>`:return b(r,`gt`,i);case`<=`:return b(r,`le`,i);case`>=`:return b(r,`ge`,i);case`==`:case`===`:return b(r,`eq`,i);case`!=`:case`!==`:return b(r,`neq`,i);default:throw new h(`Unsupported binary operator: ${e.operator}`,e.type)}}if(i.isLogicalExpression(e)){let r=y(e.left,t,n),i=y(e.right,t,n);if(e.operator===`&&`)return b(r,`and`,i);if(e.operator===`||`)return b(r,`or`,i);throw new h(`Unsupported logical operator: ${e.operator}`,e.type)}throw new h(`Unsupported node type: ${e.type}`,e.type)}function b(e,t,n){let r=e?.[t];if(typeof r!=`function`)throw new h(`Operand does not support .${t}() — likely type mismatch (got ${e===null?`null`:typeof e}: ${String(Object.getPrototypeOf(e??Object.prototype)?.constructor?.name??`?`)})`,`BinaryExpression`);return r.call(e,n)}function x(e,t){let n=e?.[t];if(typeof n!=`function`)throw new h(`Operand does not support .${t}() — likely type mismatch (got ${e===null?`null`:typeof e})`,`UnaryExpression`);return n.call(e)}export{d as i,g as n,l as r,h as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as e from"@babel/parser";import t from"@babel/traverse";import n from"@babel/generator";import*as r from"@babel/types";const i=t.default??t,a=n.default??n;function o(t,n={}){return e.parse(t,{sourceType:n.sourceType??`unambiguous`,plugins:n.plugins??[`jsx`,`typescript`]})}function s(e,t){i(e,t)}function c(e,t={}){return a(e,t).code}export{s as a,r as i,c as n,o as r,a as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";const t=e(import.meta.url),n=`pnpm add -O better-sqlite3@12.10.0`,r=`npm rebuild better-sqlite3 --foreground-scripts`;function i(e){return e instanceof Error?e.message:String(e)}function a(e){return/better-sqlite3|better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version/i.test(i(e))}function o(e){let t=i(e);return/Cannot find module 'better-sqlite3'|Cannot find package 'better-sqlite3'|better-sqlite3 is not installed/i.test(t)?`missing`:/better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version|module was compiled against/i.test(t)?`abi-mismatch`:`load-failed`}function s(e){let t=o(e),a=i(e);return t===`missing`?`GRACEFUL: better-sqlite3 is not installed. Install the optional trace backend with \`${n}\`.`:t===`abi-mismatch`?`GRACEFUL: better-sqlite3 is installed but its native binary is incompatible with the current Node.js runtime (${process.version}, ABI ${process.versions.modules}). Rebuild it with \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`:`GRACEFUL: better-sqlite3 failed to initialize. Try \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`}function c(){try{return t(t.resolve(`better-sqlite3/package.json`)).version??null}catch{return null}}function l(){let e=c();if(!e)return{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:null,issue:`missing`};try{let n=new(t(
|
|
1
|
+
import{createRequire as e}from"node:module";const t=e(import.meta.url),n=`pnpm add -O better-sqlite3@12.10.0`,r=`npm rebuild better-sqlite3 --foreground-scripts`;function i(e){return e instanceof Error?e.message:String(e)}function a(e){return/better-sqlite3|better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version/i.test(i(e))}function o(e){let t=i(e);return/Cannot find module 'better-sqlite3'|Cannot find package 'better-sqlite3'|better-sqlite3 is not installed/i.test(t)?`missing`:/better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version|module was compiled against/i.test(t)?`abi-mismatch`:`load-failed`}function s(e){let t=o(e),a=i(e);return t===`missing`?`GRACEFUL: better-sqlite3 is not installed. Install the optional trace backend with \`${n}\`.`:t===`abi-mismatch`?`GRACEFUL: better-sqlite3 is installed but its native binary is incompatible with the current Node.js runtime (${process.version}, ABI ${process.versions.modules}). Rebuild it with \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`:`GRACEFUL: better-sqlite3 failed to initialize. Try \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`}function c(){try{return t(t.resolve(`better-sqlite3/package.json`)).version??null}catch{return null}}function l(){let e=c();if(!e)return{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:null,issue:`missing`};try{let n=new(t("better-sqlite3"))(`:memory:`);try{n.prepare(`SELECT 1 AS ok`).get()}finally{n.close()}return{status:`ok`,detail:`installed (${e}) — native trace backend healthy`,version:e}}catch(t){let r=o(t);return r===`missing`?{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:e,issue:r}:{status:`warn`,detail:`installed (${e}) but ${s(t)}`,version:e,issue:r}}}export{a as n,l as r,s as t};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{t}from"./logger-BGCcd-jJ.mjs";import{ft as n,nt as r,rt as i}from"./constants-nvsLpSri.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{t as o}from"./ToolProbe-B02GC3ZY.mjs";import{v as s}from"./ensure-browser-core-BP70x0TB.mjs";import{tmpdir as c}from"node:os";import{constants as l}from"node:fs";import{basename as u,dirname as d,isAbsolute as f,join as p,normalize as m,resolve as h}from"node:path";import{access as g,mkdtemp as _,readFile as v,readdir as y,rm as b,stat as x,writeFile as S}from"node:fs/promises";import{createHash as C,randomUUID as w}from"node:crypto";import{execFile as T}from"node:child_process";var E=class{sessions=new Map;activeSessionId;fridaProbe;probePromise;async attach(e){let t=await this.getAvailability();if(!t.available)throw new s(t.reason??`Frida CLI is not available`);let n=await this.runFridaCommand(e,`console.log("__frida_attach_ok__");`);if(n.error)throw new a(`CONNECTION`,n.error);let r=w(),i={id:r,target:e,pid:this.resolvePid(e),status:`attached`,mode:`attach`,attachedAt:new Date().toISOString()};return this.sessions.set(r,i),this.activeSessionId=r,r}async spawn(e){let t=await this.getAvailability();if(!t.available)throw new s(t.reason??`Frida CLI is not available`);let n=await this.runFridaCommandWithArgs(e,this.buildSpawnTargetArgs(e),`console.log("__frida_spawn_ok__");`);if(n.error)throw new a(`CONNECTION`,n.error);let r=w(),i={id:r,target:e,pid:null,status:`attached`,mode:`spawn`,resumed:!1,attachedAt:new Date().toISOString()};return this.sessions.set(r,i),this.activeSessionId=r,r}async detach(){let e=this.getActiveSessionRecord();e&&(e.status=`detached`,this.activeSessionId=void 0)}async executeScript(e){let t=this.requireActiveSession(),n=await this.runFridaCommandForSession(t,e);return n.error&&(t.status=`error`,t.lastError=n.error),n}async resume(e){if(e&&!this.useSession(e))throw new s(`Unknown Frida session: ${e}`);let t=this.requireActiveSession(),n=await this.runFridaCommandForSession(t,[`const resume = Process.resume;`,`if (typeof resume === "function") {`,` resume();`,` console.log("__frida_resume_ok__");`,`} else {`,` console.log("__frida_resume_unavailable__");`,`}`].join(`
|
|
2
|
+
`));return n.error?(t.status=`error`,t.lastError=n.error):t.resumed=!0,n}async enumerateModules(){let e=this.requireActiveSession(),t=await this.runFridaCommandForSession(e,`console.log(JSON.stringify(Process.enumerateModules()));`),n=this.parseModuleList(t.output);return n.length>0?n:(t.error&&(e.status=`error`,e.lastError=t.error),[])}async enumerateFunctions(e){let t=this.requireActiveSession(),n=JSON.stringify(e),r=await this.runFridaCommandForSession(t,[`const entries = Process.getModuleByName(${n}).enumerateExports()`,`.filter(function (entry) { return entry.type === "function"; })`,`.map(function (entry) {`,` return { name: entry.name, address: String(entry.address), size: 0 };`,`});`,`console.log(JSON.stringify(entries));`].join(``)),i=this.parseFunctionList(r.output);return i.length>0?i:(r.error&&(t.status=`error`,t.lastError=r.error),[])}async findSymbols(e){let t=this.requireActiveSession(),n=e.trim(),r=n.includes(`:`)?n:n.includes(`!`)?`exports:${n}`:`exports:*!${n}*`,i=JSON.stringify(r),a=await this.runFridaCommandForSession(t,[`const resolver = new ApiResolver("module");`,`const matches = resolver.enumerateMatches(${i});`,`const mapped = matches.map(function (entry) {`,` const resolvedName = typeof entry.name === "string" ? entry.name : "unknown";`,` const resolvedAddress = entry.address ? String(entry.address) : "0x0";`,` return { name: resolvedName, address: resolvedAddress, demangled: resolvedName };`,`});`,`console.log(JSON.stringify(mapped));`].join(``)),o=this.parseSymbolList(a.output);return o.length>0?o:(a.error&&(t.status=`error`,t.lastError=a.error),[])}async memoryScan(e,t={}){let n=this.requireActiveSession(),r=e.trim();if(r.length===0)return[];let i=JSON.stringify(r),a=Math.max(1,Math.min(t.max??1e3,1e4)),o=[];if(t.address&&typeof t.size==`number`&&t.size>0){let e=JSON.stringify(t.address),n=Math.min(t.size,64*1024*1024);o.push(`var ranges = [{ base: ptr(${e}), size: ${n} }];`)}else if(t.moduleName){let e=JSON.stringify(t.moduleName);o.push(`var mod = Process.getModuleByName(${e});`,`var ranges = [{ base: mod.base, size: mod.size }];`)}else o.push(`var ranges = Process.enumerateRanges({ protection: 'r--', coalesce: false });`);let s=await this.runFridaCommandForSession(n,[...o,`var results = [];`,`var max = ${a};`,`for (var i = 0; i < ranges.length && results.length < max; i++) {`,` try {`,` Memory.scanSync(ranges[i].base, ranges[i].size, ${i}).forEach(function (m) {`,` if (results.length < max) results.push({ address: String(m.address), size: m.size });`,` });`,` } catch (e) { /* range not readable, skip */ }`,`}`,`console.log(JSON.stringify(results));`].join(`
|
|
3
|
+
`)),c=this.parseMemoryMatchList(s.output);return c.length>0?c:(s.error&&(n.status=`error`,n.lastError=s.error),[])}async memoryRead(e,t){let n=this.requireActiveSession(),r=e.trim(),i=JSON.stringify(r),a=Math.max(1,Math.min(t,65536)),o=await this.runFridaCommandForSession(n,[`var buf = ptr(${i}).readByteArray(${a});`,`var view = new Uint8Array(buf);`,`var hex = "";`,`for (var i = 0; i < view.length; i++) {`,` hex += ("00" + view[i].toString(16)).slice(-2);`,`}`,`console.log(JSON.stringify({ address: ${i}, size: ${a}, hex: hex }));`].join(`
|
|
4
|
+
`));return this.parseMemoryReadResult(o.output,r,a)||(o.error&&(n.status=`error`,n.lastError=o.error),{address:r,size:a,hex:``})}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,target:e.target,pid:e.pid,status:e.status,mode:e.mode,resumed:e.resumed}))}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.fridaProbe)return this.fridaProbe;this.probePromise||=o(`frida`);let e=await this.probePromise;return this.fridaProbe=e,this.probePromise=void 0,e}useSession(e){return this.sessions.has(e)?(this.activeSessionId=e,!0):!1}hasSession(e){return this.sessions.has(e)}getSessionDiagnostics(e){let t=this.sessions.get(e);if(t)return{status:t.status,lastError:t.lastError}}getActiveSessionRecord(){if(this.activeSessionId)return this.sessions.get(this.activeSessionId)}requireActiveSession(){let e=this.getActiveSessionRecord();if(!e)throw new s(`No active Frida session. Call attach() first.`);return e}resolvePid(e){if(!/^\d+$/.test(e))return null;let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}async runFridaCommand(e,t){return this.runFridaCommandWithArgs(e,this.buildTargetArgs(e),t)}async runFridaCommandForSession(e,t){let n=e.mode===`spawn`&&e.resumed!==!0?this.buildSpawnTargetArgs(e.target):this.buildTargetArgs(e.target);return this.runFridaCommandWithArgs(e.target,n,t)}async runFridaCommandWithArgs(e,n,i){let a=await this.getAvailability();if(!a.available)return{output:``,error:a.reason??`Frida CLI is not available`};let o=a.path??`frida`,s=[...n,`--runtime=v8`,`-q`,`-e`,i];try{let e=await this.execFileUtf8(o,s,r),t=e.stdout.trim(),n=e.stderr.trim();return n?{output:t,error:n}:{output:t}}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Frida command failed`,{target:e,message:r}),{output:``,error:r}}}buildSpawnTargetArgs(e){return[`-f`,e]}buildTargetArgs(e){return/^\d+$/.test(e)?[`-p`,e]:e.includes(`/`)||e.includes(`\\`)?[`-f`,e]:[`-n`,e]}parseModuleList(e){let t=this.extractJsonData(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.readStringField(e,`path`),i=this.normalizeHex(e.base),a=this.readNumberField(e,`size`);!t||!r||!i||a===void 0||n.push({name:t,base:i,size:a,path:r})}return n}parseFunctionList(e){let t=this.extractJsonData(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readNumberField(e,`size`)??0;!t||!r||n.push({name:t,address:r,size:i})}return n}parseSymbolList(e){let t=this.extractJsonData(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readStringField(e,`demangled`);!t||!r||(i?n.push({name:t,address:r,demangled:i}):n.push({name:t,address:r}))}return n}parseMemoryMatchList(e){let t=this.extractJsonData(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.normalizeHex(e.address),r=this.readNumberField(e,`size`)??0;t&&n.push({address:t,size:r})}return n}parseMemoryReadResult(e,t,n){let r=this.extractJsonData(e);if(!this.isRecord(r))return;let i=this.readStringField(r,`hex`);if(i!==void 0)return{address:this.normalizeHex(r.address)??t,size:this.readNumberField(r,`size`)??n,hex:i}}extractJsonData(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.startsWith(`{`)||e.startsWith(`[`)).toReversed();for(let e of t)try{return JSON.parse(e)}catch{continue}}readStringField(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}readNumberField(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}normalizeHex(e){if(typeof e==`number`&&Number.isFinite(e))return`0x${e.toString(16)}`;if(typeof e==`string`&&e.length>0)return e.startsWith(`0x`)?e:`0x${e}`}isRecord(e){return typeof e==`object`&&!!e}execFileUtf8(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:5242880,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}};const D=[`GHIDRA_HEADLESS_PATH`,`GHIDRA_ANALYZE_HEADLESS`],O=[`GHIDRA_HOME`,`GHIDRA_INSTALL_DIR`],k=process.platform===`win32`?[`analyzeHeadless.bat`,`analyzeHeadless.cmd`]:[`analyzeHeadless`];var A=class e{ghidraProbe;probePromise;analysisCache=new Map;static CACHE_TTL_MS=1800*1e3;discoveryPaths;constructor(e={}){this.discoveryPaths=e.discoveryPaths??N()}async analyze(e,n){await g(e);let r=await v(e),a=this.extractPrintableStrings(r),o=this.deriveImports(a),l=this.deriveExports(a),u=await this.getAvailability();if(!u.available)throw new s([`Ghidra analyzeHeadless is not available: ${u.reason||`not found on PATH`}`,`Install Ghidra and add analyzeHeadless to your PATH.`,`Windows: add <ghidra>/support to PATH. Linux/macOS: add <ghidra_install_dir>/support to PATH.`].join(` `));if(!n?.forceRefresh){let n=this.getCachedResult(e,r);if(n)return t.info(`[binary-instrument] Returning cached Ghidra analysis for ${e}`),{...n,strings:a,imports:o,exports:l}}let d=typeof n?.timeout==`number`&&Number.isFinite(n.timeout)?n.timeout:i,f=await _(p(c(),`jshook-ghidra-script-`)),m=p(f,`BinaryInstrumentDump.java`);try{await S(m,this.buildDefaultScript(),`utf8`);let t=await this.headlessAnalyze(m,e,d),n={functions:this.parseDecompiledOutput(t),imports:o,exports:l,strings:a};return this.cacheResult(e,r,n),n}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Ghidra analyze fallback`,{binaryPath:e,message:r}),{functions:[],imports:o,exports:l,strings:a}}finally{await b(f,{recursive:!0,force:!0})}}async analyzeBatch(e,n){let r=new Map;for(let i of e)try{let e=await this.analyze(i,n);r.set(i,e)}catch(e){let n=e instanceof Error?e.message:String(e);t.warn(`[binary-instrument] Batch analysis failed for ${i}`,{message:n}),r.set(i,{functions:[],imports:[],exports:[],strings:[]})}return r}async runCustomScript(e,t,n){let r=await this.getAvailability();if(!r.available)throw new s([`Ghidra analyzeHeadless is not available: ${r.reason||`not found on PATH`}`,`Install Ghidra and add analyzeHeadless to your PATH.`].join(` `));await g(e);let a=await _(p(c(),`jshook-ghidra-custom-`)),o=p(a,L(t,n?.language??I(t)));try{return await S(o,t,`utf8`),await this.headlessAnalyze(o,e,n?.timeout??i)}finally{await b(a,{recursive:!0,force:!0})}}async headlessAnalyze(e,t,n=i){let r=await this.getAvailability();if(!r.available)throw new s(r.reason??`Ghidra analyzeHeadless is not available`);await g(t),await g(e);let a=r.path??`analyzeHeadless`,o=await _(p(c(),`jshook-ghidra-project-`));try{let r=await this.execFileUtf8(a,[o,`binary-instrument`,`-import`,t,`-scriptPath`,d(e),`-postScript`,u(e)],n);return[r.stdout.trim(),r.stderr.trim()].filter(e=>e.length>0).join(`
|
|
5
|
+
`)}finally{await b(o,{recursive:!0,force:!0})}}parseDecompiledOutput(e){let t=[],n=F(e),r=/FUNCTION_START\s*[\r\n]+NAME:(.+?)\s*[\r\n]+ADDRESS:(.+?)\s*[\r\n]+SIGNATURE:(.+?)\s*[\r\n]+DECOMPILED_START\s*[\r\n]+([\s\S]*?)\s*[\r\n]+DECOMPILED_END\s*[\r\n]+FUNCTION_END/g,i=r.exec(n);for(;i;){let e=i[1]??``,a=i[2]??``,o=i[3]??``,s=i[4]??``,c=e.trim(),l=this.normalizeHex(a.trim()),u=o.trim(),d=s.trim();c.length>0&&l.length>0&&u.length>0&&t.push({name:c,address:l,signature:u,decompiled:d}),i=r.exec(n)}return t}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.ghidraProbe)return this.ghidraProbe;this.probePromise||=this.probeAnalyzeHeadless();let e=await this.probePromise;return this.ghidraProbe=e,this.probePromise=void 0,e}async probeAnalyzeHeadless(){return await this.resolveFromEnvironment()||await this.resolveFromDiscoveryPaths()||o(`analyzeHeadless`,[`-help`])}async resolveFromEnvironment(){for(let e of D){let t=process.env[e]?.trim();if(!t)continue;let n=await this.probeCandidate(t,e);if(n)return n}for(let e of O){let t=process.env[e]?.trim();if(!t)continue;let n=await this.probeHomeDirectory(t,e);if(n)return n}return null}async resolveFromDiscoveryPaths(){for(let e of this.discoveryPaths){let t=await this.probeHomeDirectory(e,`auto-discovery`);if(t)return t;for(let t of await M(e)){let e=await this.probeHomeDirectory(t,`auto-discovery`);if(e)return e}}return null}async probeHomeDirectory(e,t){let n=j(e);for(let e of n){let n=await this.probeCandidate(e,t);if(n)return n}return null}async probeCandidate(e,t){let n=m(e);if(!(await x(n).catch(()=>null))?.isFile())return null;try{await g(n,l.X_OK)}catch{try{await g(n,l.R_OK)}catch{return null}}return{available:!0,path:n,version:`analyzeHeadless (${t})`}}buildDefaultScript(){return[`// @category BinaryInstrument`,`import ghidra.app.decompiler.DecompInterface;`,`import ghidra.app.decompiler.DecompileResults;`,`import ghidra.app.script.GhidraScript;`,`import ghidra.program.model.listing.Function;`,`import ghidra.program.model.listing.FunctionIterator;`,``,`public class BinaryInstrumentDump extends GhidraScript {`,` @Override`,` public void run() throws Exception {`,` DecompInterface decompiler = new DecompInterface();`,` decompiler.openProgram(currentProgram);`,``,` try {`,` FunctionIterator functions = currentProgram.getFunctionManager().getFunctions(true);`,` while (functions.hasNext()) {`,` Function function = functions.next();`,` emit("FUNCTION_START");`,` emit("NAME:" + function.getName());`,` emit("ADDRESS:" + function.getEntryPoint().toString());`,` emit("SIGNATURE:" + getSignature(function));`,` emit("DECOMPILED_START");`,` emit(decompileFunction(decompiler, function));`,` emit("DECOMPILED_END");`,` emit("FUNCTION_END");`,` }`,` } finally {`,` decompiler.dispose();`,` }`,` }`,``,` private void emit(String value) {`,` System.out.println(value);`,` }`,``,` private String getSignature(Function function) {`,` try {`,` return function.getSignature().toString();`,` } catch (Exception ignored) {`,` return function.getName() + "()";`,` }`,` }`,``,` private String decompileFunction(DecompInterface decompiler, Function function) {`,` try {`,` DecompileResults results = decompiler.decompileFunction(function, 30, monitor);`,` if (results != null && results.decompileCompleted() && results.getDecompiledFunction() != null) {`,` return results.getDecompiledFunction().getC();`,` }`,` return "// no decompiled output";`,` } catch (Exception error) {`,` return "// decompile failed: " + error.getMessage();`,` }`,` }`,`}`].join(`
|
|
6
|
+
`)}extractPrintableStrings(e){let t=[],n=``;for(let r of e.values()){if(r>=32&&r<=126){n+=String.fromCharCode(r);continue}n.length>=4&&t.push(n),n=``}return n.length>=4&&t.push(n),Array.from(new Set(t)).slice(0,1e3)}deriveImports(e){return e.filter(e=>/(?:\.dll|\.so|\.dylib|kernel32|user32|libc|printf|malloc|LoadLibrary)/i.test(e)).slice(0,100)}deriveExports(e){return e.filter(e=>/^[A-Za-z_][A-Za-z0-9_@?$]{2,}$/.test(e)).slice(0,100)}normalizeHex(e){return e.startsWith(`0x`)?e:`0x${e}`}getCachedResult(t,n){let r=this.analysisCache.get(t);return r?Date.now()-r.analyzedAt>e.CACHE_TTL_MS||this.computeHash(n)!==r.hash?(this.analysisCache.delete(t),null):{...r.result}:null}cacheResult(e,t,n){if(this.analysisCache.set(e,{hash:this.computeHash(t),fileSize:t.length,analyzedAt:Date.now(),result:n}),this.analysisCache.size>20){let e=``,t=1/0;for(let[n,r]of this.analysisCache.entries())r.analyzedAt<t&&(t=r.analyzedAt,e=n);e&&this.analysisCache.delete(e)}}computeHash(e){return C(`sha256`).update(e).digest(`hex`).substring(0,32)}execFileUtf8(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:16777216,encoding:`utf8`,shell:P(e)},(e,t,n)=>{if(e){let r=[typeof t==`string`&&t.trim()?`stdout:\n${t.trim()}`:``,typeof n==`string`&&n.trim()?`stderr:\n${n.trim()}`:``].filter(e=>e.length>0).join(`
|
|
7
|
+
`);r&&e instanceof Error&&(e.message=`${e.message}\n${r}`),i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}};function j(e){let t=m(e),n=f(t)?t:h(t),r=[n];for(let e of k)r.push(p(n,e)),r.push(p(n,`support`,e));return Array.from(new Set(r))}async function M(e){try{return(await y(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/ghidra/i.test(e.name)).slice(0,20).map(t=>p(e,t.name))}catch{return[]}}function N(){let e=new Set,t=t=>{t&&t.trim().length>0&&e.add(t.trim())};return t(process.cwd()),t(process.env.USERPROFILE),t(process.env.HOME),process.platform===`win32`?(t(process.env.ProgramFiles),t(process.env[`ProgramFiles(x86)`]),t(`C:\\tools`)):(t(`/opt`),t(`/usr/local`),t(`/Applications`)),Array.from(e)}function P(e){return process.platform===`win32`&&/\.(?:bat|cmd)$/i.test(e)}function F(e){return e.split(/\r?\n/).map(e=>{let t=/^(?:INFO|WARN|ERROR)\s+[^>]+>\s*(.*)$/.exec(e);return t?(t[1]??``).replace(/\s+\(GhidraScript\)\s*$/,``):e}).join(`
|
|
8
|
+
`)}function I(e){return/\bextends\s+GhidraScript\b/.test(e)||/\bimport\s+ghidra\./.test(e)||/\bpublic\s+class\s+\w+\b/.test(e)?`java`:`python`}function L(e,t){return t===`python`?`custom_script.py`:`${/\bpublic\s+class\s+([A-Za-z_$][\w$]*)\b/.exec(e)?.[1]??`CustomScript`}.java`}var R=class{generateHooks(e){let t=[];for(let n of e.functions){let r=this.classifyFunction(n,e);r!==`unknown`&&t.push({functionName:n.name,description:this.describeCategory(r,e),hookCode:this.buildHookCode(n,r),parameters:this.buildParameters(n)})}return t}exportScript(e,t){if(t!==`frida`)throw new a(`VALIDATION`,`Unsupported export format: "${t}". Only "frida" is supported.`);let n=[`// Frida hook script`,`// auto-generated by HookCodeGenerator`,`// Hook count: ${e.length}`,``];for(let t of e)n.push(`// ${t.functionName}: ${t.description}`),n.push(t.hookCode),n.push(``);return n.join(`
|
|
9
|
+
`)}classifyFunction(e,t){let n=e.name.toLowerCase(),r=t.imports.map(e=>e.toLowerCase()),i=t.strings.map(e=>e.toLowerCase());return e.name.startsWith(`Java_`)?`jni`:n.includes(`aes`)?`aes`:n.includes(`md5`)?`md5`:n.includes(`sha`)?`sha`:n.includes(`rsa`)?`rsa`:n.includes(`base64`)?`base64`:n.includes(`send`)||n.includes(`recv`)||n.includes(`socket`)||n.includes(`http`)?`network`:n.includes(`open`)||n.includes(`read`)||n.includes(`write`)||n.includes(`fopen`)?`file-io`:(n.includes(`decrypt`)||n.includes(`encrypt`))&&i.some(e=>e.includes(`obfuscation`)||e.includes(`encryption`))?`obfuscation`:n.includes(`memcpy`)||n.includes(`strcpy`)||n.includes(`memmove`)||n.includes(`string`)?`string`:r.some(e=>e.includes(`aes`))?`aes`:`unknown`}describeCategory(e,t){switch(e){case`jni`:return`JNI bridge hook for Java/native boundary inspection`;case`aes`:return`AES crypto hook for key/plaintext capture`;case`md5`:return`MD5 crypto hook for digest inspection`;case`sha`:return`SHA crypto hook for digest inspection`;case`rsa`:return`RSA crypto hook for key operation tracing`;case`base64`:return`Base64 transform hook for encoded data tracing`;case`network`:return`Network hook for request and response body tracing`;case`file-io`:return`File I/O hook for filesystem access tracing`;case`string`:return`String operation hook for buffer tracing`;case`obfuscation`:return t.strings.some(e=>e.toLowerCase().includes(`obfuscation`))?`Potential obfuscation hook for runtime string decryption tracing`:`Potential obfuscation hook`;case`unknown`:return`Unknown hook`}}buildHookCode(e,t){if(t===`jni`)return[`Java.perform(function () {`,` const target = ptr("${e.address}");`,` Interceptor.attach(target, {`,` onEnter(args) {`,` console.log("[jni] ${e.name}");`,` },`,` });`,`});`].join(`
|
|
10
|
+
`);let n=t===`aes`||t===`md5`||t===`sha`||t===`rsa`||t===`base64`?` console.log(hexdump(args[0]));`:` console.log("[trace] entering");`,r=e.name.replace(/[^A-Za-z0-9_]/g,`_`);return[`const target_${r} = ptr("${e.address}");`,`Interceptor.attach(target_${r}, {`,` onEnter(args) {`,` console.log("[hook] ${e.name}");`,n,` },`,`});`].join(`
|
|
11
|
+
`)}buildParameters(e){return e.parameters.length>0?e.parameters.map((e,t)=>({name:e.name||`arg${t}`,type:e.type||`pointer`,description:`Captured parameter ${t}`})):[{name:`arg0`,type:`pointer`,description:`Captured parameter 0`}]}};async function z(e,t){let n=B(e),r=V(t.pluginId),i=H(r,n);if(!i)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${r} is not installed`};let a=U(e,i);if(!a?.lifecycleContext)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${i} is installed but has no runtime`};try{let e=(await a.lifecycleContext.invokeTool(t.toolName,t.args)).content?.find(e=>e.type===`text`)?.text;if(!e)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin returned no text content`};try{let n=JSON.parse(e);if(G(n))return{tool:`binary-instrument`,action:t.toolName,success:K(n,`success`)??!0,data:n.data,error:q(n,`error`)}}catch{return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}catch(e){return{success:!1,tool:`binary-instrument`,action:t.toolName,error:e instanceof Error?e.message:String(e)}}}function B(e){return Array.from(e.extensionPluginsById.keys()).map(V)}function V(e){return e.replaceAll(`_`,`-`)}function H(e,t){let n=e.replace(/^plugin-/,``);for(let r of t){let t=r.replace(/^plugin-/,``);if(r===e||t===n)return r}}function U(e,t){for(let[n,r]of e.extensionPluginRuntimeById.entries())if(V(n)===t)return W(r)?r:void 0}function W(e){return typeof e==`object`&&!!e}function G(e){return typeof e==`object`&&!!e}function K(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function q(e,t){let n=e[t];return typeof n==`string`?n:void 0}var J=class{generateFridaHookScript(e,t){let n=t?.includeArgs??!0,r=t?.includeRetAddr??!1,i=[`'use strict';`,``,`function resolveTarget(name) {`,` try {`,` const exported = Module.findExportByName(null, name);`,` if (exported) {`,` return exported;`,` }`,` } catch (error) {}`,` try {`,` const symbol = DebugSymbol.fromName(name);`,` if (symbol && symbol.address) {`,` return symbol.address;`,` }`,` } catch (error) {}`,` return null;`,`}`,``,`const installedHooks = [];`];for(let t=0;t<e.length;t+=1){let a=this.toDescriptor(e[t]),o=`target_${t}`,s=a.demangled??a.name,c=a.address?`const ${o} = ptr("${this.escapeForDoubleQuotes(a.address)}");`:`const ${o} = resolveTarget("${this.escapeForDoubleQuotes(a.name)}");`;i.push(c),i.push(`if (${o}) {`),i.push(` Interceptor.attach(${o}, {`),i.push(` onEnter(args) {`),r?i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)} ret=" + this.returnAddress);`):i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)}");`),n&&(i.push(` const renderedArgs = [];`),i.push(` for (let i = 0; i < 6; i += 1) {`),i.push(` try {`),i.push(` renderedArgs.push(String(args[i]));`),i.push(` } catch (error) {`),i.push(` renderedArgs.push("<unreadable>");`),i.push(` }`),i.push(` }`),i.push(` console.log("[binary-instrument] args " + JSON.stringify(renderedArgs));`)),i.push(` },`),i.push(` onLeave(retval) {`),i.push(` console.log("[binary-instrument] leave ${this.escapeForDoubleQuotes(s)} retval=" + retval);`),i.push(` },`),i.push(` });`),i.push(` installedHooks.push({ name: "${this.escapeForDoubleQuotes(s)}", address: String(${o}) });`),i.push(`} else {`),i.push(` console.log("[binary-instrument] unresolved ${this.escapeForDoubleQuotes(s)}");`),i.push(`}`),i.push(``)}return i.push(`console.log("[binary-instrument] hooks=" + JSON.stringify(installedHooks));`),i.join(`
|
|
12
|
+
`)}generateInterceptorScript(e){return this.generateFridaHookScript(e,{includeArgs:!0,includeRetAddr:!1})}toDescriptor(e){return typeof e==`string`?{name:e}:e}escapeForDoubleQuotes(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}},Y=class{sessions=new Map;close(){for(let e of this.sessions.values())if(e.childProcess)try{process.kill(e.childProcess.pid,`SIGTERM`)}catch{}this.sessions.clear()}async launch(e,t=`arm`,r){let i=r??process.env.UNIDBG_JAR;if(!i)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var or pass jarPath.`);try{await g(i)}catch{throw new a(`NOT_FOUND`,`Unidbg JAR not found: ${i}`)}try{await g(e)}catch{throw new a(`NOT_FOUND`,`Shared library not found: ${e}`)}let o=w(),c=this.getJavaCommand(),l=[`-jar`,i,`--so`,e,`--arch`,t,`--server`];try{let r=await this.execFileUtf8(c,l,n),i=this.parseLaunchOutput(r.stdout,o),a={id:i.id,soPath:e,arch:t,startedAt:new Date().toISOString(),childProcess:i.pid?{pid:i.pid}:void 0};return this.sessions.set(o,a),{sessionId:o,soPath:e,arch:t}}catch(e){throw new a(`RUNTIME`,`Unidbg launch failed: ${e instanceof Error?e.message:String(e)}`)}}async callFunction(e,t,r={}){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let i=process.env.UNIDBG_JAR;if(!i)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var before calling Unidbg.`);let o=this.getJavaCommand(),c=[`-jar`,i,`--session`,e,`--call`,t,`--args`,JSON.stringify(r)];try{let i=await this.execFileUtf8(o,c,n);return{sessionId:e,functionName:t,args:r,returnValue:this.extractReturnValue(i.stdout),stdout:i.stdout.trim(),stderr:i.stderr.trim(),trace:[]}}catch(e){throw new a(`RUNTIME`,`Unidbg call failed: ${e instanceof Error?e.message:String(e)}`)}}async trace(e){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let t=process.env.UNIDBG_JAR;if(!t)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var before tracing Unidbg.`);let r=this.getJavaCommand(),i=[`-jar`,t,`--session`,e,`--trace`];try{let t=await this.execFileUtf8(r,i,n);return{sessionId:e,trace:this.parseTraceOutput(t.stdout),instructionCount:this.countInstructions(t.stdout)}}catch(e){throw new a(`RUNTIME`,`Unidbg trace failed: ${e instanceof Error?e.message:String(e)}`)}}getSessionInfo(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,soPath:e.soPath,arch:e.arch,startedAt:e.startedAt}))}getJavaCommand(){return process.env.JAVA_HOME?`${process.env.JAVA_HOME}/bin/java`:`java`}parseLaunchOutput(e,t){let n=e.split(/\r?\n/).filter(e=>e.trim().length>0);for(let e of n.toReversed())try{let t=JSON.parse(e);if(typeof t.id==`string`)return{id:t.id,pid:typeof t.pid==`number`?t.pid:null}}catch{}return{id:t,pid:null}}extractReturnValue(e){let t=/return[=:\s]+(0x[0-9a-fA-F]+|-?\d+)/.exec(e);return t?.[1]?t[1]:`0x0`}parseTraceOutput(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)).slice(0,1e4)}countInstructions(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)&&/\b(ldr|str|mov|bl|b|add|sub)\b/i.test(e)).length}async execFileUtf8(e,t,n){return new Promise((r,i)=>{T(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``,exitCode:0})})})}},X=e({GhidraAnalyzer:()=>A,HookGenerator:()=>J});export{z as a,E as c,B as i,Y as n,R as o,J as r,A as s,X as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-88NL7fhV.mjs";import{a as t}from"./constants-nvsLpSri.mjs";import{o as n}from"./outputPaths-CHtELDyi.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{dirname as a,resolve as o}from"node:path";import{mkdir as s,writeFile as c}from"node:fs/promises";import{createDecipheriv as l,randomUUID as u}from"node:crypto";function d(e){return e.replace(/\s+/g,``).toUpperCase()}function f(e){return e.length>0&&e.length%2==0&&/^[0-9A-F]+$/i.test(e)}function p(e){if(!e)return;let t=new Date(e);if(!Number.isNaN(t.valueOf()))return t.toISOString()}function m(){return o(n(),`jshook-boringssl-${u()}.log`)}function h(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(e.length===0||e.startsWith(`#`))continue;let r=e.split(/\s+/),i=r[0],a=r[1],o=r[2],s=p(r[3]);if(!i||!a||!o)continue;let c=d(a),l=d(o);if(!f(c)||!f(l))continue;let u={label:i,clientRandom:c,secret:l};s&&(u.timestamp=s),t.push(u)}return t}var g=class{keyLogPath;cachedEntries=[];secretByClientRandom=new Map;constructor(e){this.keyLogPath=o(e??m())}async enableKeyLog(){return await s(a(this.keyLogPath),{recursive:!0}),await c(this.keyLogPath,``,{flag:`a`}),process.env.SSLKEYLOGFILE=this.keyLogPath,this.keyLogPath}async disableKeyLog(){if(process.env.SSLKEYLOGFILE===this.keyLogPath){delete process.env.SSLKEYLOGFILE;return}delete process.env.SSLKEYLOGFILE}getKeyLogFilePath(){return this.keyLogPath}parseKeyLog(e){let t=o(e??this.keyLogPath);if(!r(t))return this.cachedEntries=[],this.secretByClientRandom.clear(),[];let n=h(i(t,`utf8`));this.cachedEntries=n,this.secretByClientRandom.clear();for(let e of n)this.secretByClientRandom.set(e.clientRandom,e.secret);return n}decryptPayload(e,t){return null}summarizeKeyLog(e){let t=this.parseKeyLog(e),n={},r=[];for(let e of t)n[e.label]=(n[e.label]??0)+1,e.timestamp&&r.push(e.timestamp);r.sort((e,t)=>e.localeCompare(t));let i={totalEntries:t.length,entriesByLabel:n};if(r.length>0){let e=r[0],t=r[r.length-1];e&&(i.firstSeen=e),t&&(i.lastSeen=t)}return i}lookupSecret(e){let t=d(e),n=this.secretByClientRandom.get(t);if(n)return n;for(let e of this.cachedEntries.length>0?this.cachedEntries:this.parseKeyLog())if(e.clientRandom===t)return e.secret;return null}};function _(e=t){return process.env.SSLKEYLOGFILE=e,e}function v(){delete process.env.SSLKEYLOGFILE}function y(){let e=process.env.SSLKEYLOGFILE;return!e||e.trim().length===0?null:e}function b(e){return e.length===0?[]:e.includes(`
|
|
2
|
+
`)||e.includes(`\r`)||e.includes(`CLIENT_`)||e.trim().startsWith(`#`)?h(e):new g(e).parseKeyLog()}function x(e){let t=[...new Set(e.map(e=>e.label))],n=new Set(e.map(e=>e.clientRandom)).size,r=e.some(e=>e.label.includes(`TRAFFIC_SECRET`));return{totalEntries:e.length,uniqueClients:n,hasClientRandom:t.includes(`CLIENT_RANDOM`),hasTrafficSecrets:r,labels:t}}function S(e){return e===`CLIENT_RANDOM`?`tls12-master-secret`:e===`CLIENT_HANDSHAKE_TRAFFIC_SECRET`||e===`SERVER_HANDSHAKE_TRAFFIC_SECRET`?`tls13-handshake-traffic`:e===`CLIENT_TRAFFIC_SECRET_0`||e===`SERVER_TRAFFIC_SECRET_0`?`tls13-app-traffic`:e===`EARLY_TRAFFIC_SECRET`?`tls13-early-data`:e===`EXPORTER_SECRET`?`tls13-exporter`:`other`}function C(e){let t={},n=new Set,r=new Map,i=new Map,a=!1,o=!1;for(let s of e){t[s.label]=(t[s.label]??0)+1,n.add(s.clientRandom),i.set(s.label,(i.get(s.label)??0)+1);let e=S(s.label);r.has(s.label)||r.set(s.label,e),e===`tls12-master-secret`&&(a=!0),e.startsWith(`tls13-`)&&(o=!0)}let s=[];for(let[e,t]of i)s.push({label:e,count:t,kind:r.get(e)??`other`});s.sort((e,t)=>t.count-e.count||e.label.localeCompare(t.label));let c;return c=e.length===0?`unknown`:a&&o?`mixed`:o?`TLS1.3`:a?`TLS1.2`:`unknown`,{totalEntries:e.length,uniqueClientRandom:n.size,entriesByLabel:t,secretTypes:s,tlsVersionInference:c,hasClientRandom:a,hasTrafficSecrets:o}}function w(e,t,n){let r=d(t),i=n?.trim();for(let t of e)if(t.clientRandom===r&&!(i&&t.label!==i))return t.secret;return null}function T(e,t,n,r=`aes-256-gcm`,i){try{let a=Buffer.from(d(e),`hex`),o=l(r,Buffer.from(d(t),`hex`),Buffer.from(d(n),`hex`));if(i){let e=Reflect.get(o,`setAuthTag`);typeof e==`function`&&e.call(o,Buffer.from(d(i),`hex`))}return Buffer.concat([o.update(a),o.final()]).toString(`utf8`)}catch{return`DECRYPTION_FAILED:${r}`}}const E=[{id:156,name:`TLS_RSA_WITH_AES_128_GCM_SHA256`},{id:157,name:`TLS_RSA_WITH_AES_256_GCM_SHA384`},{id:4865,name:`TLS_AES_128_GCM_SHA256`},{id:4866,name:`TLS_AES_256_GCM_SHA384`},{id:4867,name:`TLS_CHACHA20_POLY1305_SHA256`},{id:4868,name:`TLS_AES_128_CCM_SHA256`},{id:4869,name:`TLS_AES_128_CCM_8_SHA256`},{id:49161,name:`TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`},{id:49162,name:`TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`},{id:49171,name:`TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`},{id:49172,name:`TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`},{id:49195,name:`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`},{id:49196,name:`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`},{id:49199,name:`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`},{id:49200,name:`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`},{id:52392,name:`TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256`},{id:52393,name:`TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256`}];new Map(E.map(e=>[e.id,e]));function D(e){let t=[...E].toSorted((e,t)=>e.id-t.id);if(!e)return t;let n=e.toLowerCase();return t.filter(e=>e.name.toLowerCase().includes(n))}const O=[`GCM`,`CCM`,`POLY1305`],k=new Set([`SHA256`,`SHA384`,`SHA`,`MD5`,`NULL`]);function A(e){return O.some(t=>e.includes(t))}function j(e){if(e.length===0)return{encryption:e,mac:null};let t=e.split(`_`),n=t[t.length-1];if(n&&k.has(n)){let r=t.slice(0,-1).join(`_`);return{encryption:r.length>0?r:e,mac:n}}return{encryption:e,mac:null}}function M(e){let t=typeof e==`string`?e:e.name,n=typeof e==`string`?null:e.id??null,r=n===null?null:`0x${n.toString(16).padStart(4,`0`)}`,i=t.includes(`_WITH_`);if(!i&&t.startsWith(`TLS_`)){let{encryption:e,mac:i}=j(t.slice(4));return{id:n,idHex:r,name:t,protocol:`TLS1.3`,keyExchange:null,authentication:null,encryption:e,mac:i,aead:A(e)}}if(i){let[e,i]=t.slice(4).split(`_WITH_`),a=(e??``).split(`_`).filter(e=>e.length>0),o=a[0]??null,s=a.length>1?a[a.length-1]??null:a[0]??null,{encryption:c,mac:l}=j(i??``);return{id:n,idHex:r,name:t,protocol:`TLS1.2`,keyExchange:o,authentication:s,encryption:c,mac:l,aead:A(c)}}return{id:n,idHex:r,name:t,protocol:`unknown`,keyExchange:null,authentication:null,encryption:null,mac:null,aead:!1}}var N=e({TLSKeyLogExtractor:()=>g});export{C as a,_ as c,b as d,x as f,g as i,y as l,M as n,T as o,D as r,v as s,N as t,w as u};
|