@jshookmcp/jshook 0.3.0 → 0.3.2
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/LICENSE +661 -661
- package/README.md +32 -49
- package/README.zh.md +32 -47
- package/dist/AntiCheatDetector-B6d4Qe9D.mjs +1 -0
- package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
- package/dist/CacheAdapters-CsNtQIR8.mjs +1 -0
- package/dist/CodeInjector-Cll_7bLJ.mjs +1 -0
- package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
- package/dist/DOMInspector-C19J4zeq.mjs +95 -0
- package/dist/DarwinAPI-ZfQdpLNI.mjs +1 -0
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
- package/dist/EventBus-DL8iLA09.mjs +1 -0
- package/dist/EvidenceGraphBridge-BtbwXsLC.mjs +1 -0
- package/dist/ExtensionManager-BD724zkO.mjs +1 -0
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
- package/dist/FingerprintManager-DT0EAUEo.mjs +1 -0
- package/dist/HardwareBreakpoint-BUfPdp0f.mjs +1 -0
- package/dist/HeapAnalyzer-B_aqY8oj.mjs +1 -0
- package/dist/{HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +66 -101
- package/dist/InstrumentationSession-D_G1ZPyd.mjs +1 -0
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
- package/dist/MemoryController-X1XNSn1n.mjs +2 -0
- package/dist/MemoryScanSession-DG_F-PjE.mjs +1 -0
- package/dist/MemoryScanner-g1_L1ub5.mjs +1 -0
- package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +1 -0
- package/dist/NativeMemoryManager.utils-BHy1P_jM.mjs +1 -0
- package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
- package/dist/PEAnalyzer-yWQaGrcx.mjs +1 -0
- package/dist/PageController-Dfsm1_o7.mjs +1 -0
- package/dist/PointerChainEngine-BhCUkmxY.mjs +1 -0
- package/dist/PrerequisiteError-BjCQA-gK.mjs +1 -0
- package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
- package/dist/ResponseBuilder-BfWP-uaT.mjs +1 -0
- package/dist/ReverseEvidenceGraph-BhSYYdiI.mjs +2 -0
- package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
- package/dist/ScriptManager-LWGPTdvD.mjs +7 -0
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
- package/dist/Speedhack-yseDPSZ9.mjs +1 -0
- package/dist/StealthVerifier-BmcxfwSF.mjs +1 -0
- package/dist/StructureAnalyzer-C5lpuZkg.mjs +2 -0
- package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
- package/dist/ToolError-DWU_z7gp.mjs +1 -0
- package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
- package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
- package/dist/ToolRouter.policy-CfhJczkt.mjs +4 -0
- package/dist/TraceRecorder-BiJWBXHX.mjs +272 -0
- package/dist/VersionDetector-CHT36Az0.mjs +9 -0
- package/dist/Win32API-eUCF57l_.mjs +1 -0
- package/dist/Win32Debug-CYrIQBvr.mjs +1 -0
- package/dist/WorkflowEngine-D876meOO.mjs +1 -0
- package/dist/analysis-D4swdMvq.mjs +6 -0
- package/dist/{antidebug-BRKeyt27.mjs → antidebug-7L3ygj_9.mjs} +8 -259
- package/dist/apk-packer-BqXcInnX.mjs +1 -0
- package/dist/artifactRetention-BCPQASm7.mjs +1 -0
- package/dist/artifacts-CkodUM4j.mjs +1 -0
- package/dist/authorization-schema-BOFwSXUN.mjs +1 -0
- package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
- package/dist/binary-instrument-DU7V6TUM.mjs +7 -0
- package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
- package/dist/bind-helpers-m2U8glkF.mjs +1 -0
- package/dist/boringssl-inspector-BBaJwwkU.mjs +2 -0
- package/dist/browser-Qqco2rOT.mjs +11 -0
- package/dist/capabilities-CyXuKUl1.mjs +1 -0
- package/dist/chunk-C_pMuVsO.mjs +1 -0
- package/dist/collector-Bpl6qy2L.mjs +1 -0
- package/dist/concurrency-DCr8WQ2M.mjs +1 -0
- package/dist/constants-BYj8Xek8.mjs +1 -0
- package/dist/coordination-CWXW1o8K.mjs +1 -0
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/debugger-DyALjYMk.mjs +1 -0
- package/dist/definitions-BWxBke3r.mjs +1 -0
- package/dist/definitions-BYwATKc-.mjs +1 -0
- package/dist/definitions-B_83XfNQ.mjs +1 -0
- package/dist/definitions-Bf3H1EwV.mjs +1 -0
- package/dist/definitions-BftdXgXI.mjs +1 -0
- package/dist/definitions-Bio5XJYy.mjs +1 -0
- package/dist/definitions-C3qNgSn1.mjs +1 -0
- package/dist/definitions-CB6vmOer.mjs +1 -0
- package/dist/definitions-CMZRSy3k.mjs +1 -0
- package/dist/definitions-CQd7yCQH.mjs +1 -0
- package/dist/definitions-CT8ln6GQ.mjs +1 -0
- package/dist/definitions-Cenu6mxo.mjs +1 -0
- package/dist/definitions-D4g-MS10.mjs +1 -0
- package/dist/definitions-D5wl_8HN.mjs +1 -0
- package/dist/definitions-DAQm1Xar.mjs +1 -0
- package/dist/definitions-DP1vgxEY.mjs +1 -0
- package/dist/definitions-DxFNRQNK2.mjs +1 -0
- package/dist/definitions-Ibci7e_L.mjs +1 -0
- package/dist/definitions-OeLvmlQy.mjs +1 -0
- package/dist/definitions-RZYGD_Ey.mjs +1 -0
- package/dist/definitions-Tls8c0A0.mjs +1 -0
- package/dist/definitions-bybDvnG0.mjs +26 -0
- package/dist/definitions-l7TjdE6V.mjs +1 -0
- package/dist/encoding-ycOaz8Vr.mjs +2 -0
- package/dist/ensure-browser-core-DxWC-NTp.mjs +1 -0
- package/dist/evidence-graph-bridge-CV_UdYqj.mjs +1 -0
- package/dist/factory-CKr4fAE1.mjs +1 -0
- package/dist/flat-target-session-DvcQX7J5.mjs +1 -0
- package/dist/formatAddress-vLA_hOJt.mjs +1 -0
- package/dist/graphql-B2TiPEow.mjs +62 -0
- package/dist/handlers-0yKLRIfo.mjs +2 -0
- package/dist/handlers-8zN_vBIz.mjs +1 -0
- package/dist/handlers-B62K4FTc.mjs +1 -0
- package/dist/handlers-BpDlVVVU.mjs +1 -0
- package/dist/handlers-CMJK7m1c.mjs +31 -0
- package/dist/handlers-D2ZOul9p.mjs +54 -0
- package/dist/handlers-D5E40ssn.mjs +5 -0
- package/dist/handlers-DGbdQAgD.mjs +4 -0
- package/dist/handlers-DHO3rjsW.mjs +1 -0
- package/dist/handlers-FJ80VzUI.mjs +2 -0
- package/dist/handlers-VHWrxbM_.mjs +1 -0
- package/dist/handlers-l8QIKqBj.mjs +2 -0
- package/dist/handlers-mPFiNPe8.mjs +302 -0
- package/dist/{handlers-Dz9PYsCa.mjs → handlers-yo_xYzT8.mjs} +118 -904
- package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
- package/dist/hooks-D4XLfgtV.mjs +600 -0
- package/dist/index.mjs +13 -5240
- package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
- package/dist/logger-sBC6IdRT.mjs +1 -0
- package/dist/maintenance-BUpIukhg.mjs +1 -0
- package/dist/manifest-0Jpt_AQa.mjs +1 -0
- package/dist/manifest-B3fZbSWR.mjs +1 -0
- package/dist/manifest-B7NB2rh2.mjs +1 -0
- package/dist/manifest-BDi4nbH1.mjs +1 -0
- package/dist/manifest-BLDfkE7n.mjs +1 -0
- package/dist/manifest-BcXbB4gf.mjs +1 -0
- package/dist/manifest-Bdnc_vrc.mjs +1 -0
- package/dist/manifest-BuYKgCnp.mjs +1 -0
- package/dist/manifest-CBfNnGPV.mjs +1 -0
- package/dist/manifest-CPS1Xv69.mjs +1 -0
- package/dist/manifest-CQH9FhwI.mjs +1 -0
- package/dist/manifest-CRryuZF4.mjs +1 -0
- package/dist/manifest-CctIumog.mjs +1 -0
- package/dist/manifest-CvTe5ZGV2.mjs +1 -0
- package/dist/manifest-D-5GH0DV.mjs +1 -0
- package/dist/manifest-D3Ssf3IC.mjs +1 -0
- package/dist/manifest-D5ck3NvC.mjs +1 -0
- package/dist/manifest-D9jUUJAu.mjs +1 -0
- package/dist/manifest-DCx6w2XV.mjs +1 -0
- package/dist/manifest-DG19q-Ld.mjs +1 -0
- package/dist/manifest-DLMlD0Zc.mjs +1 -0
- package/dist/manifest-DYpn8w_h.mjs +1 -0
- package/dist/manifest-DYzWI8Xs.mjs +1 -0
- package/dist/manifest-D_obs5F4.mjs +1 -0
- package/dist/manifest-DujQqEQR.mjs +2 -0
- package/dist/manifest-DwL2ik8P.mjs +1 -0
- package/dist/manifest-ItF5P8A12.mjs +1 -0
- package/dist/manifest-KZphqIyX.mjs +1 -0
- package/dist/manifest-LG42zPLY2.mjs +1 -0
- package/dist/manifest-LLdI5m4T.mjs +1 -0
- package/dist/manifest-QYbQXJn0.mjs +1 -0
- package/dist/manifest-RcpX_MyZ.mjs +123 -0
- package/dist/manifest-YgVd8Sgz.mjs +1 -0
- package/dist/manifest-Zy7Odg5J.mjs +1 -0
- package/dist/manifest-ff1H7Pdp.mjs +1 -0
- package/dist/manifest-iuhF6pTL2.mjs +1 -0
- package/dist/manifest-nXHmtMSp2.mjs +1 -0
- package/dist/manifest-xWfu6iLo.mjs +1 -0
- package/dist/manifest-yC16OhL2.mjs +1 -0
- package/dist/manifest-ztWJoXy4.mjs +1 -0
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +1 -0
- package/dist/modules-BPBcSaM-.mjs +333 -0
- package/dist/mojo-ipc-BhwsdVUW.mjs +9 -0
- package/dist/native/scripts/linux/enum-windows.sh +12 -12
- package/dist/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/native-j8l473zn.mjs +961 -0
- package/dist/network-T0VRwNPd.mjs +7 -0
- package/dist/outputPaths-B4Ic4RZh.mjs +2 -0
- package/dist/parse-args-Bw413PlW.mjs +1 -0
- package/dist/platform-CzaQtISh.mjs +93 -0
- package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +1 -0
- package/dist/process-CWhsCWrf.mjs +2 -0
- package/dist/proxy-DZFlDsG3.mjs +2 -0
- package/dist/registry-DH4sc1dt.mjs +1 -0
- package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
- package/dist/response-C7rKQst4.mjs +1 -0
- package/dist/search-defaults-lYBVn_3L.mjs +1 -0
- package/dist/server/plugin-api.d.mts +19 -36
- package/dist/server/plugin-api.mjs +1 -293
- package/dist/shared-state-board-BSjXLUV1.mjs +1 -0
- package/dist/sourcemap-Dh3Ai_ur.mjs +1 -0
- package/dist/ssrf-policy-CsIJGkpd.mjs +1 -0
- package/dist/streaming-BcJ0B6ao.mjs +1 -0
- package/dist/tool-builder-qif8M9-K.mjs +1 -0
- package/dist/transform-DOxzeWPB.mjs +103 -0
- package/dist/types-D9EiE5o9.mjs +1 -0
- package/dist/types-Fz69RzbZ.mjs +1 -0
- package/dist/wasm-CZ_HTfKR.mjs +174 -0
- package/dist/webcrack-C1iYG_EX.mjs +46 -0
- package/dist/workflow-BdwQmARn.mjs +101 -0
- package/package.json +55 -82
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/AntiCheatDetector-CqGDXmfc.mjs +0 -350
- package/dist/CacheAdapters-jJFy20G-.mjs +0 -80
- package/dist/CodeInjector-BdjRfNx7.mjs +0 -150
- package/dist/ConsoleMonitor-DykL3IAw.mjs +0 -2269
- package/dist/DarwinAPI-ETyy0xyo.mjs +0 -363
- package/dist/DetailedDataManager-HT49OrvF.mjs +0 -217
- package/dist/EventBus-DFKvADm3.mjs +0 -141
- package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +0 -153
- package/dist/ExtensionManager-BDMsY2Dz.mjs +0 -721
- package/dist/FingerprintManager-BN4UQWnX.mjs +0 -96
- package/dist/HardwareBreakpoint-Cc2AFq1Y.mjs +0 -239
- package/dist/HeapAnalyzer-DruMgsgj.mjs +0 -284
- package/dist/InstrumentationSession-DLH0vd-z.mjs +0 -244
- package/dist/MemoryController-CMtviNW_.mjs +0 -167
- package/dist/MemoryScanSession-ITgb_NMi.mjs +0 -278
- package/dist/MemoryScanner-CiL7Z3ey.mjs +0 -428
- package/dist/NativeMemoryManager.impl-D9Lkovvn.mjs +0 -485
- package/dist/NativeMemoryManager.utils-BBlAixF5.mjs +0 -165
- package/dist/PEAnalyzer-DMQ44gen.mjs +0 -385
- package/dist/PageController-BPJNqqBN.mjs +0 -431
- package/dist/PointerChainEngine-K7wN8Z-w.mjs +0 -325
- package/dist/PrerequisiteError-TuyZIs6n.mjs +0 -20
- package/dist/ProcessRegistry-zGg12QbE.mjs +0 -74
- package/dist/ResponseBuilder-CJXWmWNw.mjs +0 -143
- package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +0 -269
- package/dist/ScriptManager-ZuWD-0Jg.mjs +0 -3003
- package/dist/Speedhack-D-z0umeT.mjs +0 -156
- package/dist/StealthVerifier-BWmPgQsv.mjs +0 -135
- package/dist/StructureAnalyzer-Cav5AVSL.mjs +0 -429
- package/dist/ToolCatalog-5OJdMiF0.mjs +0 -582
- package/dist/ToolError-jh9whhMd.mjs +0 -15
- package/dist/ToolProbe-DbCFGyrg.mjs +0 -45
- package/dist/ToolRegistry-B9krbTtI.mjs +0 -180
- package/dist/ToolRouter.policy-BGDAGyeH.mjs +0 -344
- package/dist/TraceRecorder-B41Z5XBj.mjs +0 -1286
- package/dist/VersionDetector-K3V4vGsw.mjs +0 -104
- package/dist/Win32API-C2kjj0ze.mjs +0 -346
- package/dist/Win32Debug-CKrGOTpo.mjs +0 -274
- package/dist/WorkflowEngine-DJ6M4opp.mjs +0 -569
- package/dist/analysis-BHeJW2Nb.mjs +0 -1234
- package/dist/artifactRetention-CPXkUJXp.mjs +0 -598
- package/dist/artifacts-DkfosXH3.mjs +0 -59
- package/dist/authorization-schema-DRqyJMSk.mjs +0 -31
- package/dist/betterSqlite3-DLSBZodi.mjs +0 -74
- package/dist/binary-instrument--V3MAhJ4.mjs +0 -971
- package/dist/bind-helpers-ClV34xdn.mjs +0 -42
- package/dist/boringssl-inspector-Bo_LOLaS.mjs +0 -180
- package/dist/browser-Dx3_S2cG.mjs +0 -4369
- package/dist/capabilities-CcHlvWgK.mjs +0 -33
- package/dist/chunk-CjcI7cDX.mjs +0 -15
- package/dist/concurrency-Drev_Vz9.mjs +0 -41
- package/dist/constants-CDZLOoVv.mjs +0 -534
- package/dist/coordination-DgItD9DL.mjs +0 -259
- package/dist/debugger-RS3RSAqs.mjs +0 -1288
- package/dist/definitions-BEoYofW5.mjs +0 -47
- package/dist/definitions-BRaefg3u.mjs +0 -365
- package/dist/definitions-BbkvZkiv.mjs +0 -96
- package/dist/definitions-BtWSHJ3o.mjs +0 -17
- package/dist/definitions-C1gCHO0i.mjs +0 -43
- package/dist/definitions-CDOg_b-l.mjs +0 -138
- package/dist/definitions-CVPD9hzZ.mjs +0 -54
- package/dist/definitions-Cea8Lgl7.mjs +0 -94
- package/dist/definitions-DAgIyjxM.mjs +0 -10
- package/dist/definitions-DJA27nsL.mjs +0 -66
- package/dist/definitions-DKPFU3LW.mjs +0 -25
- package/dist/definitions-DPRpZQ96.mjs +0 -47
- package/dist/definitions-DUE5gmdn.mjs +0 -18
- package/dist/definitions-DYVjOtxa.mjs +0 -26
- package/dist/definitions-DcYLVLCo.mjs +0 -37
- package/dist/definitions-Pp5LI2H4.mjs +0 -27
- package/dist/definitions-j9KdHVNR.mjs +0 -14
- package/dist/definitions-uzkjBwa7.mjs +0 -258
- package/dist/definitions-va-AnLuQ.mjs +0 -28
- package/dist/encoding-DJeqHmpd.mjs +0 -1079
- package/dist/evidence-graph-bridge-DcYizFk2.mjs +0 -136
- package/dist/factory-C90tBff6.mjs +0 -575
- package/dist/flat-target-session-Dgax2Cy3.mjs +0 -29
- package/dist/formatAddress-nnMvEohD.mjs +0 -17
- package/dist/graphql-CoHrhweh.mjs +0 -1197
- package/dist/handlers-4jmR0nMs.mjs +0 -898
- package/dist/handlers-BAHPxcch.mjs +0 -789
- package/dist/handlers-BOs9b907.mjs +0 -2600
- package/dist/handlers-BWXEy6ef.mjs +0 -917
- package/dist/handlers-Bndn6QvE.mjs +0 -111
- package/dist/handlers-BqC4bD4s.mjs +0 -681
- package/dist/handlers-BtYq60bM2.mjs +0 -276
- package/dist/handlers-BzgcB4iv.mjs +0 -799
- package/dist/handlers-CRyRWj2b.mjs +0 -859
- package/dist/handlers-CVv2H1uq.mjs +0 -592
- package/dist/handlers-Dl5a7JS4.mjs +0 -572
- package/dist/handlers-Dx2d7jt7.mjs +0 -2537
- package/dist/handlers-HujRKC3b.mjs +0 -661
- package/dist/handlers.impl-XWXkQfyi.mjs +0 -807
- package/dist/hooks-B1B8NRHL.mjs +0 -898
- package/dist/logger-Dh_xb7_2.mjs +0 -93
- package/dist/maintenance-PRMkLVRW.mjs +0 -835
- package/dist/manifest-67Bok-Si.mjs +0 -58
- package/dist/manifest-6lNTMZAB2.mjs +0 -87
- package/dist/manifest-B2duEHiH.mjs +0 -90
- package/dist/manifest-B6EY9Vm8.mjs +0 -57
- package/dist/manifest-B6nKSbyY.mjs +0 -95
- package/dist/manifest-BL8AQNPF.mjs +0 -106
- package/dist/manifest-BSZvJJmV.mjs +0 -47
- package/dist/manifest-BU7qzUyX.mjs +0 -418
- package/dist/manifest-Bl62e8WK.mjs +0 -49
- package/dist/manifest-Bo5cXjdt.mjs +0 -82
- package/dist/manifest-BpS4gtUK.mjs +0 -1347
- package/dist/manifest-Bv65_e2W.mjs +0 -101
- package/dist/manifest-BytNIF4Z.mjs +0 -117
- package/dist/manifest-C-xtsjS3.mjs +0 -81
- package/dist/manifest-CDYl7OhA.mjs +0 -66
- package/dist/manifest-CRZ3xmkD.mjs +0 -61
- package/dist/manifest-CoW6u4Tp.mjs +0 -132
- package/dist/manifest-Cq5zN_8A.mjs +0 -50
- package/dist/manifest-D7YZM_2e.mjs +0 -194
- package/dist/manifest-DE_VrAeQ.mjs +0 -314
- package/dist/manifest-DGsXSCpT.mjs +0 -39
- package/dist/manifest-DJ2vfEuW.mjs +0 -156
- package/dist/manifest-DPXDYhEu.mjs +0 -80
- package/dist/manifest-Dd4fQb0a.mjs +0 -322
- package/dist/manifest-Deq6opGg.mjs +0 -223
- package/dist/manifest-DfJTafJK.mjs +0 -37
- package/dist/manifest-DgOdgN_j.mjs +0 -50
- package/dist/manifest-DlbMW4v4.mjs +0 -47
- package/dist/manifest-DmVfbH0w.mjs +0 -374
- package/dist/manifest-Dog6Ddjr.mjs +0 -109
- package/dist/manifest-DvgU5FWb.mjs +0 -58
- package/dist/manifest-HsfDBs7j.mjs +0 -50
- package/dist/manifest-I8oQHvCG.mjs +0 -186
- package/dist/manifest-NvH_a-av.mjs +0 -786
- package/dist/manifest-cEJU1v0Z.mjs +0 -129
- package/dist/manifest-wOl5XLB12.mjs +0 -112
- package/dist/modules-tZozf0LQ.mjs +0 -10635
- package/dist/mojo-ipc-DXNEXEqb.mjs +0 -640
- package/dist/network-CPVvwvFg.mjs +0 -3852
- package/dist/outputPaths-um7lCRY3.mjs +0 -1141
- package/dist/parse-args-B4cY5Vx5.mjs +0 -39
- package/dist/platform-CYeFoTWp.mjs +0 -2161
- package/dist/process-BTbgcVc6.mjs +0 -1306
- package/dist/proxy-r8YN6nP1.mjs +0 -192
- package/dist/registry-Bl8ZQW61.mjs +0 -34
- package/dist/response-CWhh2aLo.mjs +0 -34
- package/dist/shared-state-board-BoZnSoj-.mjs +0 -586
- package/dist/sourcemap-BIDHUVXy.mjs +0 -934
- package/dist/ssrf-policy-Dsqd-DTX.mjs +0 -166
- package/dist/streaming-Dal6utPp.mjs +0 -725
- package/dist/tool-builder-BHJp32mV.mjs +0 -186
- package/dist/transform-DRVgGG90.mjs +0 -1011
- package/dist/types-Bx92KJfT.mjs +0 -4
- package/dist/types-DDBWs9UP.mjs +0 -37
- package/dist/wasm-BYx5UOeG.mjs +0 -1044
- package/dist/webcrack-Be0_FccV.mjs +0 -747
- package/dist/workflow-BpuKEtvn.mjs +0 -725
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import{n as e}from"./chunk-C_pMuVsO.mjs";import{i as t}from"./artifacts-CkodUM4j.mjs";import{t as n}from"./betterSqlite3-Brtq-SIQ.mjs";import{randomUUID as r}from"node:crypto";import{writeFile as i}from"node:fs/promises";const a={Debugger:[`Debugger.paused`,`Debugger.resumed`,`Debugger.scriptParsed`],Runtime:[`Runtime.consoleAPICalled`,`Runtime.exceptionThrown`],Network:[`Network.requestWillBeSent`,`Network.requestServedFromCache`,`Network.responseReceived`,`Network.dataReceived`,`Network.loadingFinished`,`Network.loadingFailed`,`Network.eventSourceMessageReceived`,`Network.webSocketCreated`,`Network.webSocketWillSendHandshakeRequest`,`Network.webSocketHandshakeResponseReceived`,`Network.webSocketFrameReceived`,`Network.webSocketFrameSent`,`Network.webSocketFrameError`,`Network.webSocketClosed`],Page:[`Page.navigatedWithinDocument`,`Page.loadEventFired`]},o=[`Debugger`,`Runtime`,`Network`,`Page`],s={recordResponseBodies:!0,streamResponseChunks:!0,maxBodyBytes:10*1024*1024,inlineBodyBytes:256*1024},c=16*1024,l=e=>typeof e==`object`&&!!e,u=e=>typeof e==`string`?e:null,d=e=>typeof e==`number`&&Number.isFinite(e)?e:null,f=e=>{let t=d(e);return t===null?null:t>0xe8d4a51000?t:t*1e3},p=e=>l(e)&&typeof e.body==`string`&&typeof e.base64Encoded==`boolean`,m=e=>{let t=Date.now();if(!l(e))return{timestamp:t,wallTime:t,monotonicTime:null};let n=f(e.wallTime),r=f(e.timestamp);return{timestamp:n??t,wallTime:n??t,monotonicTime:r}},h=e=>l(e)&&typeof e.requestId==`string`?e.requestId:null,g=(e,t)=>{let n=null,r=null;if(!l(t))return{scriptId:n,lineNumber:r};if(`scriptId`in t&&(n=String(t.scriptId)),`lineNumber`in t&&(r=Number(t.lineNumber)||null),e===`Debugger.paused`&&Array.isArray(t.callFrames)){let e=t.callFrames[0];if(e){let t=e.location;t&&(n=String(t.scriptId??n),r=Number(t.lineNumber??r)||null)}}return{scriptId:n,lineNumber:r}},_=(e,t)=>{if(!l(t))return t??{};let n={...t};if(e===`Network.dataReceived`&&typeof n.data==`string`){let e=n.data;n.hasChunkData=!0,n.chunkDataBytes=Buffer.byteLength(e,`utf8`),n.data=`[captured in network_chunks]`}if(e===`Network.eventSourceMessageReceived`&&typeof n.data==`string`&&Buffer.byteLength(n.data,`utf8`)>c&&(n.data=`${n.data.slice(0,c)}...[truncated]`,n.truncatedData=!0),(e===`Network.webSocketFrameReceived`||e===`Network.webSocketFrameSent`)&&l(n.response)&&typeof n.response.payloadData==`string`){let e={...n.response},t=e.payloadData;Buffer.byteLength(t,`utf8`)>c&&(e.payloadData=`${t.slice(0,c)}...[truncated]`,e.truncatedPayloadData=!0,n.response=e)}return n},v=e=>{let t=u(e.remoteIPAddress),n=d(e.remotePort);return t?n===null?t:`${t}:${n}`:null},y=e=>({requestId:e,url:null,method:null,resourceType:null,requestHeaders:`{}`,requestPostData:null,status:null,statusText:null,responseHeaders:`{}`,mimeType:null,protocol:null,remoteAddress:null,fromDiskCache:!1,fromServiceWorker:!1,startedWallTime:null,responseWallTime:null,finishedWallTime:null,startedMonotonicTime:null,responseMonotonicTime:null,finishedMonotonicTime:null,encodedDataLength:null,receivedDataLength:0,receivedEncodedDataLength:0,chunkCount:0,streamingEnabled:!1,streamingSupported:null,streamingError:null,bodyCaptureState:`none`,bodyInline:null,bodyArtifactPath:null,bodyBase64Encoded:!1,bodySize:null,bodyTruncated:!1,bodyError:null,failed:!1,errorText:null});var b=class{deps;resources=new Map;options={...s};counts={networkRequestCount:0,networkChunkCount:0,networkBodyCount:0};constructor(e){this.deps=e}configure(e){return this.resources.clear(),this.counts={networkRequestCount:0,networkChunkCount:0,networkBodyCount:0},this.options={...s,...e},this.getOptions()}clear(){this.resources.clear(),this.counts={networkRequestCount:0,networkChunkCount:0,networkBodyCount:0}}getOptions(){return{...this.options}}getCounts(){return{...this.counts}}handleEvent(e,t,n){let r=h(t);if(r)switch(e){case`Network.requestWillBeSent`:this.handleRequestWillBeSent(r,t,n);return;case`Network.requestServedFromCache`:this.handleRequestServedFromCache(r);return;case`Network.responseReceived`:this.handleResponseReceived(r,t,n);return;case`Network.dataReceived`:this.handleDataReceived(r,t,n);return;case`Network.loadingFinished`:this.handleLoadingFinished(r,t,n);return;case`Network.loadingFailed`:this.handleLoadingFailed(r,t,n);return;default:return}}handleRequestWillBeSent(e,t,n){let r=this.getOrCreateResource(e),i=l(t)&&l(t.request)?t.request:null;r.url=i?u(i.url):r.url,r.method=i?u(i.method):r.method,r.resourceType=l(t)&&typeof t.type==`string`?t.type:r.resourceType,r.requestHeaders=i?JSON.stringify(i.headers??{}):r.requestHeaders,r.requestPostData=i?u(i.postData):r.requestPostData,r.startedWallTime=n.wallTime??r.startedWallTime??n.timestamp,r.startedMonotonicTime=n.monotonicTime??r.startedMonotonicTime,this.syncResource(r)}handleRequestServedFromCache(e){let t=this.getOrCreateResource(e);t.fromDiskCache=!0,this.syncResource(t)}handleResponseReceived(e,t,n){let r=this.getOrCreateResource(e),i=l(t)&&l(t.response)?t.response:null;r.url=i?u(i.url)??r.url:r.url,r.status=i?d(i.status):r.status,r.statusText=i?u(i.statusText):r.statusText,r.responseHeaders=i?JSON.stringify(i.headers??{}):r.responseHeaders,r.mimeType=i?u(i.mimeType):r.mimeType,r.protocol=i?u(i.protocol):r.protocol,r.remoteAddress=i?v(i):r.remoteAddress,r.fromDiskCache=i?!!i.fromDiskCache:r.fromDiskCache,r.fromServiceWorker=i?!!i.fromServiceWorker:r.fromServiceWorker,r.responseWallTime=n.wallTime??r.responseWallTime??n.timestamp,r.responseMonotonicTime=n.monotonicTime??r.responseMonotonicTime,this.syncResource(r),this.options.streamResponseChunks&&r.streamingSupported===null&&this.deps.trackOperation(this.enableStreamingForRequest(e))}handleDataReceived(e,t,n){let r=this.getOrCreateResource(e),i=l(t)?t:null,a=i?d(i.dataLength)??0:0,o=i?d(i.encodedDataLength)??0:0,s=i?u(i.data):null;r.receivedDataLength+=a,r.receivedEncodedDataLength+=o,r.chunkCount+=1;let c=r.receivedDataLength<=this.options.maxBodyBytes,f={requestId:e,sequence:r.chunkCount,timestamp:n.timestamp,monotonicTime:n.monotonicTime,dataLength:a,encodedDataLength:o,chunkData:c?s:null,chunkIsBase64:s!==null};try{this.deps.getDb()?.insertNetworkChunk(f),this.counts.networkChunkCount++}catch{}this.syncResource(r)}handleLoadingFinished(e,t,n){let r=this.getOrCreateResource(e);r.finishedWallTime=n.wallTime??n.timestamp,r.finishedMonotonicTime=n.monotonicTime??r.finishedMonotonicTime,l(t)&&(r.encodedDataLength=d(t.encodedDataLength)??r.encodedDataLength),this.syncResource(r),this.options.recordResponseBodies&&this.deps.trackOperation(this.captureResponseBody(e))}handleLoadingFailed(e,t,n){let r=this.getOrCreateResource(e);r.finishedWallTime=n.wallTime??n.timestamp,r.finishedMonotonicTime=n.monotonicTime??r.finishedMonotonicTime,r.failed=!0,r.errorText=l(t)?u(t.errorText):null,this.syncResource(r)}async enableStreamingForRequest(e){let t=this.deps.getCdpSession(),n=this.deps.getDb();if(!t||!n||!this.options.streamResponseChunks)return;let r=this.resources.get(e);if(!(!r||r.streamingSupported!==null))try{let i=await t.send(`Network.streamResourceContent`,{requestId:e});if(r.streamingEnabled=!0,r.streamingSupported=!0,r.streamingError=null,l(i)){let t=u(i.bufferedData);if(t){let i=Buffer.from(t,`base64`).length,a={requestId:e,sequence:r.chunkCount+1,timestamp:Date.now(),monotonicTime:r.responseMonotonicTime,dataLength:i,encodedDataLength:i,chunkData:r.receivedDataLength+i<=this.options.maxBodyBytes?t:null,chunkIsBase64:!0};r.chunkCount+=1,r.receivedDataLength+=i,r.receivedEncodedDataLength+=i,n.insertNetworkChunk(a),this.counts.networkChunkCount++}}}catch(e){r.streamingEnabled=!1,r.streamingSupported=!1,r.streamingError=e instanceof Error?e.message:String(e)}finally{this.syncResource(r)}}async captureResponseBody(e){let n=this.deps.getCdpSession();if(!n||!this.deps.getDb()||!this.options.recordResponseBodies)return;let r=this.resources.get(e);if(r)try{let a=await n.send(`Network.getResponseBody`,{requestId:e});if(!p(a))return;if(r.bodyBase64Encoded=a.base64Encoded,r.bodySize=a.base64Encoded?Buffer.from(a.body,`base64`).length:Buffer.byteLength(a.body,`utf8`),r.bodyTruncated=r.bodySize>this.options.maxBodyBytes,r.bodyTruncated)r.bodyCaptureState=`truncated`,r.bodyInline=a.body.slice(0,this.options.inlineBodyBytes),r.bodyArtifactPath=null,r.bodyError=`Body exceeded configured maxBodyBytes (${this.options.maxBodyBytes})`;else if(r.bodySize<=this.options.inlineBodyBytes)r.bodyCaptureState=`inline`,r.bodyInline=a.body,r.bodyArtifactPath=null,r.bodyError=null;else{let n=a.base64Encoded?`b64`:`txt`,{absolutePath:o}=await t({category:`traces`,toolName:`trace_body`,target:e.slice(0,32),ext:n});await i(o,a.body,`utf8`),r.bodyCaptureState=`artifact`,r.bodyInline=null,r.bodyArtifactPath=o,r.bodyError=null}this.counts.networkBodyCount++}catch(e){r.bodyCaptureState=r.bodyCaptureState===`none`?`error`:r.bodyCaptureState,r.bodyError=e instanceof Error?e.message:String(e)}finally{this.syncResource(r)}}getOrCreateResource(e){let t=this.resources.get(e);if(t)return t;let n=y(e);return this.resources.set(e,n),this.counts.networkRequestCount++,n}syncResource(e){try{this.deps.getDb()?.upsertNetworkResource(e)}catch{}}};function x(e){e.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
3
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
|
+
timestamp REAL NOT NULL,
|
|
5
|
+
category TEXT NOT NULL,
|
|
6
|
+
event_type TEXT NOT NULL,
|
|
7
|
+
data TEXT NOT NULL DEFAULT '{}',
|
|
8
|
+
script_id TEXT,
|
|
9
|
+
line_number INTEGER,
|
|
10
|
+
wall_time REAL,
|
|
11
|
+
monotonic_time REAL,
|
|
12
|
+
request_id TEXT,
|
|
13
|
+
sequence INTEGER
|
|
14
|
+
);
|
|
15
|
+
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
|
16
|
+
CREATE INDEX IF NOT EXISTS idx_events_category_type ON events(category, event_type);
|
|
17
|
+
CREATE INDEX IF NOT EXISTS idx_events_script_id ON events(script_id);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);
|
|
19
|
+
|
|
20
|
+
CREATE TABLE IF NOT EXISTS memory_deltas (
|
|
21
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
22
|
+
timestamp REAL NOT NULL,
|
|
23
|
+
address TEXT NOT NULL,
|
|
24
|
+
old_value TEXT NOT NULL,
|
|
25
|
+
new_value TEXT NOT NULL,
|
|
26
|
+
size INTEGER NOT NULL,
|
|
27
|
+
value_type TEXT NOT NULL
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS idx_memory_timestamp ON memory_deltas(timestamp);
|
|
30
|
+
CREATE INDEX IF NOT EXISTS idx_memory_address ON memory_deltas(address);
|
|
31
|
+
|
|
32
|
+
CREATE TABLE IF NOT EXISTS heap_snapshots (
|
|
33
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
34
|
+
timestamp REAL NOT NULL,
|
|
35
|
+
snapshot_data BLOB,
|
|
36
|
+
summary TEXT NOT NULL DEFAULT '{}'
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
CREATE TABLE IF NOT EXISTS metadata (
|
|
40
|
+
key TEXT PRIMARY KEY,
|
|
41
|
+
value TEXT NOT NULL
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
CREATE TABLE IF NOT EXISTS network_resources (
|
|
45
|
+
request_id TEXT PRIMARY KEY,
|
|
46
|
+
url TEXT,
|
|
47
|
+
method TEXT,
|
|
48
|
+
resource_type TEXT,
|
|
49
|
+
request_headers TEXT NOT NULL DEFAULT '{}',
|
|
50
|
+
request_post_data TEXT,
|
|
51
|
+
status INTEGER,
|
|
52
|
+
status_text TEXT,
|
|
53
|
+
response_headers TEXT NOT NULL DEFAULT '{}',
|
|
54
|
+
mime_type TEXT,
|
|
55
|
+
protocol TEXT,
|
|
56
|
+
remote_address TEXT,
|
|
57
|
+
from_disk_cache INTEGER NOT NULL DEFAULT 0,
|
|
58
|
+
from_service_worker INTEGER NOT NULL DEFAULT 0,
|
|
59
|
+
started_wall_time REAL,
|
|
60
|
+
response_wall_time REAL,
|
|
61
|
+
finished_wall_time REAL,
|
|
62
|
+
started_monotonic_time REAL,
|
|
63
|
+
response_monotonic_time REAL,
|
|
64
|
+
finished_monotonic_time REAL,
|
|
65
|
+
encoded_data_length INTEGER,
|
|
66
|
+
received_data_length INTEGER NOT NULL DEFAULT 0,
|
|
67
|
+
received_encoded_data_length INTEGER NOT NULL DEFAULT 0,
|
|
68
|
+
chunk_count INTEGER NOT NULL DEFAULT 0,
|
|
69
|
+
streaming_enabled INTEGER NOT NULL DEFAULT 0,
|
|
70
|
+
streaming_supported INTEGER,
|
|
71
|
+
streaming_error TEXT,
|
|
72
|
+
body_capture_state TEXT NOT NULL DEFAULT 'none',
|
|
73
|
+
body_inline TEXT,
|
|
74
|
+
body_artifact_path TEXT,
|
|
75
|
+
body_base64_encoded INTEGER NOT NULL DEFAULT 0,
|
|
76
|
+
body_size INTEGER,
|
|
77
|
+
body_truncated INTEGER NOT NULL DEFAULT 0,
|
|
78
|
+
body_error TEXT,
|
|
79
|
+
failed INTEGER NOT NULL DEFAULT 0,
|
|
80
|
+
error_text TEXT
|
|
81
|
+
);
|
|
82
|
+
CREATE INDEX IF NOT EXISTS idx_network_resources_started_wall_time
|
|
83
|
+
ON network_resources(started_wall_time);
|
|
84
|
+
|
|
85
|
+
CREATE TABLE IF NOT EXISTS network_chunks (
|
|
86
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
87
|
+
request_id TEXT NOT NULL,
|
|
88
|
+
sequence INTEGER NOT NULL,
|
|
89
|
+
timestamp REAL NOT NULL,
|
|
90
|
+
monotonic_time REAL,
|
|
91
|
+
data_length INTEGER NOT NULL,
|
|
92
|
+
encoded_data_length INTEGER NOT NULL,
|
|
93
|
+
chunk_data TEXT,
|
|
94
|
+
chunk_is_base64 INTEGER NOT NULL DEFAULT 0
|
|
95
|
+
);
|
|
96
|
+
CREATE INDEX IF NOT EXISTS idx_network_chunks_request_sequence
|
|
97
|
+
ON network_chunks(request_id, sequence);
|
|
98
|
+
CREATE INDEX IF NOT EXISTS idx_network_chunks_timestamp
|
|
99
|
+
ON network_chunks(timestamp);
|
|
100
|
+
`),E(e,`events`,`wall_time`,`REAL`),E(e,`events`,`monotonic_time`,`REAL`),E(e,`events`,`request_id`,`TEXT`),E(e,`events`,`sequence`,`INTEGER`)}function S(e){return{insertEventStmt:e.prepare(`
|
|
101
|
+
INSERT INTO events (
|
|
102
|
+
timestamp,
|
|
103
|
+
category,
|
|
104
|
+
event_type,
|
|
105
|
+
data,
|
|
106
|
+
script_id,
|
|
107
|
+
line_number,
|
|
108
|
+
wall_time,
|
|
109
|
+
monotonic_time,
|
|
110
|
+
request_id,
|
|
111
|
+
sequence
|
|
112
|
+
)
|
|
113
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
114
|
+
`),insertDeltaStmt:e.prepare(`
|
|
115
|
+
INSERT INTO memory_deltas (timestamp, address, old_value, new_value, size, value_type)
|
|
116
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
117
|
+
`),insertSnapshotStmt:e.prepare(`
|
|
118
|
+
INSERT INTO heap_snapshots (timestamp, snapshot_data, summary)
|
|
119
|
+
VALUES (?, ?, ?)
|
|
120
|
+
`),upsertMetadataStmt:e.prepare(`
|
|
121
|
+
INSERT INTO metadata (key, value) VALUES (?, ?)
|
|
122
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
123
|
+
`),upsertNetworkResourceStmt:e.prepare(`
|
|
124
|
+
INSERT INTO network_resources (
|
|
125
|
+
request_id,
|
|
126
|
+
url,
|
|
127
|
+
method,
|
|
128
|
+
resource_type,
|
|
129
|
+
request_headers,
|
|
130
|
+
request_post_data,
|
|
131
|
+
status,
|
|
132
|
+
status_text,
|
|
133
|
+
response_headers,
|
|
134
|
+
mime_type,
|
|
135
|
+
protocol,
|
|
136
|
+
remote_address,
|
|
137
|
+
from_disk_cache,
|
|
138
|
+
from_service_worker,
|
|
139
|
+
started_wall_time,
|
|
140
|
+
response_wall_time,
|
|
141
|
+
finished_wall_time,
|
|
142
|
+
started_monotonic_time,
|
|
143
|
+
response_monotonic_time,
|
|
144
|
+
finished_monotonic_time,
|
|
145
|
+
encoded_data_length,
|
|
146
|
+
received_data_length,
|
|
147
|
+
received_encoded_data_length,
|
|
148
|
+
chunk_count,
|
|
149
|
+
streaming_enabled,
|
|
150
|
+
streaming_supported,
|
|
151
|
+
streaming_error,
|
|
152
|
+
body_capture_state,
|
|
153
|
+
body_inline,
|
|
154
|
+
body_artifact_path,
|
|
155
|
+
body_base64_encoded,
|
|
156
|
+
body_size,
|
|
157
|
+
body_truncated,
|
|
158
|
+
body_error,
|
|
159
|
+
failed,
|
|
160
|
+
error_text
|
|
161
|
+
)
|
|
162
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
163
|
+
ON CONFLICT(request_id) DO UPDATE SET
|
|
164
|
+
url = excluded.url,
|
|
165
|
+
method = excluded.method,
|
|
166
|
+
resource_type = excluded.resource_type,
|
|
167
|
+
request_headers = excluded.request_headers,
|
|
168
|
+
request_post_data = excluded.request_post_data,
|
|
169
|
+
status = excluded.status,
|
|
170
|
+
status_text = excluded.status_text,
|
|
171
|
+
response_headers = excluded.response_headers,
|
|
172
|
+
mime_type = excluded.mime_type,
|
|
173
|
+
protocol = excluded.protocol,
|
|
174
|
+
remote_address = excluded.remote_address,
|
|
175
|
+
from_disk_cache = excluded.from_disk_cache,
|
|
176
|
+
from_service_worker = excluded.from_service_worker,
|
|
177
|
+
started_wall_time = excluded.started_wall_time,
|
|
178
|
+
response_wall_time = excluded.response_wall_time,
|
|
179
|
+
finished_wall_time = excluded.finished_wall_time,
|
|
180
|
+
started_monotonic_time = excluded.started_monotonic_time,
|
|
181
|
+
response_monotonic_time = excluded.response_monotonic_time,
|
|
182
|
+
finished_monotonic_time = excluded.finished_monotonic_time,
|
|
183
|
+
encoded_data_length = excluded.encoded_data_length,
|
|
184
|
+
received_data_length = excluded.received_data_length,
|
|
185
|
+
received_encoded_data_length = excluded.received_encoded_data_length,
|
|
186
|
+
chunk_count = excluded.chunk_count,
|
|
187
|
+
streaming_enabled = excluded.streaming_enabled,
|
|
188
|
+
streaming_supported = excluded.streaming_supported,
|
|
189
|
+
streaming_error = excluded.streaming_error,
|
|
190
|
+
body_capture_state = excluded.body_capture_state,
|
|
191
|
+
body_inline = excluded.body_inline,
|
|
192
|
+
body_artifact_path = excluded.body_artifact_path,
|
|
193
|
+
body_base64_encoded = excluded.body_base64_encoded,
|
|
194
|
+
body_size = excluded.body_size,
|
|
195
|
+
body_truncated = excluded.body_truncated,
|
|
196
|
+
body_error = excluded.body_error,
|
|
197
|
+
failed = excluded.failed,
|
|
198
|
+
error_text = excluded.error_text
|
|
199
|
+
`),insertNetworkChunkStmt:e.prepare(`
|
|
200
|
+
INSERT INTO network_chunks (
|
|
201
|
+
request_id,
|
|
202
|
+
sequence,
|
|
203
|
+
timestamp,
|
|
204
|
+
monotonic_time,
|
|
205
|
+
data_length,
|
|
206
|
+
encoded_data_length,
|
|
207
|
+
chunk_data,
|
|
208
|
+
chunk_is_base64
|
|
209
|
+
)
|
|
210
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
211
|
+
`)}}function C(e){return{id:e.id,timestamp:e.timestamp,category:e.category,eventType:e.event_type,data:e.data,scriptId:e.script_id??null,lineNumber:e.line_number??null,wallTime:e.wall_time??null,monotonicTime:e.monotonic_time??null,requestId:e.request_id??null,sequence:e.sequence??null}}function w(e,t){return{id:e.id,requestId:e.request_id,sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonic_time??null,dataLength:e.data_length,encodedDataLength:e.encoded_data_length,chunkData:e.chunk_data??null,chunkIsBase64:t(e.chunk_is_base64)}}function T(e,t){return{requestId:e.request_id,url:e.url??null,method:e.method??null,resourceType:e.resource_type??null,requestHeaders:e.request_headers??`{}`,requestPostData:e.request_post_data??null,status:e.status??null,statusText:e.status_text??null,responseHeaders:e.response_headers??`{}`,mimeType:e.mime_type??null,protocol:e.protocol??null,remoteAddress:e.remote_address??null,fromDiskCache:t(e.from_disk_cache),fromServiceWorker:t(e.from_service_worker),startedWallTime:e.started_wall_time??null,responseWallTime:e.response_wall_time??null,finishedWallTime:e.finished_wall_time??null,startedMonotonicTime:e.started_monotonic_time??null,responseMonotonicTime:e.response_monotonic_time??null,finishedMonotonicTime:e.finished_monotonic_time??null,encodedDataLength:e.encoded_data_length??null,receivedDataLength:e.received_data_length??0,receivedEncodedDataLength:e.received_encoded_data_length??0,chunkCount:e.chunk_count??0,streamingEnabled:t(e.streaming_enabled),streamingSupported:e.streaming_supported===null||e.streaming_supported===void 0?null:t(e.streaming_supported),streamingError:e.streaming_error??null,bodyCaptureState:e.body_capture_state??`none`,bodyInline:e.body_inline??null,bodyArtifactPath:e.body_artifact_path??null,bodyBase64Encoded:t(e.body_base64_encoded),bodySize:e.body_size??null,bodyTruncated:t(e.body_truncated),bodyError:e.body_error??null,failed:t(e.failed),errorText:e.error_text??null}}function E(e,t,n,r){e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n)||e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`)}let D;try{D=e(`better-sqlite3`)}catch{}const O=/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|ATTACH|DETACH|REPLACE|PRAGMA)\b/i;var k=class{options;db;batchSize;eventBuffer=[];memoryBuffer=[];networkChunkBuffer=[];closed=!1;insertEventStmt;insertDeltaStmt;insertSnapshotStmt;upsertMetadataStmt;upsertNetworkResourceStmt;insertNetworkChunkStmt;constructor(e){if(this.options=e,!D)throw Error(n(Error(`Cannot find package 'better-sqlite3'`)));try{this.db=new D(e.dbPath)}catch(e){throw Error(n(e),{cause:e})}this.batchSize=e.batchSize??200,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`synchronous = NORMAL`),x(this.db);let t=S(this.db);this.insertEventStmt=t.insertEventStmt,this.insertDeltaStmt=t.insertDeltaStmt,this.insertSnapshotStmt=t.insertSnapshotStmt,this.upsertMetadataStmt=t.upsertMetadataStmt,this.upsertNetworkResourceStmt=t.upsertNetworkResourceStmt,this.insertNetworkChunkStmt=t.insertNetworkChunkStmt}get dbPath(){return this.options.dbPath}insertEvent(e){this.ensureOpen(),this.eventBuffer.push(e),this.eventBuffer.length>=this.batchSize&&this.flush()}insertMemoryDelta(e){this.ensureOpen(),this.memoryBuffer.push(e),this.memoryBuffer.length>=this.batchSize&&this.flush()}insertNetworkChunk(e){this.ensureOpen(),this.networkChunkBuffer.push(e),this.networkChunkBuffer.length>=this.batchSize&&this.flush()}upsertNetworkResource(e){this.ensureOpen(),this.upsertNetworkResourceStmt.run(e.requestId,e.url,e.method,e.resourceType,e.requestHeaders,e.requestPostData,e.status,e.statusText,e.responseHeaders,e.mimeType,e.protocol,e.remoteAddress,+!!e.fromDiskCache,+!!e.fromServiceWorker,e.startedWallTime,e.responseWallTime,e.finishedWallTime,e.startedMonotonicTime,e.responseMonotonicTime,e.finishedMonotonicTime,e.encodedDataLength,e.receivedDataLength,e.receivedEncodedDataLength,e.chunkCount,+!!e.streamingEnabled,e.streamingSupported===null?null:+!!e.streamingSupported,e.streamingError,e.bodyCaptureState,e.bodyInline,e.bodyArtifactPath,+!!e.bodyBase64Encoded,e.bodySize,+!!e.bodyTruncated,e.bodyError,+!!e.failed,e.errorText)}insertHeapSnapshot(e){this.ensureOpen(),this.insertSnapshotStmt.run(e.timestamp,e.snapshotData,e.summary)}setMetadata(e,t){this.ensureOpen(),this.upsertMetadataStmt.run(e,t)}flush(){this.closed||(this.db.transaction(()=>{for(let e of this.eventBuffer)this.insertEventStmt.run(e.timestamp,e.category,e.eventType,e.data,e.scriptId,e.lineNumber,e.wallTime??null,e.monotonicTime??null,e.requestId??null,e.sequence??null);for(let e of this.memoryBuffer)this.insertDeltaStmt.run(e.timestamp,e.address,e.oldValue,e.newValue,e.size,e.valueType);for(let e of this.networkChunkBuffer)this.insertNetworkChunkStmt.run(e.requestId,e.sequence,e.timestamp,e.monotonicTime,e.dataLength,e.encodedDataLength,e.chunkData,+!!e.chunkIsBase64)})(),this.eventBuffer=[],this.memoryBuffer=[],this.networkChunkBuffer=[])}query(e){if(this.ensureOpen(),O.test(e))throw Error(`Write operations are not allowed in trace queries. Rejected SQL: ${e.slice(0,100)}`);let t=this.db.prepare(e),n=t.all();if(n.length===0)return{columns:t.columns().map(e=>e.name),rows:[],rowCount:0};let r=Object.keys(n[0]);return{columns:r,rows:n.map(e=>r.map(t=>e[t])),rowCount:n.length}}getEventsByTimeRange(e,t){return this.ensureOpen(),this.flush(),this.db.prepare(`
|
|
212
|
+
SELECT
|
|
213
|
+
id,
|
|
214
|
+
timestamp,
|
|
215
|
+
category,
|
|
216
|
+
event_type,
|
|
217
|
+
data,
|
|
218
|
+
script_id,
|
|
219
|
+
line_number,
|
|
220
|
+
wall_time,
|
|
221
|
+
monotonic_time,
|
|
222
|
+
request_id,
|
|
223
|
+
sequence
|
|
224
|
+
FROM events
|
|
225
|
+
WHERE timestamp >= ? AND timestamp <= ?
|
|
226
|
+
ORDER BY timestamp ASC, sequence ASC, id ASC
|
|
227
|
+
`).all(e,t).map(C)}getEventsByRequestId(e){return this.ensureOpen(),this.flush(),this.db.prepare(`
|
|
228
|
+
SELECT
|
|
229
|
+
id,
|
|
230
|
+
timestamp,
|
|
231
|
+
category,
|
|
232
|
+
event_type,
|
|
233
|
+
data,
|
|
234
|
+
script_id,
|
|
235
|
+
line_number,
|
|
236
|
+
wall_time,
|
|
237
|
+
monotonic_time,
|
|
238
|
+
request_id,
|
|
239
|
+
sequence
|
|
240
|
+
FROM events
|
|
241
|
+
WHERE request_id = ?
|
|
242
|
+
ORDER BY COALESCE(monotonic_time, timestamp) ASC, sequence ASC, id ASC
|
|
243
|
+
`).all(e).map(C)}getNetworkResource(e){this.ensureOpen(),this.flush();let t=this.db.prepare(`
|
|
244
|
+
SELECT *
|
|
245
|
+
FROM network_resources
|
|
246
|
+
WHERE request_id = ?
|
|
247
|
+
LIMIT 1
|
|
248
|
+
`).get(e);return t?T(t,this.fromSqliteBoolean):null}getNetworkChunks(e,t){this.ensureOpen(),this.flush();let n=`
|
|
249
|
+
SELECT
|
|
250
|
+
id,
|
|
251
|
+
request_id,
|
|
252
|
+
sequence,
|
|
253
|
+
timestamp,
|
|
254
|
+
monotonic_time,
|
|
255
|
+
data_length,
|
|
256
|
+
encoded_data_length,
|
|
257
|
+
chunk_data,
|
|
258
|
+
chunk_is_base64
|
|
259
|
+
FROM network_chunks
|
|
260
|
+
WHERE request_id = ?
|
|
261
|
+
ORDER BY sequence ASC
|
|
262
|
+
${typeof t==`number`?`LIMIT ?`:``}
|
|
263
|
+
`,r=this.db.prepare(n);return(typeof t==`number`?r.all(e,t):r.all(e)).map(e=>w(e,this.fromSqliteBoolean))}getMemoryDeltasByAddress(e){return this.ensureOpen(),this.flush(),this.db.prepare(`
|
|
264
|
+
SELECT id, timestamp, address, old_value, new_value, size, value_type
|
|
265
|
+
FROM memory_deltas
|
|
266
|
+
WHERE address = ?
|
|
267
|
+
ORDER BY timestamp ASC
|
|
268
|
+
`).all(e).map(e=>({id:e.id,timestamp:e.timestamp,address:e.address,oldValue:e.old_value,newValue:e.new_value,size:e.size,valueType:e.value_type}))}getHeapSnapshots(){return this.ensureOpen(),this.db.prepare(`
|
|
269
|
+
SELECT id, timestamp, snapshot_data, summary
|
|
270
|
+
FROM heap_snapshots
|
|
271
|
+
ORDER BY timestamp ASC
|
|
272
|
+
`).all().map(e=>({id:e.id,timestamp:e.timestamp,snapshotData:e.snapshot_data,summary:e.summary}))}getMetadata(){this.ensureOpen();let e=this.db.prepare(`SELECT key, value FROM metadata`).all(),t={};for(let n of e)t[n.key]=n.value;return t}close(){this.closed||=(this.flush(),this.db.close(),!0)}get isClosed(){return this.closed}fromSqliteBoolean(e){return e===1||e===!0}ensureOpen(){if(this.closed)throw Error(`TraceDB is closed`)}},A=class{db=null;state=`idle`;session=null;eventBusUnsub=null;cdpListeners=new Map;enabledCdpDomains=new Set;cdpSession=null;ownsCdpSession=!1;eventCount=0;memoryDeltaCount=0;heapSnapshotCount=0;eventSequence=0;pendingOperations=new Set;networkCapture=new b({getDb:()=>this.db,getCdpSession:()=>this.cdpSession,trackOperation:e=>this.trackOperation(e)});async start(e,n,i){if(this.state===`recording`)throw Error(`Recording already in progress`);let s=r(),{absolutePath:c}=await t({category:`traces`,toolName:`trace_recorder`,target:s.slice(0,8),ext:`db`}),l=n?(i?.cdpDomains??o).filter(e=>a[e]):[];this.db=new k({dbPath:c}),this.eventCount=0,this.memoryDeltaCount=0,this.heapSnapshotCount=0,this.eventSequence=0,this.pendingOperations.clear(),this.cdpListeners.clear(),this.enabledCdpDomains.clear(),this.cdpSession=n,this.ownsCdpSession=i?.ownsSession??!1;try{let t=this.networkCapture.configure(i?.network);if(n)for(let e of l)await n.send(`${e}.enable`),this.enabledCdpDomains.add(e);let r=Date.now();if(this.db.setMetadata(`sessionId`,s),this.db.setMetadata(`platform`,process.platform),this.db.setMetadata(`startedAt`,String(r)),this.db.setMetadata(`nodeVersion`,process.version),this.db.setMetadata(`network.recordResponseBodies`,String(t.recordResponseBodies)),this.db.setMetadata(`network.streamResponseChunks`,String(t.streamResponseChunks)),this.db.setMetadata(`network.maxBodyBytes`,String(t.maxBodyBytes)),this.db.setMetadata(`network.inlineBodyBytes`,String(t.inlineBodyBytes)),this.eventBusUnsub=e.onAny(e=>{if(this.state===`recording`)try{let t=Date.now();this.db?.insertEvent({timestamp:t,wallTime:t,monotonicTime:null,category:this.mapEventCategory(String(e.event)),eventType:String(e.event),data:JSON.stringify(e.payload??{}),scriptId:null,lineNumber:null,requestId:null,sequence:this.nextSequence()}),this.eventCount++}catch{}}),n)for(let e of l){let t=a[e]??[];for(let r of t){let t=t=>{if(!(this.state!==`recording`||!this.db))try{let n=m(t),i=h(t),{scriptId:a,lineNumber:o}=g(r,t),s=JSON.stringify(_(r,t));this.db.insertEvent({timestamp:n.timestamp,wallTime:n.wallTime,monotonicTime:n.monotonicTime,category:e.toLowerCase(),eventType:r,data:s,scriptId:a,lineNumber:o,requestId:i,sequence:this.nextSequence()}),this.eventCount++,e===`Network`&&this.networkCapture.handleEvent(r,t,n)}catch{}};n.on(r,t),this.cdpListeners.set(r,t)}}return this.session={sessionId:s,dbPath:c,startedAt:r,eventCount:0,memoryDeltaCount:0,heapSnapshotCount:0,...this.networkCapture.getCounts()},this.state=`recording`,{...this.session}}catch(e){throw await this.cleanupFailedStart(),e}}recordMemoryDelta(e){if(!(this.state!==`recording`||!this.db))try{this.db.insertMemoryDelta(e),this.memoryDeltaCount++}catch{}}async captureActiveHeapSnapshot(){if(!this.cdpSession)throw Error(`Cannot capture heap snapshot: no active CDP session`);return await this.captureHeapSnapshot(this.cdpSession)}async captureHeapSnapshot(e){if(this.state!==`recording`||!this.db)throw Error(`Cannot capture heap snapshot: not recording`);let t=[],n=!1,r=e=>{if(typeof e==`object`&&e){let n=e.chunk;typeof n==`string`&&t.push(n)}};try{await e.send(`HeapProfiler.enable`),e.on(`HeapProfiler.addHeapSnapshotChunk`,r),n=!0,await e.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1});let i=t.join(``),a=Buffer.from(i,`utf-8`),o=this.extractHeapSummary(i);return this.db.insertHeapSnapshot({timestamp:Date.now(),snapshotData:a,summary:JSON.stringify(o)}),this.heapSnapshotCount++,a.byteLength}finally{n&&e.off(`HeapProfiler.addHeapSnapshotChunk`,r),await e.send(`HeapProfiler.disable`).catch(()=>{})}}async stop(){if(this.state!==`recording`)throw Error(`GRACEFUL: Cannot stop: not currently recording`);if(this.eventBusUnsub&&=(this.eventBusUnsub(),null),this.cdpSession)for(let[e,t]of this.cdpListeners)this.cdpSession.off(e,t);this.cdpListeners.clear(),await this.waitForPendingOperations();let e;if(this.cdpSession){if(this.enabledCdpDomains.size>0){let t=Array.from(this.enabledCdpDomains);e=(await Promise.allSettled(t.map(e=>this.cdpSession.send(`${e}.disable`)))).flatMap((e,n)=>e.status===`rejected`?[`${t[n]}.disable failed: ${e.reason instanceof Error?e.reason.message:String(e.reason)}`]:[])}if(this.enabledCdpDomains.clear(),this.ownsCdpSession&&typeof this.cdpSession.detach==`function`)try{await this.cdpSession.detach()}catch(t){(e??=[]).push(`cdpSession.detach failed: ${t instanceof Error?t.message:String(t)}`)}this.cdpSession=null,this.ownsCdpSession=!1}if(this.db){let t=Date.now(),n=this.networkCapture.getCounts();this.db.setMetadata(`stoppedAt`,String(t)),this.db.setMetadata(`eventCount`,String(this.eventCount)),this.db.setMetadata(`memoryDeltaCount`,String(this.memoryDeltaCount)),this.db.setMetadata(`heapSnapshotCount`,String(this.heapSnapshotCount)),this.db.setMetadata(`networkRequestCount`,String(n.networkRequestCount)),this.db.setMetadata(`networkChunkCount`,String(n.networkChunkCount)),this.db.setMetadata(`networkBodyCount`,String(n.networkBodyCount)),this.db.close(),this.session&&(this.session.stoppedAt=t,this.session.eventCount=this.eventCount,this.session.memoryDeltaCount=this.memoryDeltaCount,this.session.heapSnapshotCount=this.heapSnapshotCount,this.session.networkRequestCount=n.networkRequestCount,this.session.networkChunkCount=n.networkChunkCount,this.session.networkBodyCount=n.networkBodyCount,e&&e.length>0?this.session.cleanupErrors=e:delete this.session.cleanupErrors)}this.state=`stopped`;let t=this.session?{...this.session}:this.createEmptySession();return this.db=null,this.networkCapture.clear(),t}getState(){return this.state}getSession(){return this.session?{...this.session}:null}getDB(){return this.db}trackOperation(e){this.pendingOperations.add(e),e.finally(()=>{this.pendingOperations.delete(e)})}async waitForPendingOperations(){for(;this.pendingOperations.size>0;)await Promise.allSettled(Array.from(this.pendingOperations))}async cleanupFailedStart(){if(this.eventBusUnsub&&=(this.eventBusUnsub(),null),this.cdpSession)for(let[e,t]of this.cdpListeners)this.cdpSession.off(e,t);if(this.cdpListeners.clear(),this.cdpSession&&this.enabledCdpDomains.size>0&&await Promise.allSettled(Array.from(this.enabledCdpDomains).map(e=>this.cdpSession.send(`${e}.disable`))),this.enabledCdpDomains.clear(),this.cdpSession&&this.ownsCdpSession&&typeof this.cdpSession.detach==`function`&&await this.cdpSession.detach().catch(()=>{}),this.cdpSession=null,this.ownsCdpSession=!1,this.db){try{this.db.close()}catch{}this.db=null}this.session=null,this.state=`idle`,this.eventCount=0,this.memoryDeltaCount=0,this.heapSnapshotCount=0,this.eventSequence=0,this.pendingOperations.clear(),this.networkCapture.clear()}nextSequence(){return this.eventSequence+=1,this.eventSequence}mapEventCategory(e){let t=e.indexOf(`:`);return t>0?e.substring(0,t):`other`}extractHeapSummary(e){try{let t=JSON.parse(e),n=t.snapshot;if(!n)return{totalSize:0,nodeCount:0,objectCounts:{}};let r=n.meta,i=n.node_count??0,a=r?.node_fields,o=r?.node_types,s=t.nodes,c={},l=0;if(a&&s&&o){let e=a.length,n=a.indexOf(`type`),r=a.indexOf(`name`),i=a.indexOf(`self_size`),o=t.strings??[];for(let t=0;t<s.length;t+=e){let e=i>=0?s[t+i]??0:0;if(l+=e,r>=0){let e=o[s[t+r]??0]??`type_${s[t+(n>=0?n:0)]}`;e&&(c[e]=(c[e]??0)+1)}}}return{totalSize:l,nodeCount:i,objectCounts:c}}catch{return{totalSize:0,nodeCount:0,objectCounts:{}}}}createEmptySession(){return{sessionId:``,dbPath:``,startedAt:0,eventCount:0,memoryDeltaCount:0,heapSnapshotCount:0,networkRequestCount:0,networkChunkCount:0,networkBodyCount:0}}};export{A as TraceRecorder,k as t};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";var t=e({VersionDetector:()=>o});function n(e){return typeof e==`object`&&!!e}function r(e){return n(e)&&typeof e.createCDPSession==`function`}function i(e,t){let n=e[t];return typeof n==`string`?n:null}function a(e){if(typeof e==`boolean`)return e;if(n(e)){let t=e.value;return typeof t==`boolean`?t:!1}return!1}var o=class{getPage;constructor(e){this.getPage=e}async detectV8Version(){return await this.detectBrowserVersion()||(typeof process.versions.v8==`string`&&process.versions.v8.length>0?this.parseV8Version(process.versions.v8):null)}parseV8Version(e){let t=/(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:\.(?<commit>[A-Za-z0-9._-]+))?/u.exec(e.trim());if(!t?.groups)return{major:0,minor:0,patch:0,commit:``};let n=Number(t.groups.major??0),r=Number(t.groups.minor??0),i=Number(t.groups.patch??0);return{major:Number.isFinite(n)?n:0,minor:Number.isFinite(r)?r:0,patch:Number.isFinite(i)?i:0,commit:t.groups.commit??``}}async supportsNativesSyntax(){if(process.execArgv.includes(`--allow-natives-syntax`))return!0;let e=await this.createSession();if(!e)return!1;try{let t=await e.send(`Runtime.evaluate`,{expression:`
|
|
2
|
+
(() => {
|
|
3
|
+
try {
|
|
4
|
+
return Boolean(new Function("return %HaveSameMap({}, {})")());
|
|
5
|
+
} catch (error) {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
})()
|
|
9
|
+
`,returnByValue:!0,awaitPromise:!1});return n(t)?a(t.result):!1}catch{return!1}finally{await e.detach().catch(()=>void 0)}}async detectBrowserVersion(){let e=await this.createSession();if(!e)return null;try{let t=await e.send(`Browser.getVersion`);if(!n(t))return null;let r=i(t,`jsVersion`);if(r)return this.parseV8Version(r);let a=i(t,`product`);return a?this.parseV8Version(a):null}catch{return null}finally{await e.detach().catch(()=>void 0)}}async createSession(){if(!this.getPage)return null;try{let e=await this.getPage();return r(e)?await e.createCDPSession():null}catch{return null}}};export{t as n,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import n from"koffi";var r=e({CloseHandle:()=>v,CreateRemoteThread:()=>T,EnumProcessModules:()=>A,GetLastError:()=>O,GetModuleBaseName:()=>j,GetModuleFileNameEx:()=>M,GetModuleHandle:()=>E,GetModuleInformation:()=>N,GetProcAddress:()=>D,MEM:()=>a,NtQueryInformationProcess:()=>k,OpenProcess:()=>_,PAGE:()=>o,PROCESS_ACCESS:()=>i,ReadProcessMemory:()=>y,VirtualAllocEx:()=>C,VirtualFreeEx:()=>w,VirtualProtectEx:()=>S,VirtualQueryEx:()=>x,WriteProcessMemory:()=>b,isKoffiAvailable:()=>d,isWindows:()=>f,openProcessForMemory:()=>P});const i={TERMINATE:1,CREATE_THREAD:2,SET_SESSIONID:4,VM_OPERATION:8,VM_READ:16,VM_WRITE:32,DUP_HANDLE:64,CREATE_PROCESS:128,SET_QUOTA:256,SET_INFORMATION:512,QUERY_INFORMATION:1024,SUSPEND_RESUME:2048,QUERY_LIMITED_INFORMATION:4096,ALL_ACCESS:2035711},a={COMMIT:4096,RESERVE:8192,DECOMMIT:16384,RELEASE:32768,FREE:65536,PRIVATE:131072,MAPPED:262144,RESET:524288,TOP_DOWN:1048576,WRITE_WATCH:2097152,PHYSICAL:4194304,LARGE_PAGES:536870912},o={NOACCESS:1,READONLY:2,READWRITE:4,WRITECOPY:8,EXECUTE:16,EXECUTE_READ:32,EXECUTE_READWRITE:64,EXECUTE_WRITECOPY:128,GUARD:256,NOCACHE:512,WRITECOMBINE:1024};let s=null,c=null,l=null,u=null;function d(){if(u!==null)return u;try{return n.load(`kernel32.dll`).unload(),u=!0,!0}catch{return u=!1,!1}}function f(){return process.platform===`win32`}function p(){return s||(s=n.load(`kernel32.dll`),t.debug(`Loaded kernel32.dll via koffi`)),s}function m(){return c||(c=n.load(`ntdll.dll`),t.debug(`Loaded ntdll.dll via koffi`)),c}function h(){return l||(l=n.load(`psapi.dll`),t.debug(`Loaded psapi.dll via koffi`)),l}function g(e){return e==null?0n:typeof e==`bigint`?e:typeof e==`number`?BigInt(e):n.address(e)}function _(e,t,n){return g(p().func(`void * OpenProcess(uint32, int, uint32)`)(e,+!!t,n))}function v(e){return p().func(`int CloseHandle(void *)`)(e)!==0}function y(e,t,n){let r=p().func(`int ReadProcessMemory(void *, void *, _Out_ uint8_t *, size_t, _Out_ size_t *)`),i=Buffer.alloc(n),a=Buffer.alloc(8);if(r(e,t,i,BigInt(n),a)===0){let e=O();throw Error(`ReadProcessMemory failed. Error: 0x${e.toString(16)}`)}return i}function b(e,t,n){let r=p().func(`int WriteProcessMemory(void *, void *, uint8_t *, size_t, _Out_ size_t *)`),i=Buffer.alloc(8);if(r(e,t,n,BigInt(n.length),i)===0){let e=O();throw Error(`WriteProcessMemory failed. Error: 0x${e.toString(16)}`)}return Number(i.readBigUInt64LE())}function x(e,t){let n=p().func(`size_t VirtualQueryEx(void *, void *, _Out_ uint8_t *, size_t)`),r=Buffer.alloc(48),i=n(e,t,r,BigInt(48));return Number(i)===48?{success:!0,info:{BaseAddress:r.readBigUInt64LE(0),AllocationBase:r.readBigUInt64LE(8),AllocationProtect:r.readUInt32LE(16),RegionSize:r.readBigUInt64LE(24),State:r.readUInt32LE(32),Protect:r.readUInt32LE(36),Type:r.readUInt32LE(40)}}:{success:!1,info:{}}}function S(e,t,n,r){let i=p().func(`int VirtualProtectEx(void *, void *, size_t, uint32, _Out_ uint32 *)`),a=Buffer.alloc(4);return{success:i(e,t,BigInt(n),r,a)!==0,oldProtect:a.readUInt32LE(0)}}function C(e,t,n,r,i){return g(p().func(`void * VirtualAllocEx(void *, void *, size_t, uint32, uint32)`)(e,t,BigInt(n),r,i))}function w(e,t,n,r){return p().func(`int VirtualFreeEx(void *, void *, size_t, uint32)`)(e,t,BigInt(n),r)!==0}function T(e,t,n){let r=p().func(`void * CreateRemoteThread(void *, void *, size_t, void *, void *, uint32, _Out_ uint32 *)`),i=Buffer.alloc(4);return{handle:g(r(e,null,0n,t,n,0,i)),threadId:i.readUInt32LE(0)}}function E(e){return g(p().func(`void * GetModuleHandleA(char *)`)(e))}function D(e,t){return g(p().func(`void * GetProcAddress(void *, char *)`)(e,t))}function O(){return p().func(`uint32 GetLastError()`)()}function k(e,t){let n=m().func(`int32 NtQueryInformationProcess(void *, uint32, _Out_ void *, uint32, void *)`),r=Buffer.alloc(8);return{status:n(e,t,r,8,null),debugPort:Number(r.readBigUInt64LE())}}function A(e,t=1024){let n=h().func(`int EnumProcessModules(void *, _Out_ void *, uint32, _Out_ uint32 *)`),r=Buffer.alloc(t*8),i=Buffer.alloc(4),a=n(e,r,t*8,i),o=i.readUInt32LE(0),s=Math.floor(o/8),c=[];for(let e=0;e<s;e++)c.push(r.readBigUInt64LE(e*8));return{success:a!==0,modules:c,count:s}}function j(e,t,n=260){let r=h().func(`uint32 GetModuleBaseNameA(void *, void *, _Out_ char *, uint32)`),i=Buffer.alloc(n);r(e,t,i,n);let a=0;for(;a<n&&i[a]!==0;)a++;return i.toString(`utf8`,0,a)}function M(e,t,n=32768){let r=h().func(`uint32 GetModuleFileNameExA(void *, void *, _Out_ char *, uint32)`),i=Buffer.alloc(n),a=r(e,t,i,n);if(typeof a!=`number`||a<=0)return null;let o=0;for(;o<n&&i[o]!==0;)o++;return o>0?i.toString(`utf8`,0,o):null}function N(e,t){let n=h().func(`int GetModuleInformation(void *, void *, _Out_ uint8_t *, uint32)`),r=Buffer.alloc(24),i=n(e,t,r,24),a={lpBaseOfDll:r.readBigUInt64LE(0),SizeOfImage:r.readUInt32LE(8),EntryPoint:r.readBigUInt64LE(16)};return{success:i!==0,info:a}}function P(e,t=!1){let n=_(t?i.VM_READ|i.VM_WRITE|i.VM_OPERATION|i.QUERY_INFORMATION:i.VM_READ|i.QUERY_INFORMATION,!1,e);if(n===0n){let t=O();throw Error(`Failed to open process ${e}. Error: 0x${t.toString(16)}. Run as Administrator.`)}return n}export{b as _,M as a,P as b,D as c,y as d,C as f,r as g,x as h,j as i,a as l,S as m,A as n,E as o,w as p,O as r,N as s,v as t,o as u,d as v,f as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{r as t,t as n}from"./Win32API-eUCF57l_.mjs";import r from"koffi";const i={TERMINATE:1,SUSPEND_RESUME:2,GET_CONTEXT:8,SET_CONTEXT:16,SET_INFORMATION:32,QUERY_INFORMATION:64,SET_THREAD_TOKEN:128,IMPERSONATE:256,DIRECT_IMPERSONATION:512,ALL_ACCESS:2032639},a={AMD64:1048576,CONTROL:1048577,INTEGER:1048578,SEGMENTS:1048580,FLOATING_POINT:1048584,DEBUG_REGISTERS:1048592,FULL:1048587,ALL:1048607},o={EXCEPTION_DEBUG_EVENT:1,CREATE_THREAD_DEBUG_EVENT:2,CREATE_PROCESS_DEBUG_EVENT:3,EXIT_THREAD_DEBUG_EVENT:4,EXIT_PROCESS_DEBUG_EVENT:5,LOAD_DLL_DEBUG_EVENT:6,UNLOAD_DLL_DEBUG_EVENT:7,OUTPUT_DEBUG_STRING_EVENT:8,RIP_EVENT:9},s={SINGLE_STEP:2147483652,BREAKPOINT:2147483651,ACCESS_VIOLATION:3221225477},c={CONTINUE:65538,EXCEPTION_NOT_HANDLED:2147549185,REPLY_LATER:1073807361},l={SNAPHEAPLIST:1,SNAPTHREAD:4,SNAPMODULE:8};function u(e){return{contextFlags:e.readUInt32LE(48),eflags:e.readUInt32LE(68),dr0:e.readBigUInt64LE(72),dr1:e.readBigUInt64LE(80),dr2:e.readBigUInt64LE(88),dr3:e.readBigUInt64LE(96),dr6:e.readBigUInt64LE(104),dr7:e.readBigUInt64LE(112),rax:e.readBigUInt64LE(120),rcx:e.readBigUInt64LE(128),rdx:e.readBigUInt64LE(136),rbx:e.readBigUInt64LE(144),rsp:e.readBigUInt64LE(152),rbp:e.readBigUInt64LE(160),rsi:e.readBigUInt64LE(168),rdi:e.readBigUInt64LE(176),r8:e.readBigUInt64LE(184),r9:e.readBigUInt64LE(192),r10:e.readBigUInt64LE(200),r11:e.readBigUInt64LE(208),r12:e.readBigUInt64LE(216),r13:e.readBigUInt64LE(224),r14:e.readBigUInt64LE(232),r15:e.readBigUInt64LE(240),rip:e.readBigUInt64LE(248)}}function d(e,t){t.contextFlags!==void 0&&e.writeUInt32LE(t.contextFlags,48),t.eflags!==void 0&&e.writeUInt32LE(t.eflags,68),t.dr0!==void 0&&e.writeBigUInt64LE(t.dr0,72),t.dr1!==void 0&&e.writeBigUInt64LE(t.dr1,80),t.dr2!==void 0&&e.writeBigUInt64LE(t.dr2,88),t.dr3!==void 0&&e.writeBigUInt64LE(t.dr3,96),t.dr6!==void 0&&e.writeBigUInt64LE(t.dr6,104),t.dr7!==void 0&&e.writeBigUInt64LE(t.dr7,112),t.rip!==void 0&&e.writeBigUInt64LE(t.rip,248)}let f=null;function p(){return f||(f=r.load(`kernel32.dll`),e.debug(`Loaded kernel32.dll for debug APIs`)),f}function m(e,t,n){return p().func(`void * OpenThread(uint32, int, uint32)`)(e,+!!t,n)}function h(e){let n=p().func(`uint32 SuspendThread(void *)`)(e);if(n===4294967295)throw Error(`SuspendThread failed. Error: 0x${t().toString(16)}`);return n}function g(e){let n=p().func(`uint32 ResumeThread(void *)`)(e);if(n===4294967295)throw Error(`ResumeThread failed. Error: 0x${t().toString(16)}`);return n}function _(e,n){let r=p().func(`int GetThreadContext(void *, _Inout_ uint8_t[1232])`),i=Buffer.alloc(1232);if(i.writeUInt32LE(n,48),r(e,i)===0)throw Error(`GetThreadContext failed. Error: 0x${t().toString(16)}`);return i}function v(e,n){if(p().func(`int SetThreadContext(void *, uint8_t[1232])`)(e,n)===0)throw Error(`SetThreadContext failed. Error: 0x${t().toString(16)}`)}function y(e){if(p().func(`int DebugActiveProcess(uint32)`)(e)===0)throw Error(`DebugActiveProcess failed for pid ${e}. Error: 0x${t().toString(16)}`)}function b(e){if(p().func(`int DebugActiveProcessStop(uint32)`)(e)===0)throw Error(`DebugActiveProcessStop failed. Error: 0x${t().toString(16)}`)}function x(e){p().func(`int DebugSetProcessKillOnExit(int)`)(+!!e)}function S(e){let t=p().func(`int WaitForDebugEvent(_Out_ uint8_t *, uint32)`),n=Buffer.alloc(176);if(t(n,e)===0)return null;let r={debugEventCode:n.readUInt32LE(0),processId:n.readUInt32LE(4),threadId:n.readUInt32LE(8)};return r.debugEventCode===o.EXCEPTION_DEBUG_EVENT&&(r.exceptionCode=n.readUInt32LE(16),r.exceptionAddress=n.readBigUInt64LE(32),r.firstChance=n.readUInt32LE(20)===0),r}function C(e,n,r){if(p().func(`int ContinueDebugEvent(uint32, uint32, uint32)`)(e,n,r)===0)throw Error(`ContinueDebugEvent failed. Error: 0x${t().toString(16)}`)}function w(e,t,n){p().func(`int FlushInstructionCache(void *, void *, size_t)`)(e,t,BigInt(n))}function T(e){let r=p().func(`void * CreateToolhelp32Snapshot(uint32, uint32)`),i=p().func(`int Thread32First(void *, _Inout_ uint8_t[28])`),a=p().func(`int Thread32Next(void *, _Inout_ uint8_t[28])`),o=r(l.SNAPTHREAD,0);if(o===0n||o===BigInt(`0xFFFFFFFFFFFFFFFF`))throw Error(`CreateToolhelp32Snapshot failed. Error: 0x${t().toString(16)}`);let s=[],c=Buffer.alloc(28);c.writeUInt32LE(28,0);try{if(i(o,c)!==0)do c.readUInt32LE(12)===e&&s.push(c.readUInt32LE(8)),c.writeUInt32LE(28,0);while(a(o,c)!==0);n(o)}catch(e){console.error(`[EnumerateProcessThreads] cleanup error:`,e)}return s}function E(e){let n=m(i.SUSPEND_RESUME|i.GET_CONTEXT|i.SET_CONTEXT|i.QUERY_INFORMATION,!1,e);if(n===0n)throw Error(`Failed to open thread ${e}. Error: 0x${t().toString(16)}`);return n}function D(e){let t=0n;for(let n of e){if(!n.enabled)continue;let{drIndex:e,access:r,size:i}=n;t|=1n<<BigInt(e*2);let a=0;switch(r){case`execute`:a=0;break;case`write`:a=1;break;case`readwrite`:case`read`:a=3;break}t|=BigInt(a)<<BigInt(16+e*4);let o=0;switch(i){case 1:o=0;break;case 2:o=1;break;case 4:o=3;break;case 8:o=2;break}t|=BigInt(o)<<BigInt(18+e*4)}return t}export{E as _,b as a,T as c,g as d,v as f,D as g,S as h,y as i,w as l,l as m,C as n,x as o,h as p,c as r,s,a as t,_ as u,u as v,d as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{l as n,o as r}from"./ToolRouter.policy-CfhJczkt.mjs";import{randomUUID as i}from"node:crypto";var a=class{store=new Map;set(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}getValueAtPath(e,t){let n=this.store.get(e);if(!n||typeof n!=`object`)return n;let r=o(n)||n;return t.split(`.`).reduce((e,t)=>{if(e&&typeof e==`object`){let n=t.match(/^(\d+)$/);return n&&Array.isArray(e)?e[Number(n[1])]:e[t]}},r)}resolve(e){let t=e.match(/^\$\{(.+)\}$/);if(!t||!t[1])return e;let n=t[1],r=n.indexOf(`.`);return r===-1?this.store.get(n):this.getValueAtPath(n.slice(0,r),n.slice(r+1))}};function o(e){if(!e||typeof e!=`object`)return;let t=e.content?.find(e=>e.type===`text`)?.text;if(typeof t==`string`)try{let e=JSON.parse(t);return e&&typeof e==`object`?e:void 0}catch{return}}function s(e){if(!e||typeof e!=`object`)return;if(e.isError)return`Tool returned MCP error response`;let t=o(e);if(t?.success===!1)return typeof t.error==`string`?t.error:`Tool reported success=false`}function c(e){if(Array.isArray(e))return e.reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0});if(!e||typeof e!=`object`)return{success:0,failure:0};let t=e;if(Array.isArray(t.__order))return t.__order.reduce((e,n)=>{let r=c(t[n]);return e.success+=r.success,e.failure+=r.failure,e},{success:0,failure:0});let n=o(e);return n?.success===!0?{success:1,failure:0}:n?.success===!1||`error`in t?{success:0,failure:1}:{success:0,failure:0}}function l(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=i.startsWith("${")?i:`\${${i}}`;n[r]=t.resolve(e)}return n}function u(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}function d(e,t){if(typeof e==`string`)return t.resolve(e);if(Array.isArray(e))return e.map(e=>d(e,t));if(e&&typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}return e}function f(e,t){if(e.has(t))return e.get(t);let[n,...r]=t.split(`.`);if(!n||!e.has(n))return;let i=e.get(n);if(i&&typeof i==`object`){let e=o(i);e&&(i=e)}for(let e of r){if(i&&typeof i==`object`){let t=e.match(/^(\d+)$/);if(t&&Array.isArray(i)){i=i[Number(t[1])];continue}i=i[e];continue}return}return i}function p(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){let n=e,r=t;return n.length===r.length&&n.every((e,t)=>p(e,r[t]))}let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>p(e[n],t[n])):!1}return!1}async function m(e,t){if(e.predicateFn)return await e.predicateFn(t);if(e.predicateId===`always_true`)return!0;if(e.predicateId===`always_false`)return!1;if(e.predicateId===`any_step_failed`)return[...t.stepResults.values()].some(e=>c(e).failure>0);let n=e.predicateId.match(/success_rate_gte_(\d+)/i);if(n?.[1]){let e=Number(n[1]),r=[...t.stepResults.values()].reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0}),i=r.success+r.failure;return i>0&&r.success/i>=e/100}let r=e.predicateId.match(/^variable_equals_(.+?)_(.+)$/);if(r?.[1]&&r[2])return p(f(t.stepResults,r[1]),r[2]);let i=e.predicateId.match(/^variable_contains_(.+?)_(.+)$/);if(i?.[1]&&i[2]){let e=f(t.stepResults,i[1]);return typeof e!=`string`&&!Array.isArray(e)?!1:String(e).includes(i[2])}let a=e.predicateId.match(/^variable_matches_(.+?)_(.+)$/);if(a?.[1]&&a[2]){let e=f(t.stepResults,a[1]);if(typeof e!=`string`)return!1;try{return new RegExp(a[2]).test(e)}catch{return!1}}throw Error(`Unknown workflow predicateId "${e.predicateId}"`)}function h(e){switch(e.kind){case`tool`:return[e];case`sequence`:case`parallel`:return e.steps.flatMap(e=>h(e));case`branch`:return[...h(e.whenTrue),...e.whenFalse?h(e.whenFalse):[]];case`fallback`:return[...h(e.primary),...h(e.fallback)];default:return[]}}function g(e){try{let t=e.getDomainInstance(`evidenceGraph`);return t?{hasGraph:!0,nodeCount:t.nodeCount,edgeCount:t.edgeCount}:{hasGraph:!1,nodeCount:0,edgeCount:0}}catch{return{hasGraph:!1,nodeCount:0,edgeCount:0}}}function _(e,t){let n=r(),i=[];for(let r of h(e)){let e=n[r.toolName]??[];for(let n of e)n.check(t)||i.push({nodeId:r.id,toolName:r.toolName,condition:n.condition,fix:n.fix})}return i}var v=class{runs=new Map;lastSuccess=new Map;recordSuccess(e){let n={workflowId:e.workflowId,runId:e.runId,startedAt:e.startedAt,finishedAt:e.finishedAt,durationMs:e.durationMs,status:`success`,stepResultKeys:Object.keys(e.stepResults)};this.runs.set(e.runId,n),this.lastSuccess.set(e.workflowId,e),t.debug(`workflow run recorded: ${e.runId} (${e.workflowId})`)}recordError(e,n,r,i){let a={workflowId:e,runId:n,startedAt:r,finishedAt:new Date().toISOString(),durationMs:Date.now()-new Date(r).getTime(),status:`error`,stepResultKeys:[]};this.runs.set(n,a),t.debug(`workflow run error: ${n} (${e}): ${i}`)}getRun(e){return this.runs.get(e)}getLastSuccess(e){return this.lastSuccess.get(e)}listRuns(e){let t=[...this.runs.values()];return e?t.filter(t=>t.workflowId===e):t}clear(){this.runs.clear(),this.lastSuccess.clear()}},y=class extends Error{warnings;constructor(e){super(`Workflow preflight failed with ${e.length} unsatisfied prerequisite(s)`),this.warnings=e,this.name=`PreflightError`}},b=e({executeExtensionWorkflow:()=>O});const x=new v;function S(e,t,n){let r=t.split(`.`).filter(Boolean),i=e;for(let e of r){if(!i||typeof i!=`object`)return n;i=i[e]}return i??n}function C(e){return new Promise(t=>setTimeout(t,e))}async function w(e,t,n){return!Number.isFinite(t)||t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}async function T(e,t,n,r){let i=t.inputFrom?l(t.inputFrom,r.dataBus):{},a={...t.input?u(t.input,r.dataBus):{},...i,...n?.[t.id]},o=async()=>{let n=await w(e.executeToolWithTracking(t.toolName,a),t.timeoutMs??0,`Workflow tool node "${t.id}"`),i=s(n);if(i)throw Error(i);return r.dataBus.set(t.id,n),n},c=t.retry;if(!c)return o();let d=0,f=c.backoffMs;for(;d<c.maxAttempts;)try{return await o()}catch(e){if(d+=1,d>=c.maxAttempts)throw e;await C(f),f=Math.max(0,Math.floor(f*(c.multiplier??1)))}throw Error(`Workflow tool node "${t.id}" exhausted retries`)}async function E(e,t,n,r){let i=Math.max(1,t.maxConcurrency??4),a={__order:[]},o=0,s=!1,c=async()=>{for(;;){if(s)return;let i=o;if(o+=1,i>=t.steps.length)return;let c=t.steps[i];if(!c)return;try{let t=await D(e,c,n,r);a[c.id]=t,a.__order.push(c.id)}catch(e){if(t.failFast)throw s=!0,e;a[c.id]={success:!1,error:e instanceof Error?e.message:String(e)},a.__order.push(c.id)}}};return await Promise.all(Array.from({length:Math.min(i,t.steps.length)},()=>c())),a}async function D(e,t,n,r){n.emitSpan(`workflow.node.start`,{nodeId:t.id,kind:t.kind});let i;switch(t.kind){case`tool`:i=await T(e,t,r.nodeInputOverrides,n);break;case`sequence`:{let a=t,o=[];for(let t of a.steps)o.push(await D(e,t,n,r));i=o;break}case`parallel`:i=await E(e,t,n,r);break;case`branch`:{let a=t,o=await m(a,n)?a.whenTrue:a.whenFalse;i=o?await D(e,o,n,r):void 0;break}case`fallback`:{let a=t;try{i=await D(e,a.primary,n,r)}catch(t){n.emitSpan(`workflow.node.fallback`,{nodeId:a.id,primaryNodeId:a.primary.id,fallbackNodeId:a.fallback.id,error:t instanceof Error?t.message:String(t)}),i=await D(e,a.fallback,n,r)}break}default:throw Error(`Unsupported workflow node kind: ${t.kind}`)}return n.stepResults.set(t.id,i),n.emitSpan(`workflow.node.finish`,{nodeId:t.id,kind:t.kind}),i}async function O(e,t,r={}){let o=i(),s=r.profile??String(e.baseTier??`workflow`),c=new Date().toISOString(),l=Date.now(),u=[],d=[],f=new Map,p=new a,m=r.config?{...e.config,...r.config}:e.config,h={workflowRunId:o,profile:s,stepResults:f,dataBus:p,invokeTool(t,n){return e.executeToolWithTracking(t,n)},emitSpan(e,t){d.push({name:e,attrs:t,at:new Date().toISOString()})},emitMetric(e,t,n,r){u.push({name:e,value:t,type:n,attrs:r,at:new Date().toISOString()})},getConfig(e,t){return S(m,e,t)}};try{await t.onStart?.(h);let i=t.build(h),a=r.preflightMode??`warn`,p=[];if(a===`skip`)h.emitSpan(`workflow.preflight`,{mode:a,skipped:!0,evidenceState:g(e),warningCount:0});else try{let t=await n(e),r=g(e);if(p=_(i,t),h.emitSpan(`workflow.preflight`,{mode:a,routingState:t,evidenceState:r,warningCount:p.length,warnings:p}),a===`strict`&&p.length>0)throw new y(p)}catch(t){if(t instanceof y)throw t;h.emitSpan(`workflow.preflight`,{mode:a,warningCount:0,skipped:!0,error:t instanceof Error?t.message:String(t),evidenceState:g(e)})}let m=await w(D(e,i,h,r),r.timeoutMs??t.timeoutMs??0,`Workflow "${t.id}"`);await t.onFinish?.(h,m);try{let t=typeof e.getDomainInstance==`function`?e.getDomainInstance(`evidenceGraph`):void 0;t&&t.nodeCount>0&&(f.set(`__evidenceSnapshot`,t.exportJson()),h.emitSpan(`workflow.evidence.auto-export`,{nodeCount:t.nodeCount,edgeCount:t.edgeCount}))}catch(e){h.emitSpan(`workflow.evidence.auto-export`,{skipped:!0,error:e instanceof Error?e.message:String(e)})}let v={workflowId:t.id,displayName:t.displayName,runId:o,profile:s,startedAt:c,finishedAt:new Date().toISOString(),durationMs:Date.now()-l,result:m,stepResults:Object.fromEntries(f.entries()),metrics:u,spans:d};return x.recordSuccess(v),v}catch(e){let n=e instanceof Error?e:Error(String(e));throw x.recordError(t.id,o,c,n),await t.onError?.(h,n),n}}export{O as n,b as t};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{Ft as t,Gr as n,Kr as r,Pt as i,Wr as a,c as o,o as s,s as c}from"./constants-BYj8Xek8.mjs";import{n as l,r as u}from"./response-C7rKQst4.mjs";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./parse-args-Bw413PlW.mjs";import{s as _}from"./PageController-Dfsm1_o7.mjs";import"./definitions-D5wl_8HN.mjs";import{n as v}from"./ResponseBuilder-BfWP-uaT.mjs";import{n as y,t as b}from"./webcrack-C1iYG_EX.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
|
+
`]);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
|
+
`&&(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
|
+
`);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};
|