@jshookmcp/jshook 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
- package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
- package/dist/CodeInjector-Btj9upnf.mjs +1 -0
- package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
- package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
- package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
- package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
- package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
- package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
- package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
- package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
- package/dist/MemoryScanner-Dxd657li.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
- package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
- package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
- package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
- package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
- package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
- package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
- package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
- package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
- package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
- package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
- package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
- package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
- package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
- package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
- package/dist/antidebug-CsnpOR9z.mjs +1 -0
- package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
- package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
- package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
- package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
- package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
- package/dist/browser-BUaB25bk.mjs +11 -0
- package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
- package/dist/collector-CB2syQEg.mjs +1 -0
- package/dist/constants-DMv3svps.mjs +2 -0
- package/dist/coordination-Dbohmj6D.mjs +1 -0
- package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
- package/dist/debugger-CLzkObIO.mjs +1 -0
- package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
- package/dist/definitions-B3a9QC2t.mjs +1 -0
- package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
- package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
- package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
- package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
- package/dist/definitions-DBYSxChX.mjs +1 -0
- package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
- package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
- package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
- package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
- package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
- package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
- package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
- package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
- package/dist/definitions-EGmqr85H.mjs +1 -0
- package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
- package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
- package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
- package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
- package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
- package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
- package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
- package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
- package/dist/handlers-6iNsXOVT.mjs +7 -0
- package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
- package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
- package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
- package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
- package/dist/handlers-CWKBBjai.mjs +1 -0
- package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
- package/dist/handlers-CrJsKnEI.mjs +1 -0
- package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
- package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
- package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
- package/dist/handlers-gVscChvl.mjs +1 -0
- package/dist/handlers-xFvI9P_y.mjs +1 -0
- package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
- package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
- package/dist/index.mjs +11 -11
- package/dist/macro-p8kuJVcm.mjs +2 -0
- package/dist/maintenance-DAqADb6Z.mjs +302 -0
- package/dist/manifest-4lmM6MZR.mjs +1 -0
- package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
- package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
- package/dist/manifest-Box-jWfr.mjs +1 -0
- package/dist/manifest-Bp33di0Q.mjs +1 -0
- package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
- package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
- package/dist/manifest-C7TdXCWY.mjs +1 -0
- package/dist/manifest-CM-n64K0.mjs +1 -0
- package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
- package/dist/manifest-CWJS45iO.mjs +1 -0
- package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
- package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
- package/dist/manifest-Cgxu2qdv.mjs +1 -0
- package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
- package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
- package/dist/manifest-CvDpVToN.mjs +1 -0
- package/dist/manifest-D8TL9RLE.mjs +1 -0
- package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
- package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
- package/dist/manifest-DLGtZH-0.mjs +1 -0
- package/dist/manifest-DXHdPt2T.mjs +1 -0
- package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
- package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
- package/dist/manifest-G2H52LKz.mjs +131 -0
- package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
- package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
- package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
- package/dist/manifest-dG6MuR1U.mjs +1 -0
- package/dist/manifest-nWXtgq5Y2.mjs +1 -0
- package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
- package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
- package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
- package/dist/native-g095qhpK.mjs +961 -0
- package/dist/network-Dvxm7eEI.mjs +7 -0
- package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
- package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
- package/dist/platform-DjWbuiF8.mjs +93 -0
- package/dist/process-Dq5I-KZW.mjs +2 -0
- package/dist/proxy-DPNgM7TE.mjs +2 -0
- package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
- package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
- package/dist/search-defaults-CJik67or.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/sourcemap-DqEW15Ao.mjs +1 -0
- package/dist/streaming-Dbk4eStJ.mjs +1 -0
- package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
- package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
- package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
- package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
- package/package.json +2 -2
- package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
- package/dist/DOMInspector-C19J4zeq.mjs +0 -95
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
- package/dist/ExtensionManager-BD724zkO.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
- 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/PageController-Dfsm1_o7.mjs +0 -1
- package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
- package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
- package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
- package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
- package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
- package/dist/VersionDetector-CHT36Az0.mjs +0 -9
- package/dist/apk-packer-BqXcInnX.mjs +0 -1
- package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
- package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
- 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-BftdXgXI.mjs +0 -1
- package/dist/definitions-Bio5XJYy.mjs +0 -1
- package/dist/definitions-CMZRSy3k.mjs +0 -1
- package/dist/definitions-DP1vgxEY.mjs +0 -1
- package/dist/definitions-Tls8c0A0.mjs +0 -1
- package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
- package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
- package/dist/handlers-8zN_vBIz.mjs +0 -1
- package/dist/handlers-DHO3rjsW.mjs +0 -1
- package/dist/handlers-FJ80VzUI.mjs +0 -2
- package/dist/handlers-VHWrxbM_.mjs +0 -1
- package/dist/handlers-mPFiNPe8.mjs +0 -302
- package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
- package/dist/maintenance-BUpIukhg.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-CRryuZF4.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-DG19q-Ld.mjs +0 -1
- package/dist/manifest-DLMlD0Zc.mjs +0 -1
- package/dist/manifest-DwL2ik8P.mjs +0 -1
- package/dist/manifest-ItF5P8A12.mjs +0 -1
- package/dist/manifest-KZphqIyX.mjs +0 -1
- package/dist/manifest-RcpX_MyZ.mjs +0 -123
- package/dist/manifest-Zy7Odg5J.mjs +0 -1
- package/dist/manifest-ff1H7Pdp.mjs +0 -1
- package/dist/manifest-iuhF6pTL2.mjs +0 -1
- package/dist/manifest-yC16OhL2.mjs +0 -1
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
- package/dist/native-j8l473zn.mjs +0 -961
- package/dist/network-T0VRwNPd.mjs +0 -7
- package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
- 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/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/types-D9EiE5o9.mjs +0 -1
- /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/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
- /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.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/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.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/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
- /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.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
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{C as t,Li as n,Ri as r,T as i,vn as a,w as o,yn as s,zi as c}from"./constants-DMv3svps.mjs";import{n as l,r as u}from"./response-B1RuVVfD.mjs";import{d}from"./ensure-browser-core-JHwDo5ql.mjs";import{a as f,c as p,n as m,o as h,r as g,t as _}from"./parse-args-ngRrvF9e.mjs";import"./definitions-DuIPS8gq.mjs";import{n as v}from"./ResponseBuilder-nPXl_khE.mjs";import{n as y,t as b}from"./webcrack-phEfVt5y.mjs";import*as x from"@babel/parser";import S from"@babel/traverse";import*as C from"@babel/types";import w from"@babel/generator";const ee=new Set([`=`,`(`,`[`,`,`,`;`,`{`,`!`,`&`,`|`,`?`,`:`,`~`,`^`,`+`,`-`,`*`,`%`,`<`,`>`,`
|
|
2
2
|
`]);function T(e){return new RegExp(e.source,e.flags)}function E(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 D(e){try{let t=x.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 S(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()}}),E(n)}catch{return null}}function te(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 ne(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(ee.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 re(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===`
|
|
3
3
|
`&&(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===`/`&&ne(e,o)){a=!0;continue}(s===`'`||s===`"`||s==="`")&&(n=s)}return n!==null||r||i||a}function O(e,t,n){let r=e=>e.replace(T(t),n),i=D(e);if(i===null)return e.replace(T(t),(...t)=>{let r=typeof t[0]==`string`?t[0]:``,i=te(t);return i!==null&&re(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 ie=/\b(-?\d+(?:\.\d+)?)\s*([+\-%*/])\s*(-?\d+(?:\.\d+)?)\b/g,ae=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*/g,oe=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*else\s*\{([^}]*)\}/g,k=/if\s*\(\s*true\s*\)\s*\{([^}]*)\}\s*(?:else\s*\{[^}]*\}\s*)?/g,A=/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,j=/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,M=/['"]([^'"]*)['"]\s*\+\s*['"]([^'"]*)['"]/g;function N(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 P(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 F(e,t){let n=t.get(e.node.name);if(!n)return null;let r=e.scope.getBinding(e.node.name);if(!r||!C.isVariableDeclarator(r.path.node)||!C.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 I(e,t){try{let n=x.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=new Map;return S(n,{ObjectProperty(e){if(!e.node.shorthand||!C.isIdentifier(e.node.key)||!C.isIdentifier(e.node.value))return;let n=e.get(`value`);if(!n.isIdentifier())return;let i=F(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=F(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:P(e,[...r.values()])}catch{return null}}function L(e){let t=e;return t=O(t,ie,(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=O(t,M,(e,t,n)=>JSON.stringify(`${t}${n}`)),t=O(t,/--(\d)/g,(e,t)=>t),t=O(t,/\+\s*(\d+(?:\.\d+)?)/g,(e,t)=>t),t=O(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 R(e){let t=e;return t=O(t,oe,(e,t)=>t),t=O(t,ae,``),t=O(t,k,(e,t)=>t),t=O(t,/\btrue\s*\?\s*([^:]+)\s*:\s*([^,;)\]}]+)/g,(e,t)=>t),t=O(t,/\bfalse\s*\?\s*[^:]+\s*:\s*([^,;)}\]]+)/g,(e,t)=>t),t=O(t,/if\s*\([^)]*\)\s*\{\s*\}\s*/g,``),t}function z(e){let t=e;return t=O(t,A,(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(`
|
|
4
4
|
`);return c.length>0?c:e}),t=O(t,j,(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(`
|
|
5
|
-
`);return l.length>0?l:e}),t}function B(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=I(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=N(r,n-1,-1),c=N(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 V={"<":(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},H=[{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`}],U=[{pattern:`boolean-literal`,regex:/!!\[\]/g,replacement:`true`},{pattern:`boolean-literal`,regex:/!\[\]/g,replacement:`false`},{pattern:`undefined-literal`,regex:/void\s+0/g,replacement:`undefined`}],W={pattern:`opaque-truthy`,regex:/!0x0\b|!\b0(?![.\d])/g,replacement:`true`},G=[{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`}],K=/if\s*\(\s*(-?\d+(?:\.\d+)?)\s*([<>!=]+)\s*(-?\d+(?:\.\d+)?)\s*\)/g,q=/!\s*(-?\d+(?:\.\d+)?)(?![.\d\s\w])/g,se=/(?:var|let|const)\s+(\w+)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\]/g;function J(e,t,n,r){return e.solved.push({pattern:t,original:n,result:r}),r}function Y(e,t){for(let n of t)e.output=O(e.output,n.regex,t=>J(e,n.pattern,t,n.replacement))}function ce(e){e.output=O(e.output,K,(t,n,r,i)=>{if(e.iterations>=e.maxIterations)return t;let a=V[r];if(!a)return t;e.iterations+=1;let o=a(Number(n),Number(i));return J(e,`constant-comparison`,t,String(o)),e.replaceInPlace?`/* ${t} => ${o} */ if (${o})`:`if (${o})`})}function le(e){e.output=O(e.output,q,(t,n)=>{let r=Number(n);return r===0||!Number.isFinite(r)?t:J(e,`opaque-falsy`,t,`false`)})}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function de(e){let t=new Map;return O(e,se,(e,n,r)=>{let i=r.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``));return t.set(n,i),e}),t}function fe(e){let t=de(e.output);if(t.size!==0)for(let[n,r]of t){let t=RegExp(`${ue(n)}\\(['"]?(0x[0-9a-fA-F]+|\\d+)['"]?\\)`,`g`);e.output=O(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,J(e,`string-array-access`,t,JSON.stringify(r[i])))})}}function pe(e){let t={output:e.code,solved:[],replaceInPlace:e.replaceInPlace,maxIterations:e.maxIterations,iterations:0};return ce(t),Y(t,H),Y(t,U),Y(t,[W]),le(t),fe(t),Y(t,G),{success:!0,solvedCount:t.solved.length,solved:t.solved,transformedCode:e.replaceInPlace?t.output:void 0}}const me=[{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 he(e){for(let t of me)if(t.test.test(e))return t.type;return`switch`}function ge(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 _e(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:he(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=ge(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}}async function ve(t,n){let r=d(n,`searchKeyword`,``),i=g(n,`forceRequireAll`,!!r),a=Math.min(m(n,`maxResults`,20),100);return v(async()=>{let n=await _(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})}var X=class{symbolCounter=0;pathCounter=0;async execute(t){let i=Date.now(),{code:o,maxPaths:s=n,maxDepth:c=a,timeout:l=r,enableConstraintSolving:u=!1}=t;e.info(` ...`);let d=[],f=[],p=[],m=[];try{let t=x.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()-i>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 a=this.executeStep(e,t);for(let e of a)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),a=Date.now()-i;return e.info(`Symbolic execution complete in ${a}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:a}}}catch(t){throw e.error(``,t),t}}executeStep(e,t){let n=[],r=null,i=0;if(S(t,{enter(t){i===e.pc&&(r=t.node,t.stop()),i++}}),!r)return[];if(C.isVariableDeclaration(r)){let t=this.cloneState(e);r.declarations.forEach(e=>{if(C.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(C.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(C.isWhileStatement(r)||C.isForStatement(r)){let t=this.cloneState(e),r=this.cloneState(e);t.pc++,r.pc+=2,n.push(t,r)}else if(C.isAssignmentExpression(r)){let t=this.cloneState(e),i=r;if(C.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 C.isIdentifier(e)?e.name:C.isNumericLiteral(e)?String(e.value):C.isStringLiteral(e)?`"${e.value}"`:C.isBinaryExpression(e)?`${this.nodeToString(e.left)} ${e.operator} ${this.nodeToString(e.right)}`:C.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(` ...`);for(let e of t){let t=this.simpleSMTSolver(e.constraints);t.satisfiable?e.isFeasible=!0:(e.isFeasible=!1,n.push(` ${e.id} : ${t.reason}`))}e.info(`Path analysis complete, feasible paths: ${t.filter(e=>e.isFeasible).length}/${t.length}`)}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(S(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})}},ye=class extends X{async executeJSVMP(n){let r=Date.now(),{instructions:a,vmType:o=`custom`,maxSteps:s=i,timeout:c=t}=n;e.info(` JSVMP...`),e.info(` : ${a.length}`),e.info(`VM type detected: ${o}`);let l=[],u=[];try{let t={pc:0,stack:[],registers:new Map,memory:new Map,pathConstraints:[]},n=0;for(;t.pc<a.length&&n<s;){if(Date.now()-r>c){l.push(`JSVMP`);break}let e=a[t.pc];if(!e){l.push(`: PC=${t.pc}`);break}if(u.push(this.cloneStateInternal(t)),t=this.executeInstruction(t,e,a),e.opcode===255)break;n++}let i=this.inferLogic(u,a),o=this.collectAllConstraints(u),d=this.calculateConfidence(u,a),f=Date.now()-r;return e.info(`JSVMP symbolic execution complete in ${f}ms`),e.info(` : ${n}`),e.info(` : ${(d*100).toFixed(1)}%`),{finalState:t,executionTrace:u,inferredLogic:i,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(`
|
|
6
|
-
`)||``}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]}}};function be(t){e.info(`Derotating string array...`);try{let n=x.parse(t,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=0;return S(n,{CallExpression(t){if(!C.isFunctionExpression(t.node.callee)&&!C.isArrowFunctionExpression(t.node.callee))return;let n=t.node.callee;if(!C.isFunctionExpression(n)||!C.isBlockStatement(n.body))return;let i=n.body.body.some(e=>C.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`),w(n,{comments:!0,compact:!1}).code):t}catch(n){return e.error(`Failed to derotate string array:`,n),t}}const Z=S.default??S,Q=w.default??w,$=new Set([`summary`,`priority`,`incremental`,`full`]),xe=new Set([`structure`,`business`,`security`,`all`]),Se=new Set([`function`,`xhr`,`fetch`,`websocket`,`localstorage`,`cookie`]),Ce=new Set([`log`,`block`,`modify`]),we=new Set([`call`,`apply`]);var Te=class{collector;scriptManager;deobfuscator;advancedDeobfuscator;obfuscationDetector;analyzer;cryptoDetector;hookManager;jsvmpDeobfuscator;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.jsvmpDeobfuscator=new y}requireCodeArg(t,n){let r=t.code;return typeof r!=`string`||r.trim().length===0?(e.warn(`${n} called without valid code argument`),null):r}extractWebcrackArgs(e){let t={},n=g(e,`unpack`),r=g(e,`unminify`),i=g(e,`jsx`),a=g(e,`mangle`),o=g(e,`forceOutput`),s=g(e,`includeModuleCode`),c=d(e,`outputDir`),l=m(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 handleCollectCode(t){let n=g(t,`returnSummaryOnly`,!1),r=p(t,`smartMode`,$),i=o,a=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:a(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:h(t,`url`),includeInline:g(t,`includeInline`),includeExternal:g(t,`includeExternal`),includeDynamic:g(t,`includeDynamic`),smartMode:r,compress:g(t,`compress`),maxTotalSize:m(t,`maxTotalSize`),maxFileSize:t.maxFileSize?m(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,_=c,v=Buffer.byteLength(JSON.stringify(d),`utf8`);return d.totalSize>f||v>_?(e.warn(`Collected code is too large (collected=${(d.totalSize/1024).toFixed(2)}KB, response=${(v/1024).toFixed(2)}KB), returning summary mode.`),l({warning:`Code size exceeds safe response threshold; summary returned.`,...u(d),estimatedResponseSize:v,estimatedResponseSizeKB:(v/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=d(e,`keyword`);if(!t)return l({success:!1,error:`keyword is required`});let n=m(e,`maxMatches`,100),r=g(e,`returnSummary`,!1),i=m(e,`maxContextSize`,5e4),a=await this.scriptManager.searchInScripts(t,{isRegex:g(e,`isRegex`),caseSensitive:g(e,`caseSensitive`),contextLines:m(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=d(e,`scriptId`),n=d(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:m(e,`maxDepth`),maxSize:m(e,`maxSize`),includeComments:g(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`})}}async handleDeobfuscate(e){let t=this.requireCodeArg(e,`deobfuscate`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});if(p(e,`engine`,new Set([`auto`,`webcrack`]),`auto`)===`webcrack`)return l(await this.advancedDeobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e),...typeof e.detectOnly==`boolean`?{detectOnly:e.detectOnly}:{}}));let n=await this.deobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e)});return n&&typeof n==`object`&&`success`in n&&n.success===!1&&!(`error`in n)?l({...n,error:n.reason||`deobfuscation failed`}):l(n)}async handleUnderstandCode(e){let t=this.requireCodeArg(e,`understand_code`);return l(t?await this.analyzer.understand({code:t,context:f(e,`context`),focus:p(e,`focus`,xe,`all`)}):{success:!1,error:`code is required and must be a non-empty string`})}async handleDetectCrypto(e){let t=this.requireCodeArg(e,`detect_crypto`);return l(t?await this.cryptoDetector.detect({code:t}):{success:!1,error:`code is required and must be a non-empty string`})}async handleManageHooks(e){let t=h(e,`action`);switch(t){case`create`:return l(await this.hookManager.createHook({target:h(e,`target`),type:p(e,`type`,Se)??`function`,action:p(e,`hookAction`,Ce,`log`),customCode:d(e,`customCode`)}));case`list`:return l({hooks:this.hookManager.getAllHooks()});case`records`:return l({records:this.hookManager.getHookRecords(h(e,`hookId`))});case`clear`:return this.hookManager.clearHookRecords(d(e,`hookId`)),l({success:!0,message:`Hook records cleared`});default:return l({success:!1,message:`Unknown hook action: ${t}. Valid actions: create, list, records, clear`})}}async handleDetectObfuscation(e){let t=this.requireCodeArg(e,`detect_obfuscation`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=g(e,`generateReport`,!0),r=this.obfuscationDetector.detect(t);if(!n)return l(r);let i=this.obfuscationDetector.generateReport(r);return u(`${JSON.stringify(r,null,2)}\n\n${i}`)}async handleWebcrackUnpack(e){let t=this.requireCodeArg(e,`webcrack_unpack`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=await b(t,{unpack:g(e,`unpack`,!0),unminify:g(e,`unminify`,!0),jsx:g(e,`jsx`,!0),mangle:g(e,`mangle`,!1),...this.extractWebcrackArgs(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 handleWebpackEnumerate(e){return ve(this.collector,e)}async handleClearCollectedData(){return v(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 v(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}}})}async handleJsDeobfuscateJsvmp(e){let t=this.requireCodeArg(e,`js_deobfuscate_jsvmp`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=g(e,`detectOnly`,!1),r=await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:g(e,`aggressive`,!1),extractInstructions:g(e,`extractInstructions`,!0),timeout:m(e,`timeout`,3e4)});return l(n?{success:!0,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,confidence:r.confidence,instructionCount:r.instructions?.length}:{success:r.isJSVMP,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,instructions:r.instructions,deobfuscatedCode:r.deobfuscatedCode,confidence:r.confidence,warnings:r.warnings,unresolvedParts:r.unresolvedParts,stats:r.stats})}async handleJsDeobfuscatePipeline(e){let t=this.requireCodeArg(e,`js_deobfuscate_pipeline`);if(!t)return l({success:!1,error:`code is required`});let n=g(e,`useWebcrack`,!0),r=g(e,`aggressive`,!1),i=g(e,`humanize`,!0),a=g(e,`returnStageDetails`,!1),o=Date.now(),s=t,c=[],u=L(s);u!==s&&(s=u,c.push(`constant_fold`));let d=R(s);d!==s&&(s=d,c.push(`dead_code_remove`));let f=s,p=!1,m,h;if(n)try{let e=await b(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){h=e instanceof Error?e.message:String(e)}if(r){let e=z(f);e!==f&&(f=e)}let _=f,v=0;if(i){let e=B(_);e.code!==_&&(_=e.code,v=e.count)}let y=Date.now()-o,x=t.length>0?1-_.length/t.length:0,S={success:!m&&!h,deobfuscatedCode:_,...m?{warning:m}:{},...h?{error:`webcrack stage failed: ${h}`}:{},stats:{originalSize:t.length,finalSize:_.length,reductionRate:Math.round(x*1e3)/10,processingTimeMs:y,stages:{preprocessor:{transforms:c,sizeAfter:s.length},deobfuscator:{webcrackApplied:p,sizeAfter:f.length,...m?{warning:m}:{},...h?{error:h}:{}},humanizer:{renameCount:v,sizeAfter:_.length}}}};return a&&(S.stageDetails={preprocessed:s.substring(0,5e3),deobfuscated:f.substring(0,5e3)}),l(S)}async handleJsAnalyzeVm(e){let t=this.requireCodeArg(e,`js_analyze_vm`);if(!t)return l({success:!1,error:`code is required`});let n=g(e,`extractBytecode`,!0);return l(_e({code:t,extractBytecode:n,mapOpcodes:g(e,`mapOpcodes`,!0),vmResult:await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:!1,extractInstructions:n,timeout:15e3})}))}async handleJsSolveConstraints(e){let t=this.requireCodeArg(e,`js_solve_constraints`);return l(t?pe({code:t,replaceInPlace:g(e,`replaceInPlace`,!0),maxIterations:m(e,`maxIterations`,100)}):{success:!1,error:`code is required`})}async handleAnalysisAstMatch(e){let t=d(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=d(e,`nodeType`);if(!n)return l({success:!1,error:`nodeType is required`});let r=m(e,`maxResults`,50),i=d(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=x.parse(t,{sourceType:`unambiguous`,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 f(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 Z(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:f(n)}),s.length>=r&&e.stop())}}),l({success:!0,matches:s,total:s.length,nodeType:n})}async handleAnalysisDeflatControlFlow(e){let t=d(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n;try{n=x.parse(t,{sourceType:`unambiguous`})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let r=g(e,`removeDispatcher`,!0),i=this.preprocessDeflatCode(t);if(i.code!==t)try{n=x.parse(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,s=this.resolveDispatcherArray.bind(this);Z(n,{WhileStatement:e=>{let t=e.node.test;if(t.type!==`BooleanLiteral`||t.value!==!0)return;let n=e.node.body;if(n.type!==`BlockStatement`)return;let r=n.body.find(e=>e.type===`SwitchStatement`);if(!r)return;let i=r.discriminant;if(i.type!==`MemberExpression`||!i.computed)return;let c=i.object;if(c.type!==`Identifier`)return;let l=c.name,u,d=i.property;if(d.type===`Identifier`?u=d.name:d.type===`UpdateExpression`&&d.argument.type===`Identifier`&&(u=d.argument.name),!u)return;let f=r.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=s(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(C.blockStatement(v)),o.add(m.identifier),o.add(h.identifier),a++}}),r&&o.size>0&&Z(n,{VariableDeclarator(e){if(e.node.id.type===`Identifier`&&o.has(e.node.id)){let t=e.parent;t.type===`VariableDeclaration`&&t.declarations.length===1?e.parentPath.remove():e.remove()}}});let c=Q(n,{retainLines:!0}).code;return l({success:!0,code:c,flattenedCount:a,dispatchersRemoved:r?o.size:0,helperTransforms:i.transforms})}async handleAnalysisDecodeStringArray(e){let t=d(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=m(e,`maxReplacements`,200),r=g(e,`removeRotation`,!0),i=r?be(t):t,a=new Map,o;try{o=x.parse(i,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}Z(o,{VariableDeclarator(e){if(!C.isIdentifier(e.node.id)||!C.isArrayExpression(e.node.init))return;let t=[];for(let n of e.node.init.elements){if(!C.isStringLiteral(n))return;t.push(n.value)}a.set(e.node.id.name,t)}});let s=[],c=0;return Z(o,{CallExpression(e){if(c>=n){e.stop();return}if(!C.isIdentifier(e.node.callee))return;let t=e.node.callee.name,r=a.get(t);if(!r||e.node.arguments.length!==1)return;let i=e.node.arguments[0];if(!C.isNumericLiteral(i)&&!C.isStringLiteral(i))return;let o=C.isNumericLiteral(i)?i.value:i.value.startsWith(`0x`)?Number.parseInt(i.value,16):Number(i.value);if(!Number.isInteger(o)||o<0||o>=r.length)return;let l=r[o];typeof l==`string`&&(s.push({arrayName:t,index:o,value:l,original:Q(e.node,{compact:!0}).code}),e.replaceWith(C.stringLiteral(l)),c+=1)}}),l({success:!0,code:Q(o,{retainLines:!0}).code,replacedCount:c,arraysFound:a.size,rotationRemoved:r&&i!==t,replacements:s})}preprocessDeflatCode(e){let t=e,n=[];return t=t.replace(/(\b[a-zA-Z_$][\w$]*)\[['"]([a-zA-Z_$][\w$]*)['"]\]\(([^)]*)\)/g,(e,t,r,i)=>we.has(r)?(n.push(`helper-member-call`),`${t}.${r}(${i})`):e),{code:t,transforms:n}}resolveDispatcherArray(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(!(!C.isAssignmentExpression(n)||n.operator!==`=`||!C.isIdentifier(n.left,{name:t})))return n.right}return null}async handleJsSymbolicExecute(e){let t=h(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=m(e,`maxPaths`),r=m(e,`maxDepth`),i=m(e,`timeout`),a=g(e,`enableConstraintSolving`,!1);return v(async()=>await new X().execute({code:t,...n===void 0?{}:{maxPaths:n},...r===void 0?{}:{maxDepth:r},...i===void 0?{}:{timeout:i},enableConstraintSolving:a}))}async handleJsSymbolicExecuteJsvmp(e){let t=f(e,`instructions`);if(!t||!Array.isArray(t))return l({success:!1,error:`instructions array is required (from js_analyze_vm output)`});let n=d(e,`vmType`),r=m(e,`maxSteps`),i=m(e,`timeout`);return v(async()=>await new ye().executeJSVMP({instructions:t,...n?{vmType:n}:{},...r===void 0?{}:{maxSteps:r},...i===void 0?{}:{timeout:i}}))}};export{Te as CoreAnalysisHandlers};
|
|
5
|
+
`);return l.length>0?l:e}),t}function B(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=I(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=N(r,n-1,-1),c=N(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 V={"<":(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},H=[{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`}],U=[{pattern:`boolean-literal`,regex:/!!\[\]/g,replacement:`true`},{pattern:`boolean-literal`,regex:/!\[\]/g,replacement:`false`},{pattern:`undefined-literal`,regex:/void\s+0/g,replacement:`undefined`}],W={pattern:`opaque-truthy`,regex:/!0x0\b|!\b0(?![.\d])/g,replacement:`true`},G=[{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`}],K=/if\s*\(\s*(-?\d+(?:\.\d+)?)\s*([<>!=]+)\s*(-?\d+(?:\.\d+)?)\s*\)/g,q=/!\s*(-?\d+(?:\.\d+)?)(?![.\d\s\w])/g,se=/(?:var|let|const)\s+(\w+)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\]/g;function J(e,t,n,r){return e.solved.push({pattern:t,original:n,result:r}),r}function Y(e,t){for(let n of t)e.output=O(e.output,n.regex,t=>J(e,n.pattern,t,n.replacement))}function ce(e){e.output=O(e.output,K,(t,n,r,i)=>{if(e.iterations>=e.maxIterations)return t;let a=V[r];if(!a)return t;e.iterations+=1;let o=a(Number(n),Number(i));return J(e,`constant-comparison`,t,String(o)),e.replaceInPlace?`/* ${t} => ${o} */ if (${o})`:`if (${o})`})}function le(e){e.output=O(e.output,q,(t,n)=>{let r=Number(n);return r===0||!Number.isFinite(r)?t:J(e,`opaque-falsy`,t,`false`)})}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function de(e){let t=new Map;return O(e,se,(e,n,r)=>{let i=r.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``));return t.set(n,i),e}),t}function fe(e){let t=de(e.output);if(t.size!==0)for(let[n,r]of t){let t=RegExp(`${ue(n)}\\(['"]?(0x[0-9a-fA-F]+|\\d+)['"]?\\)`,`g`);e.output=O(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,J(e,`string-array-access`,t,JSON.stringify(r[i])))})}}function pe(e){let t={output:e.code,solved:[],replaceInPlace:e.replaceInPlace,maxIterations:e.maxIterations,iterations:0};return ce(t),Y(t,H),Y(t,U),Y(t,[W]),le(t),fe(t),Y(t,G),{success:!0,solvedCount:t.solved.length,solved:t.solved,transformedCode:e.replaceInPlace?t.output:void 0}}const me=[{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 he(e){for(let t of me)if(t.test.test(e))return t.type;return`switch`}function ge(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 _e(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:he(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=ge(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}}async function ve(t,n){let r=h(n,`searchKeyword`,``),i=_(n,`forceRequireAll`,!!r),a=Math.min(g(n,`maxResults`,20),100);return v(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})}var X=class{symbolCounter=0;pathCounter=0;async execute(t){let i=Date.now(),{code:a,maxPaths:o=r,maxDepth:s=n,timeout:l=c,enableConstraintSolving:u=!1}=t;e.info(` ...`);let d=[],f=[],p=[],m=[];try{let t=x.parse(a,{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<o;){if(Date.now()-i>l){m.push(`Symbolic execution timed out`);break}let{state:e,depth:r}=n.pop();if(r>=s){m.push(`Max depth reached: ${s}`);continue}let a=this.executeStep(e,t);for(let e of a)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),c=Date.now()-i;return e.info(`Symbolic execution complete in ${c}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:c}}}catch(t){throw e.error(``,t),t}}executeStep(e,t){let n=[],r=null,i=0;if(S(t,{enter(t){i===e.pc&&(r=t.node,t.stop()),i++}}),!r)return[];if(C.isVariableDeclaration(r)){let t=this.cloneState(e);r.declarations.forEach(e=>{if(C.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(C.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(C.isWhileStatement(r)||C.isForStatement(r)){let t=this.cloneState(e),r=this.cloneState(e);t.pc++,r.pc+=2,n.push(t,r)}else if(C.isAssignmentExpression(r)){let t=this.cloneState(e),i=r;if(C.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 C.isIdentifier(e)?e.name:C.isNumericLiteral(e)?String(e.value):C.isStringLiteral(e)?`"${e.value}"`:C.isBinaryExpression(e)?`${this.nodeToString(e.left)} ${e.operator} ${this.nodeToString(e.right)}`:C.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(` ...`);for(let e of t){let t=this.simpleSMTSolver(e.constraints);t.satisfiable?e.isFeasible=!0:(e.isFeasible=!1,n.push(` ${e.id} : ${t.reason}`))}e.info(`Path analysis complete, feasible paths: ${t.filter(e=>e.isFeasible).length}/${t.length}`)}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(S(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})}},ye=class extends X{async executeJSVMP(t){let n=Date.now(),{instructions:r,vmType:i=`custom`,maxSteps:o=a,timeout:c=s}=t;e.info(` JSVMP...`),e.info(` : ${r.length}`),e.info(`VM type detected: ${i}`);let l=[],u=[];try{let t={pc:0,stack:[],registers:new Map,memory:new Map,pathConstraints:[]},i=0;for(;t.pc<r.length&&i<o;){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),s=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:s,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(`
|
|
6
|
+
`)||``}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]}}};function be(t){e.info(`Derotating string array...`);try{let n=x.parse(t,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=0;return S(n,{CallExpression(t){if(!C.isFunctionExpression(t.node.callee)&&!C.isArrowFunctionExpression(t.node.callee))return;let n=t.node.callee;if(!C.isFunctionExpression(n)||!C.isBlockStatement(n.body))return;let i=n.body.body.some(e=>C.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`),w(n,{comments:!0,compact:!1}).code):t}catch(n){return e.error(`Failed to derotate string array:`,n),t}}const Z=S.default??S,Q=w.default??w,$=new Set([`summary`,`priority`,`incremental`,`full`]),xe=new Set([`structure`,`business`,`security`,`all`]),Se=new Set([`function`,`xhr`,`fetch`,`websocket`,`localstorage`,`cookie`]),Ce=new Set([`log`,`block`,`modify`]),we=new Set([`call`,`apply`]);var Te=class{collector;scriptManager;deobfuscator;advancedDeobfuscator;obfuscationDetector;analyzer;cryptoDetector;hookManager;jsvmpDeobfuscator;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.jsvmpDeobfuscator=new y}requireCodeArg(t,n){let r=t.code;return typeof r!=`string`||r.trim().length===0?(e.warn(`${n} called without valid code argument`),null):r}extractWebcrackArgs(e){let t={},n=_(e,`unpack`),r=_(e,`unminify`),i=_(e,`jsx`),a=_(e,`mangle`),o=_(e,`forceOutput`),s=_(e,`includeModuleCode`),c=h(e,`outputDir`),l=g(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 handleCollectCode(n){let r=_(n,`returnSummaryOnly`,!1),a=m(n,`smartMode`,$),s=i,c=e=>e.slice(0,s).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:c(e.files)).slice(0,s),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}};a||=`summary`;let d=await this.collector.collect({url:p(n,`url`),includeInline:_(n,`includeInline`),includeExternal:_(n,`includeExternal`),includeDynamic:_(n,`includeDynamic`),smartMode:a,compress:_(n,`compress`),maxTotalSize:g(n,`maxTotalSize`),maxFileSize:n.maxFileSize?g(n,`maxFileSize`,0)*1024:void 0,priorities:n.priorities});if(r)return l({mode:`summary`,...u(d),hint:`Use get_script_source for specific files.`});let f=t,h=o,v=Buffer.byteLength(JSON.stringify(d),`utf8`);return d.totalSize>f||v>h?(e.warn(`Collected code is too large (collected=${(d.totalSize/1024).toFixed(2)}KB, response=${(v/1024).toFixed(2)}KB), returning summary mode.`),l({warning:`Code size exceeds safe response threshold; summary returned.`,...u(d),estimatedResponseSize:v,estimatedResponseSizeKB:(v/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=h(e,`keyword`);if(!t)return l({success:!1,error:`keyword is required`});let n=g(e,`maxMatches`,100),r=_(e,`returnSummary`,!1),i=g(e,`maxContextSize`,5e4),a=await this.scriptManager.searchInScripts(t,{isRegex:_(e,`isRegex`),caseSensitive:_(e,`caseSensitive`),contextLines:g(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=h(e,`scriptId`),n=h(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:g(e,`maxDepth`),maxSize:g(e,`maxSize`),includeComments:_(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`})}}async handleDeobfuscate(e){let t=this.requireCodeArg(e,`deobfuscate`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});if(m(e,`engine`,new Set([`auto`,`webcrack`]),`auto`)===`webcrack`)return l(await this.advancedDeobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e),...typeof e.detectOnly==`boolean`?{detectOnly:e.detectOnly}:{}}));let n=await this.deobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e)});return n&&typeof n==`object`&&`success`in n&&n.success===!1&&!(`error`in n)?l({...n,error:n.reason||`deobfuscation failed`}):l(n)}async handleUnderstandCode(e){let t=this.requireCodeArg(e,`understand_code`);return l(t?await this.analyzer.understand({code:t,context:f(e,`context`),focus:m(e,`focus`,xe,`all`)}):{success:!1,error:`code is required and must be a non-empty string`})}async handleDetectCrypto(e){let t=this.requireCodeArg(e,`detect_crypto`);return l(t?await this.cryptoDetector.detect({code:t}):{success:!1,error:`code is required and must be a non-empty string`})}async handleManageHooks(e){let t=p(e,`action`);switch(t){case`create`:return l(await this.hookManager.createHook({target:p(e,`target`),type:m(e,`type`,Se)??`function`,action:m(e,`hookAction`,Ce,`log`),customCode:h(e,`customCode`)}));case`list`:return l({hooks:this.hookManager.getAllHooks()});case`records`:return l({records:this.hookManager.getHookRecords(p(e,`hookId`))});case`clear`:return this.hookManager.clearHookRecords(h(e,`hookId`)),l({success:!0,message:`Hook records cleared`});default:return l({success:!1,message:`Unknown hook action: ${t}. Valid actions: create, list, records, clear`})}}async handleDetectObfuscation(e){let t=this.requireCodeArg(e,`detect_obfuscation`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=_(e,`generateReport`,!0),r=this.obfuscationDetector.detect(t);if(!n)return l(r);let i=this.obfuscationDetector.generateReport(r);return u(`${JSON.stringify(r,null,2)}\n\n${i}`)}async handleWebcrackUnpack(e){let t=this.requireCodeArg(e,`webcrack_unpack`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=await b(t,{unpack:_(e,`unpack`,!0),unminify:_(e,`unminify`,!0),jsx:_(e,`jsx`,!0),mangle:_(e,`mangle`,!1),...this.extractWebcrackArgs(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 handleWebpackEnumerate(e){return ve(this.collector,e)}async handleClearCollectedData(){return v(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 v(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}}})}async handleJsDeobfuscateJsvmp(e){let t=this.requireCodeArg(e,`js_deobfuscate_jsvmp`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=_(e,`detectOnly`,!1),r=await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:_(e,`aggressive`,!1),extractInstructions:_(e,`extractInstructions`,!0),timeout:g(e,`timeout`,3e4)});return l(n?{success:!0,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,confidence:r.confidence,instructionCount:r.instructions?.length}:{success:r.isJSVMP,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,instructions:r.instructions,deobfuscatedCode:r.deobfuscatedCode,confidence:r.confidence,warnings:r.warnings,unresolvedParts:r.unresolvedParts,stats:r.stats})}async handleJsDeobfuscatePipeline(e){let t=this.requireCodeArg(e,`js_deobfuscate_pipeline`);if(!t)return l({success:!1,error:`code is required`});let n=_(e,`useWebcrack`,!0),r=_(e,`aggressive`,!1),i=_(e,`humanize`,!0),a=_(e,`returnStageDetails`,!1),o=Date.now(),s=t,c=[],u=L(s);u!==s&&(s=u,c.push(`constant_fold`));let d=R(s);d!==s&&(s=d,c.push(`dead_code_remove`));let f=s,p=!1,m,h;if(n)try{let e=await b(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){h=e instanceof Error?e.message:String(e)}if(r){let e=z(f);e!==f&&(f=e)}let g=f,v=0;if(i){let e=B(g);e.code!==g&&(g=e.code,v=e.count)}let y=Date.now()-o,x=t.length>0?1-g.length/t.length:0,S={success:!m&&!h,deobfuscatedCode:g,...m?{warning:m}:{},...h?{error:`webcrack stage failed: ${h}`}:{},stats:{originalSize:t.length,finalSize:g.length,reductionRate:Math.round(x*1e3)/10,processingTimeMs:y,stages:{preprocessor:{transforms:c,sizeAfter:s.length},deobfuscator:{webcrackApplied:p,sizeAfter:f.length,...m?{warning:m}:{},...h?{error:h}:{}},humanizer:{renameCount:v,sizeAfter:g.length}}}};return a&&(S.stageDetails={preprocessed:s.substring(0,5e3),deobfuscated:f.substring(0,5e3)}),l(S)}async handleJsAnalyzeVm(e){let t=this.requireCodeArg(e,`js_analyze_vm`);if(!t)return l({success:!1,error:`code is required`});let n=_(e,`extractBytecode`,!0);return l(_e({code:t,extractBytecode:n,mapOpcodes:_(e,`mapOpcodes`,!0),vmResult:await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:!1,extractInstructions:n,timeout:15e3})}))}async handleJsSolveConstraints(e){let t=this.requireCodeArg(e,`js_solve_constraints`);return l(t?pe({code:t,replaceInPlace:_(e,`replaceInPlace`,!0),maxIterations:g(e,`maxIterations`,100)}):{success:!1,error:`code is required`})}async handleAnalysisAstMatch(e){let t=h(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=h(e,`nodeType`);if(!n)return l({success:!1,error:`nodeType is required`});let r=g(e,`maxResults`,50),i=h(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=x.parse(t,{sourceType:`unambiguous`,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 Z(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 handleAnalysisDeflatControlFlow(e){let t=h(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n;try{n=x.parse(t,{sourceType:`unambiguous`})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let r=_(e,`removeDispatcher`,!0),i=this.preprocessDeflatCode(t);if(i.code!==t)try{n=x.parse(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,s=this.resolveDispatcherArray.bind(this);Z(n,{WhileStatement:e=>{let t=e.node.test;if(t.type!==`BooleanLiteral`||t.value!==!0)return;let n=e.node.body;if(n.type!==`BlockStatement`)return;let r=n.body.find(e=>e.type===`SwitchStatement`);if(!r)return;let i=r.discriminant;if(i.type!==`MemberExpression`||!i.computed)return;let c=i.object;if(c.type!==`Identifier`)return;let l=c.name,u,d=i.property;if(d.type===`Identifier`?u=d.name:d.type===`UpdateExpression`&&d.argument.type===`Identifier`&&(u=d.argument.name),!u)return;let f=r.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=s(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(C.blockStatement(v)),o.add(m.identifier),o.add(h.identifier),a++}}),r&&o.size>0&&Z(n,{VariableDeclarator(e){if(e.node.id.type===`Identifier`&&o.has(e.node.id)){let t=e.parent;t.type===`VariableDeclaration`&&t.declarations.length===1?e.parentPath.remove():e.remove()}}});let c=Q(n,{retainLines:!0}).code;return l({success:!0,code:c,flattenedCount:a,dispatchersRemoved:r?o.size:0,helperTransforms:i.transforms})}async handleAnalysisDecodeStringArray(e){let t=h(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=g(e,`maxReplacements`,200),r=_(e,`removeRotation`,!0),i=r?be(t):t,a=new Map,o;try{o=x.parse(i,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}Z(o,{VariableDeclarator(e){if(!C.isIdentifier(e.node.id)||!C.isArrayExpression(e.node.init))return;let t=[];for(let n of e.node.init.elements){if(!C.isStringLiteral(n))return;t.push(n.value)}a.set(e.node.id.name,t)}});let s=[],c=0;return Z(o,{CallExpression(e){if(c>=n){e.stop();return}if(!C.isIdentifier(e.node.callee))return;let t=e.node.callee.name,r=a.get(t);if(!r||e.node.arguments.length!==1)return;let i=e.node.arguments[0];if(!C.isNumericLiteral(i)&&!C.isStringLiteral(i))return;let o=C.isNumericLiteral(i)?i.value:i.value.startsWith(`0x`)?Number.parseInt(i.value,16):Number(i.value);if(!Number.isInteger(o)||o<0||o>=r.length)return;let l=r[o];typeof l==`string`&&(s.push({arrayName:t,index:o,value:l,original:Q(e.node,{compact:!0}).code}),e.replaceWith(C.stringLiteral(l)),c+=1)}}),l({success:!0,code:Q(o,{retainLines:!0}).code,replacedCount:c,arraysFound:a.size,rotationRemoved:r&&i!==t,replacements:s})}preprocessDeflatCode(e){let t=e,n=[];return t=t.replace(/(\b[a-zA-Z_$][\w$]*)\[['"]([a-zA-Z_$][\w$]*)['"]\]\(([^)]*)\)/g,(e,t,r,i)=>we.has(r)?(n.push(`helper-member-call`),`${t}.${r}(${i})`):e),{code:t,transforms:n}}resolveDispatcherArray(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(!(!C.isAssignmentExpression(n)||n.operator!==`=`||!C.isIdentifier(n.left,{name:t})))return n.right}return null}async handleJsSymbolicExecute(e){let t=p(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=g(e,`maxPaths`),r=g(e,`maxDepth`),i=g(e,`timeout`),a=_(e,`enableConstraintSolving`,!1);return v(async()=>await new X().execute({code:t,...n===void 0?{}:{maxPaths:n},...r===void 0?{}:{maxDepth:r},...i===void 0?{}:{timeout:i},enableConstraintSolving:a}))}async handleJsSymbolicExecuteJsvmp(e){let t=f(e,`instructions`);if(!t||!Array.isArray(t))return l({success:!1,error:`instructions array is required (from js_analyze_vm output)`});let n=h(e,`vmType`),r=g(e,`maxSteps`),i=g(e,`timeout`);return v(async()=>await new ye().executeJSVMP({instructions:t,...n?{vmType:n}:{},...r===void 0?{}:{maxSteps:r},...i===void 0?{}:{timeout:i}}))}};export{Te as CoreAnalysisHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./definitions-aeRd5DAR.mjs";import{t as e}from"./handlers-DB6xVVWq.mjs";export{e as AntiDebugToolHandlers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{Xr as t,g as n,h as r}from"./constants-BYj8Xek8.mjs";import{i,l as a,n as o}from"./outputPaths-B4Ic4RZh.mjs";import{n as s,r as c}from"./artifacts-CkodUM4j.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;HISTORY_RETENTION=300*1e3;currentUsage=0;toolCallHistory=[];warnings=new Set;sessionStartTime=Date.now();trackingEnabled=!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(){return this.currentUsage/this.MAX_TOKENS>=this.AUTO_CLEANUP_THRESHOLD}autoCleanup(){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;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.sessionStartTime=Date.now(),e.info(`Token budget reset complete`)}},h=class t{static instance;GLOBAL_MAX_SIZE=r;LOW_HIT_RATE_THRESHOLD=n;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 t=0,n=0,r=0,i=0,a=[];for(let[o,s]of this.caches)try{let e=await s.getStats();t+=e.entries,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,s=this.generateRecommendations(n,o,a);return{totalEntries:t,totalSize:n,totalSizeMB:(n/1024/1024).toFixed(2),hitRate:o,caches:a,recommendations:s}}async smartCleanup(t){let n=t||this.GLOBAL_MAX_SIZE*.7,r=await this.getGlobalStats(),i=r.totalSize;if(i<=n)return e.info(`No cleanup needed`),{before:i,after:i,freed:0,freedPercentage:0};e.info(`Smart cleanup: current ${r.totalSizeMB}MB, target ${(n/1024/1024).toFixed(2)}MB`),await this.cleanupExpired();let a=await this.getGlobalStats();if(a.totalSize<=n||(await this.cleanupLowHitRate(),a=await this.getGlobalStats(),a.totalSize<=n))return this.calculateCleanupResult(i,a.totalSize);await this.cleanupLargeItems();let o=await this.getGlobalStats();return this.calculateCleanupResult(i,o.totalSize)}async cleanupExpired(){e.info(`Cleaning up expired data...`);for(let[t,n]of this.caches)if(n.cleanup)try{await n.cleanup(),e.debug(`Cleaned up expired data in ${t}`)}catch(n){e.error(`Failed to cleanup ${t}:`,n)}}async cleanupLowHitRate(){e.info(`Cleaning up low hit rate caches...`);let t=await this.getGlobalStats(),n=t.hitRate;for(let r of t.caches)if(r.hitRate!==void 0&&r.hitRate<n*this.LOW_HIT_RATE_THRESHOLD){let t=this.caches.get(r.name);if(t?.clear)try{await t.clear(),e.info(`Cleared low hit rate cache: ${r.name} (${(r.hitRate*100).toFixed(1)}%)`)}catch(t){e.error(`Failed to clear ${r.name}:`,t)}}}async cleanupLargeItems(){e.info(`Cleaning up large caches...`);let t=(await this.getGlobalStats()).caches.toSorted((e,t)=>t.size-e.size);for(let n of t.slice(0,2)){let t=this.caches.get(n.name);if(t?.clear)try{await t.clear(),e.info(`Cleared large cache: ${n.name} (${n.sizeMB}MB)`)}catch(t){e.error(`Failed to clear ${n.name}:`,t)}}}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}};function g(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 _(e){let t=g(),n={...t,retentionDays:e?.retentionDays??t.retentionDays,maxTotalBytes:e?.maxTotalBytes??t.maxTotalBytes},r=e?.now??Date.now(),a=e?.dryRun??!1,o=e?.directories??y(),s=n.retentionDays>0?r-n.retentionDays*864e5:0,c=0,l=0,u=0,d=0,p=0,m=[],h=[],_=i(),v=[];function S(e){v.push(f(e,{force:!0}).then(()=>void 0).catch(()=>void 0))}for(let e of o)await b(e,_,s,a,e=>{c++,s>0&&e.mtimeMs<s?(l++,u+=e.size,d+=e.size,h.length<20&&h.push(e.relativePath),a||S(e.path)):m.push(e)});if(n.maxTotalBytes>0){let e=m.reduce((e,t)=>e+t.size,0);if(e>n.maxTotalBytes){m.sort((e,t)=>e.mtimeMs-t.mtimeMs);let t=0;for(;t<m.length&&e>n.maxTotalBytes;){let n=m[t];e-=n.size,l++,u+=n.size,p+=n.size,h.length<20&&h.push(n.relativePath),a||S(n.path),t++}m.splice(0,t)}}return a||(await Promise.all(v),await Promise.all(o.map(e=>x(e)))),{success:!0,scannedFiles:c,removedFiles:l,removedBytes:u,removedByAge:d,removedBySize:p,remainingFiles:m.length,remainingBytes:m.reduce((e,t)=>e+t.size,0),dryRun:a,directories:o,removedSample:h,config:n}}function v(){let t=g();if(!t.enabled||t.cleanupIntervalMinutes<=0)return null;let n=setInterval(()=>{_().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 y(){let e=i(),t=u(process.cwd(),`debugger-sessions`),n=u(e,`debugger-sessions`),r=new Set([c(),a().paths.screenshotDir,o(),t,n]);for(let e of[`wasm`,`traces`,`profiles`,`dumps`,`reports`,`har`,`sessions`,`tmp`])r.add(s(e));return[...r]}async function b(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 b(a,t,n,r,i);else if(o.isFile()){let e;try{e=await p(a)}catch{continue}i({path:a,relativePath:S(t,a),size:e.size,mtimeMs:e.mtimeMs})}}}async function x(e){let t;try{t=await d(e,{withFileTypes:!0})}catch{return}await Promise.all(t.filter(e=>e.isDirectory()).map(t=>x(l(e,t.name))));try{(await d(e)).length===0&&await f(e,{recursive:!0,force:!0})}catch{}}function S(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^[\\/]/,``).replace(/\\/g,`/`):t.replace(/\\/g,`/`)}export{m as a,h as i,g as n,v as r,_ as t};
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{G as t,K as n,Ui as r}from"./constants-DMv3svps.mjs";import{i,l as a,n as o}from"./outputPaths-D2ddHrOJ.mjs";import{n as s,r as c}from"./artifacts-D-4pSS_N.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 t{static instance;MAX_TOKENS=r;WARNING_THRESHOLDS=[.8,.9,.95];BYTES_PER_TOKEN=4;AUTO_CLEANUP_THRESHOLD=.9;HISTORY_RETENTION=300*1e3;currentUsage=0;toolCallHistory=[];warnings=new Set;sessionStartTime=Date.now();trackingEnabled=!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 t,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(){return this.currentUsage/this.MAX_TOKENS>=this.AUTO_CLEANUP_THRESHOLD}autoCleanup(){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;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.sessionStartTime=Date.now(),e.info(`Token budget reset complete`)}},h=class r{static instance;GLOBAL_MAX_SIZE=t;LOW_HIT_RATE_THRESHOLD=n;caches=new Map;constructor(){e.info(`UnifiedCacheManager initialized`)}static getInstance(){return this.instance||=new r,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 t=0,n=0,r=0,i=0,a=[];for(let[o,s]of this.caches)try{let e=await s.getStats();t+=e.entries,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,s=this.generateRecommendations(n,o,a);return{totalEntries:t,totalSize:n,totalSizeMB:(n/1024/1024).toFixed(2),hitRate:o,caches:a,recommendations:s}}async smartCleanup(t){let n=t||this.GLOBAL_MAX_SIZE*.7,r=await this.getGlobalStats(),i=r.totalSize;if(i<=n)return e.info(`No cleanup needed`),{before:i,after:i,freed:0,freedPercentage:0};e.info(`Smart cleanup: current ${r.totalSizeMB}MB, target ${(n/1024/1024).toFixed(2)}MB`),await this.cleanupExpired();let a=await this.getGlobalStats();if(a.totalSize<=n||(await this.cleanupLowHitRate(),a=await this.getGlobalStats(),a.totalSize<=n))return this.calculateCleanupResult(i,a.totalSize);await this.cleanupLargeItems();let o=await this.getGlobalStats();return this.calculateCleanupResult(i,o.totalSize)}async cleanupExpired(){e.info(`Cleaning up expired data...`);for(let[t,n]of this.caches)if(n.cleanup)try{await n.cleanup(),e.debug(`Cleaned up expired data in ${t}`)}catch(n){e.error(`Failed to cleanup ${t}:`,n)}}async cleanupLowHitRate(){e.info(`Cleaning up low hit rate caches...`);let t=await this.getGlobalStats(),n=t.hitRate;for(let r of t.caches)if(r.hitRate!==void 0&&r.hitRate<n*this.LOW_HIT_RATE_THRESHOLD){let t=this.caches.get(r.name);if(t?.clear)try{await t.clear(),e.info(`Cleared low hit rate cache: ${r.name} (${(r.hitRate*100).toFixed(1)}%)`)}catch(t){e.error(`Failed to clear ${r.name}:`,t)}}}async cleanupLargeItems(){e.info(`Cleaning up large caches...`);let t=(await this.getGlobalStats()).caches.toSorted((e,t)=>t.size-e.size);for(let n of t.slice(0,2)){let t=this.caches.get(n.name);if(t?.clear)try{await t.clear(),e.info(`Cleared large cache: ${n.name} (${n.sizeMB}MB)`)}catch(t){e.error(`Failed to clear ${n.name}:`,t)}}}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}};function g(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 _(e){let t=g(),n={...t,retentionDays:e?.retentionDays??t.retentionDays,maxTotalBytes:e?.maxTotalBytes??t.maxTotalBytes},r=e?.now??Date.now(),a=e?.dryRun??!1,o=e?.directories??y(),s=n.retentionDays>0?r-n.retentionDays*864e5:0,c=0,l=0,u=0,d=0,p=0,m=[],h=[],_=i(),v=[];function S(e){v.push(f(e,{force:!0}).then(()=>void 0).catch(()=>void 0))}for(let e of o)await b(e,_,s,a,e=>{c++,s>0&&e.mtimeMs<s?(l++,u+=e.size,d+=e.size,h.length<20&&h.push(e.relativePath),a||S(e.path)):m.push(e)});if(n.maxTotalBytes>0){let e=m.reduce((e,t)=>e+t.size,0);if(e>n.maxTotalBytes){m.sort((e,t)=>e.mtimeMs-t.mtimeMs);let t=0;for(;t<m.length&&e>n.maxTotalBytes;){let n=m[t];e-=n.size,l++,u+=n.size,p+=n.size,h.length<20&&h.push(n.relativePath),a||S(n.path),t++}m.splice(0,t)}}return a||(await Promise.all(v),await Promise.all(o.map(e=>x(e)))),{success:!0,scannedFiles:c,removedFiles:l,removedBytes:u,removedByAge:d,removedBySize:p,remainingFiles:m.length,remainingBytes:m.reduce((e,t)=>e+t.size,0),dryRun:a,directories:o,removedSample:h,config:n}}function v(){let t=g();if(!t.enabled||t.cleanupIntervalMinutes<=0)return null;let n=setInterval(()=>{_().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 y(){let e=i(),t=u(process.cwd(),`debugger-sessions`),n=u(e,`debugger-sessions`),r=new Set([c(),a().paths.screenshotDir,o(),t,n]);for(let e of[`wasm`,`traces`,`profiles`,`dumps`,`reports`,`har`,`sessions`,`tmp`])r.add(s(e));return[...r]}async function b(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 b(a,t,n,r,i);else if(o.isFile()){let e;try{e=await p(a)}catch{continue}i({path:a,relativePath:S(t,a),size:e.size,mtimeMs:e.mtimeMs})}}}async function x(e){let t;try{t=await d(e,{withFileTypes:!0})}catch{return}await Promise.all(t.filter(e=>e.isDirectory()).map(t=>x(l(e,t.name))));try{(await d(e)).length===0&&await f(e,{recursive:!0,force:!0})}catch{}}function S(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^[\\/]/,``).replace(/\\/g,`/`):t.replace(/\\/g,`/`)}export{m as a,h as i,g as n,v as r,_ as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{i as t}from"./outputPaths-D2ddHrOJ.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};
|
|
@@ -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,9 @@
|
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import{Qt as n,Yi as r,en as i}from"./constants-DMv3svps.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{t as o}from"./ToolProbe-DQiREmNp.mjs";import{v as s}from"./ensure-browser-core-JHwDo5ql.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`,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.runFridaCommand(t.target,e);return n.error&&(t.status=`error`,t.lastError=n.error),n}async enumerateModules(){let e=this.requireActiveSession(),t=await this.runFridaCommand(e.target,`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.runFridaCommand(t.target,[`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.runFridaCommand(t.target,[`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),[])}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,target:e.target,pid:e.pid,status:e.status}))}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,r){let i=await this.getAvailability();if(!i.available)return{output:``,error:i.reason??`Frida CLI is not available`};let a=i.path??`frida`,o=[...this.buildTargetArgs(e),`--runtime=v8`,`-q`,`-e`,r];try{let e=await this.execFileUtf8(a,o,n),t=e.stdout.trim(),r=e.stderr.trim();return r?{output:t,error:r}:{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}}}buildTargetArgs(e){return/^\d+$/.test(e)?[`-p`,e]:e.includes(`/`)||e.includes(`\\`)?[`-f`,e]:[`-n`,e]}parseModuleList(e){let t=this.extractJsonPayload(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.extractJsonPayload(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.extractJsonPayload(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}extractJsonPayload(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(`
|
|
2
|
+
`)}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(`
|
|
3
|
+
`)}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(`
|
|
4
|
+
`);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(`D:\\coding\\security`),t(`D:\\tools`),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(`
|
|
5
|
+
`)}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(`
|
|
6
|
+
`)}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 payload tracing`;case`network`:return`Network hook for request and payload 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(`
|
|
7
|
+
`);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(`
|
|
8
|
+
`)}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(`
|
|
9
|
+
`)}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,n=`arm`,i){let o=i??process.env.UNIDBG_JAR;if(!o)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var or pass jarPath.`);try{await g(o)}catch{throw new a(`NOT_FOUND`,`Unidbg JAR not found: ${o}`)}try{await g(e)}catch{throw new a(`NOT_FOUND`,`Shared library not found: ${e}`)}let c=w(),l=this.getJavaCommand(),u=[`-jar`,o,`--so`,e,`--arch`,n,`--server`];try{let t=await this.execFileUtf8(l,u,r),i=this.parseLaunchOutput(t.stdout,c),a={id:i.id,soPath:e,arch:n,startedAt:new Date().toISOString(),childProcess:i.pid?{pid:i.pid}:void 0};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}catch(r){let i=r instanceof Error?r.message:String(r);t.warn(`[binary-instrument] Unidbg launch failed, registering stub session`,{soPath:e,message:i});let a={id:c,soPath:e,arch:n,startedAt:new Date().toISOString()};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}}async callFunction(e,t,n={}){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let i=process.env.UNIDBG_JAR;if(!i)return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:``,trace:[`mock-unidbg-unavailable`],_note:`Unidbg emulation requires UNIDBG_JAR to be configured`};let o=this.getJavaCommand(),s=[`-jar`,i,`--session`,e,`--call`,t,`--args`,JSON.stringify(n)];try{let i=await this.execFileUtf8(o,s,r);return{sessionId:e,functionName:t,args:n,returnValue:this.extractReturnValue(i.stdout),stdout:i.stdout.trim(),stderr:i.stderr.trim(),trace:[]}}catch(r){return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:r instanceof Error?r.message:String(r),trace:[`error`]}}}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)return{sessionId:e,trace:[`mock-unidbg-unavailable`],_note:`Unidbg tracing requires UNIDBG_JAR to be configured`};let n=this.getJavaCommand(),i=[`-jar`,t,`--session`,e,`--trace`];try{let t=await this.execFileUtf8(n,i,r);return{sessionId:e,trace:this.parseTraceOutput(t.stdout),instructionCount:this.countInstructions(t.stdout)}}catch(t){return{sessionId:e,trace:[`error`],error:t instanceof Error?t.message:String(t)}}}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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
2
|
-
`)||e.includes(`\r`)||e.includes(`CLIENT_`)||e.trim().startsWith(`#`)?m(e):new h(e).parseKeyLog()}function b(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 x(e,t,n){let r=u(t),i=n?.trim();for(let t of e)if(t.clientRandom===r&&!(i&&t.label!==i))return t.secret;return null}function S(e,t,r
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{a as t}from"./outputPaths-D2ddHrOJ.mjs";import{existsSync as n,readFileSync as r}from"node:fs";import{dirname as i,resolve as a}from"node:path";import{mkdir as o,writeFile as s}from"node:fs/promises";import{createDecipheriv as c,randomUUID as l}from"node:crypto";function u(e){return e.replace(/\s+/g,``).toUpperCase()}function d(e){return e.length>0&&e.length%2==0&&/^[0-9A-F]+$/i.test(e)}function f(e){if(!e)return;let t=new Date(e);if(!Number.isNaN(t.valueOf()))return t.toISOString()}function p(){return a(t(),`jshook-boringssl-${l()}.log`)}function m(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=f(r[3]);if(!i||!a||!o)continue;let c=u(a),l=u(o);if(!d(c)||!d(l))continue;let p={label:i,clientRandom:c,secret:l};s&&(p.timestamp=s),t.push(p)}return t}var h=class{keyLogPath;cachedEntries=[];secretByClientRandom=new Map;constructor(e){this.keyLogPath=a(e??p())}async enableKeyLog(){return await o(i(this.keyLogPath),{recursive:!0}),await s(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=a(e??this.keyLogPath);if(!n(t))return this.cachedEntries=[],this.secretByClientRandom.clear(),[];let i=m(r(t,`utf8`));this.cachedEntries=i,this.secretByClientRandom.clear();for(let e of i)this.secretByClientRandom.set(e.clientRandom,e.secret);return i}decryptPayload(e,t){let n=u(e);if(!d(n)||t.length===0||!t.some(e=>e.secret.length>0))return null;try{return Buffer.from(n,`hex`)}catch{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=u(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 g(e=`/tmp/sslkeylog.log`){return process.env.SSLKEYLOGFILE=e,e}function _(){delete process.env.SSLKEYLOGFILE}function v(){let e=process.env.SSLKEYLOGFILE;return!e||e.trim().length===0?null:e}function y(e){return e.length===0?[]:e.includes(`
|
|
2
|
+
`)||e.includes(`\r`)||e.includes(`CLIENT_`)||e.trim().startsWith(`#`)?m(e):new h(e).parseKeyLog()}function b(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 x(e,t,n){let r=u(t),i=n?.trim();for(let t of e)if(t.clientRandom===r&&!(i&&t.label!==i))return t.secret;return null}function S(e,t,n,r=`aes-256-gcm`,i){try{let a=Buffer.from(u(e),`hex`),o=c(r,Buffer.from(u(t),`hex`),Buffer.from(u(n),`hex`));if(i){let e=Reflect.get(o,`setAuthTag`);typeof e==`function`&&e.call(o,Buffer.from(u(i),`hex`))}return Buffer.concat([o.update(a),o.final()]).toString(`utf8`)}catch{return`DECRYPTION_FAILED:${r}`}}var C=e({TLSKeyLogExtractor:()=>h});export{g as a,y as c,_ as i,b as l,h as n,v as o,S as r,x as s,C as t};
|