@jshookmcp/jshook 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -4
- package/README.zh.md +19 -4
- package/dist/AntiCheatDetector-B-mz4DK_.mjs +1 -0
- package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-Cdic8FsH.mjs} +1 -1
- package/dist/CodeAnalyzerDataFlow-a-NkwcaG.mjs +2 -0
- package/dist/CodeInjector-B099WO6x.mjs +1 -0
- package/dist/ConsoleMonitor-BZRqrBH-.mjs +306 -0
- package/dist/CpuEngine-BC8jayy9.mjs +1 -0
- package/dist/DartAotExecutor-B7WVTKsd.mjs +1 -0
- package/dist/DartAotLoader-BxdhW-K2.mjs +2 -0
- package/dist/DarwinAPI-DzojdfjF.mjs +1 -0
- package/dist/DetailedDataManager-Dgh402Gp.mjs +5 -0
- package/dist/ExecutionSandbox-QbWQmzuC.mjs +45 -0
- package/dist/ExtensionManager.tools-D3h818Xs.mjs +1 -0
- package/dist/FingerprintManager-D9Zlr6be.mjs +1 -0
- package/dist/HardwareBreakpoint-C_lJ22bj.mjs +1 -0
- package/dist/HeapAnalyzer-bJbLvzp6.mjs +1 -0
- package/dist/HookPatternScanner-yx4vJ9sd.mjs +1 -0
- package/dist/InstrumentationSession-Cv1wikLA.mjs +1 -0
- package/dist/IntegrityScanner-BB7sw-SA.mjs +1 -0
- package/dist/JScramblerDeobfuscator-NVR5VatT.mjs +1 -0
- package/dist/MCPServer.activation.ttl-C2wOCMLV.mjs +1 -0
- package/dist/MCPServer.search.helpers-DlassAew.mjs +2 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/MemoryController-CCsGuGJS.mjs +2 -0
- package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-BZ2A9Ph1.mjs} +1 -1
- package/dist/MemoryScanner-DAxsq7Sx.mjs +1 -0
- package/dist/NativeMemoryManager.impl-BIJzXMqH.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-CMoul2an.mjs} +1 -1
- package/dist/PEAnalyzer-CB_kaTis.mjs +1 -0
- package/dist/PackerDeobfuscator-BpwGjxDL.mjs +7 -0
- package/dist/PointerChainEngine-B6SYv6ZM.mjs +1 -0
- package/dist/ProcessRegistry-C5W1Tkn9.mjs +1 -0
- package/dist/{handlers-mPFiNPe8.mjs → QuickJSSandbox-CIde-jzG.mjs} +2 -5
- package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-BLicSCjn.mjs} +1 -1
- package/dist/ReverseEvidenceGraph-DJzk0GQz.mjs +2 -0
- package/dist/ServerRuntimeState-DGXNv8Ji.mjs +1 -0
- package/dist/Speedhack-MGoeq1ZS.mjs +1 -0
- package/dist/StructureAnalyzer-CCTWAXR3.mjs +2 -0
- package/dist/ToolHandlerMap-C40EmuLT.mjs +1 -0
- package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-B02GC3ZY.mjs} +1 -1
- package/dist/ToolRegistry-CzqQxFqf.mjs +1 -0
- package/dist/ToolRouter.policy-Bgb3S8jc.mjs +4 -0
- package/dist/TraceRecorder-BfeCTQUj.mjs +407 -0
- package/dist/VMDeobfuscator-BHtkV850.mjs +1 -0
- package/dist/Win32API-G7QPyckq.mjs +1 -0
- package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-6yzmtv5b.mjs} +1 -1
- package/dist/allocation-track-CiI-CnaI.mjs +1 -0
- package/dist/analysis-CojUzwX-.mjs +27 -0
- package/dist/antidebug-CgU84TE1.mjs +1 -0
- package/dist/apk-DrPBsOq8.mjs +1 -0
- package/dist/artifactRetention-Bk6fW2uF.mjs +1 -0
- package/dist/artifacts-Bx9GLx4J.mjs +1 -0
- package/dist/ast-bridge-BlOrmVAv.mjs +1 -0
- package/dist/ast-utils-B9E5k_v1.mjs +1 -0
- package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
- package/dist/binary-instrument-DiE1BP0x.mjs +12 -0
- package/dist/boringssl-inspector-C6M3sOga.mjs +2 -0
- package/dist/browser-QDUu5ML9.mjs +29 -0
- package/dist/{handlers-yo_xYzT8.mjs → canvas-g5kmLdY-.mjs} +1098 -24
- package/dist/{capabilities-CyXuKUl1.mjs → capabilities-DwzyxL2w.mjs} +1 -1
- package/dist/cdp-session-Dy4OwMOP.mjs +1 -0
- package/dist/collector-Cld4i-E4.mjs +1 -0
- package/dist/config-5ODJ3Aj0.mjs +3 -0
- package/dist/constants-nvsLpSri.mjs +1 -0
- package/dist/coordination-C6y2gM9O.mjs +98 -0
- package/dist/coverage-and-block--cWjjEe5.mjs +1 -0
- package/dist/dart-inspector-D4IKxZ6u.mjs +0 -0
- package/dist/debugger-C2SpiXoO.mjs +1 -0
- package/dist/definitions-0mtilYzG.mjs +1 -0
- package/dist/definitions-9csunmeX.mjs +1 -0
- package/dist/definitions-B11MudW_.mjs +1 -0
- package/dist/definitions-BKpRDjcI.mjs +1 -0
- package/dist/definitions-BXE3H4re.mjs +1 -0
- package/dist/definitions-BlPHe5DX.mjs +1 -0
- package/dist/definitions-Bob4XMxI.mjs +27 -0
- package/dist/definitions-BpIQN2nm.mjs +1 -0
- package/dist/definitions-BvolWeSu.mjs +1 -0
- package/dist/definitions-C-6j3Ejl.mjs +1 -0
- package/dist/definitions-C-AdFfFu.mjs +1 -0
- package/dist/definitions-CArdw_9T.mjs +1 -0
- package/dist/definitions-CCvIcRrT.mjs +1 -0
- package/dist/definitions-CJPE5PIl.mjs +1 -0
- package/dist/definitions-CbqeW06u.mjs +1 -0
- package/dist/definitions-Cexmkypg.mjs +1 -0
- package/dist/definitions-D1dxl8qt.mjs +1 -0
- package/dist/definitions-D3uT-ZbU.mjs +1 -0
- package/dist/definitions-DtOY5iUc.mjs +1 -0
- package/dist/{definitions-DxFNRQNK2.mjs → definitions-DvrYdDCJ2.mjs} +1 -1
- package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/definitions-ihxOqOC4.mjs +1 -0
- package/dist/deopt-trace-qnAcC931.mjs +17 -0
- package/dist/disasm-DoxSucGp.mjs +1 -0
- package/dist/dumpsys-parser-Du-5ruEe.mjs +2 -0
- package/dist/encoding-UMtwgy4M.mjs +2 -0
- package/dist/ensure-browser-core-BP70x0TB.mjs +285 -0
- package/dist/factory-BeND77hf.mjs +2 -0
- package/dist/graphql-CF7QKJME.mjs +68 -0
- package/dist/grpc-raw-Dp7ps2sv.mjs +1 -0
- package/dist/handlers--qCl9vNv.mjs +1 -0
- package/dist/handlers-BHIu1LqA.mjs +1 -0
- package/dist/{antidebug-7L3ygj_9.mjs → handlers-BQ4K8Jbr.mjs} +2 -2
- package/dist/handlers-BxQv-wtf.mjs +8 -0
- package/dist/handlers-ByYG27-5.mjs +1 -0
- package/dist/handlers-C0I9-BtX.mjs +5 -0
- package/dist/handlers-CL0Iokmw.mjs +1 -0
- package/dist/handlers-CNbhIdSK.mjs +4 -0
- package/dist/handlers-CnTTSJFs.mjs +109 -0
- package/dist/handlers-CoDx6akJ2.mjs +49 -0
- package/dist/{handlers-0yKLRIfo.mjs → handlers-DASJI0Pn.mjs} +1 -1
- package/dist/handlers-DRKMaA-_.mjs +74 -0
- package/dist/handlers-Dalu0olz.mjs +2 -0
- package/dist/handlers-KY0g31ny.mjs +9 -0
- package/dist/handlers-oGo60aVv.mjs +1 -0
- package/dist/handlers.impl-BTXLw6Qc.mjs +1 -0
- package/dist/heap-sampling-BqdiU-5j.mjs +1 -0
- package/dist/{hooks-D4XLfgtV.mjs → hooks-COK3t5rT.mjs} +52 -33
- package/dist/index.mjs +11 -11
- package/dist/logger-BGCcd-jJ.mjs +1 -0
- package/dist/macro-nUYUjKNZ.mjs +2 -0
- package/dist/maintenance-CfnE7ZKU.mjs +4 -0
- package/dist/manifest-7EOTUc0D.mjs +1 -0
- package/dist/manifest-B5ujuQmf.mjs +1 -0
- package/dist/manifest-BErXl3zn.mjs +1 -0
- package/dist/manifest-BKA-mD3J.mjs +1 -0
- package/dist/manifest-BUXj23bX.mjs +1 -0
- package/dist/manifest-BfXt9cau.mjs +1 -0
- package/dist/manifest-Bx-tpURK.mjs +1 -0
- package/dist/manifest-C0owVAdq.mjs +1 -0
- package/dist/manifest-C5XqYc9o.mjs +1 -0
- package/dist/manifest-CVKzLjsA.mjs +1 -0
- package/dist/manifest-CaeFjdhj.mjs +1 -0
- package/dist/manifest-CegBgip0.mjs +1 -0
- package/dist/manifest-CoJHqlgS.mjs +1 -0
- package/dist/manifest-D0dbtDqd.mjs +1 -0
- package/dist/manifest-D5Gr8ujd.mjs +12 -0
- package/dist/manifest-D82z-5og.mjs +1 -0
- package/dist/manifest-DA2afIwh.mjs +1 -0
- package/dist/manifest-DAbiFP5o.mjs +1 -0
- package/dist/manifest-DEY0s1O72.mjs +1 -0
- package/dist/manifest-DTOqNqiA.mjs +1 -0
- package/dist/manifest-DZ6ELNgX.mjs +1 -0
- package/dist/manifest-DjHkjddT.mjs +1 -0
- package/dist/manifest-DocA_itf2.mjs +1 -0
- package/dist/manifest-Dpnhvfq0.mjs +1 -0
- package/dist/manifest-DucPMG_a.mjs +1 -0
- package/dist/manifest-Dw5yYEac.mjs +1 -0
- package/dist/manifest-Ic_Cg66S.mjs +1 -0
- package/dist/manifest-JHaG6GMN.mjs +1 -0
- package/dist/manifest-QdkIzmYM.mjs +1 -0
- package/dist/manifest-YZqaCe25.mjs +1 -0
- package/dist/manifest-f0lUeXwq.mjs +1 -0
- package/dist/manifest-h-Ebisf8.mjs +1 -0
- package/dist/manifest-oOfTymBS.mjs +1 -0
- package/dist/manifest-qXqrO6KC.mjs +2 -0
- package/dist/mapsParser-DrJoeC0c.mjs +1 -0
- package/dist/modules-CC_ADmwi.mjs +333 -0
- package/dist/mojo-ipc-kVztXYw-.mjs +140 -0
- package/dist/native-D9ouskXO.mjs +961 -0
- package/dist/native-bridge-Dzd7hYoq.mjs +1 -0
- package/dist/network-C5Y-S87J.mjs +7 -0
- package/dist/one-gadget-CiWFE17F.mjs +1 -0
- package/dist/outputPaths-CHtELDyi.mjs +1 -0
- package/dist/parse-args-B6dwWc9k.mjs +1 -0
- package/dist/platform-BIXgJaM3.mjs +94 -0
- package/dist/process-aDIfLC0v.mjs +6 -0
- package/dist/proxy-DsHsQ1I4.mjs +2 -0
- package/dist/registry-7h8jJ9y9.mjs +1 -0
- package/dist/{registry-DH4sc1dt.mjs → registry-DJDnkQW2.mjs} +1 -1
- package/dist/response-R8ghbZSb.mjs +1 -0
- package/dist/retry-policy-DtYv0kDi.mjs +1 -0
- package/dist/reverseEngineeringConfig-BhZLOa3C.mjs +1 -0
- package/dist/safeOutput-Dt4mfjXA.mjs +1 -0
- package/dist/search-defaults-BBRJNAzC.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/server/search/EmbeddingWorker.d.mts +1 -0
- package/dist/server/search/EmbeddingWorker.mjs +1 -0
- package/dist/shared-BKtWZDGN.mjs +1 -0
- package/dist/sourcemap-2VIeVeKw.mjs +3 -0
- package/dist/streaming-DkpE3GGU.mjs +15 -0
- package/dist/syscall-DGZoYM_U.mjs +1 -0
- package/dist/transform-BJqsBC_-.mjs +105 -0
- package/dist/turbofan-graph-CbGHNVtl.mjs +1 -0
- package/dist/turbofan-inspect--NdCuYXi.mjs +23 -0
- package/dist/types-CWSvzmIh.mjs +1 -0
- package/dist/v8-inspector-CTJo08-K.mjs +297 -0
- package/dist/wasm-DX4Qm2Vs.mjs +235 -0
- package/dist/weakrefs-inspect-CnhaF-rN.mjs +57 -0
- package/dist/webgpu-D4-DxbxZ.mjs +6 -0
- package/dist/workflow-DHktRNF2.mjs +108 -0
- package/package.json +33 -27
- package/dist/AntiCheatDetector-B6d4Qe9D.mjs +0 -1
- package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
- package/dist/ConsoleMonitor-CxDJV15E.mjs +0 -306
- package/dist/DOMInspector-C19J4zeq.mjs +0 -95
- package/dist/DarwinAPI-ZfQdpLNI.mjs +0 -1
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
- package/dist/ExtensionManager-BD724zkO.mjs +0 -1
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +0 -1
- package/dist/FingerprintManager-DT0EAUEo.mjs +0 -1
- package/dist/HardwareBreakpoint-BUfPdp0f.mjs +0 -1
- package/dist/HeapAnalyzer-B_aqY8oj.mjs +0 -1
- package/dist/InstrumentationSession-D_G1ZPyd.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
- package/dist/MemoryController-X1XNSn1n.mjs +0 -2
- package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
- package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
- package/dist/PEAnalyzer-yWQaGrcx.mjs +0 -1
- package/dist/PageController-Dfsm1_o7.mjs +0 -1
- package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
- package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
- package/dist/ProcessRegistry-C-bN48oR.mjs +0 -1
- package/dist/ReverseEvidenceGraph-BhSYYdiI.mjs +0 -2
- package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
- package/dist/Speedhack-yseDPSZ9.mjs +0 -1
- package/dist/StructureAnalyzer-C5lpuZkg.mjs +0 -2
- package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
- package/dist/ToolRegistry-C5oB8KP8.mjs +0 -1
- package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
- package/dist/TraceRecorder-BiJWBXHX.mjs +0 -272
- package/dist/VersionDetector-CHT36Az0.mjs +0 -9
- package/dist/Win32API-eUCF57l_.mjs +0 -1
- package/dist/WorkflowEngine-D876meOO.mjs +0 -1
- package/dist/analysis-D4swdMvq.mjs +0 -6
- package/dist/apk-packer-BqXcInnX.mjs +0 -1
- package/dist/artifactRetention-BCPQASm7.mjs +0 -1
- package/dist/artifacts-CkodUM4j.mjs +0 -1
- package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
- package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
- package/dist/boringssl-inspector-BBaJwwkU.mjs +0 -2
- package/dist/browser-Qqco2rOT.mjs +0 -11
- package/dist/collector-Bpl6qy2L.mjs +0 -1
- package/dist/constants-BYj8Xek8.mjs +0 -1
- package/dist/coordination-CWXW1o8K.mjs +0 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/debugger-DyALjYMk.mjs +0 -1
- package/dist/definitions-BWxBke3r.mjs +0 -1
- package/dist/definitions-BYwATKc-.mjs +0 -1
- package/dist/definitions-B_83XfNQ.mjs +0 -1
- package/dist/definitions-Bf3H1EwV.mjs +0 -1
- package/dist/definitions-BftdXgXI.mjs +0 -1
- package/dist/definitions-Bio5XJYy.mjs +0 -1
- package/dist/definitions-C3qNgSn1.mjs +0 -1
- package/dist/definitions-CB6vmOer.mjs +0 -1
- package/dist/definitions-CMZRSy3k.mjs +0 -1
- package/dist/definitions-CQd7yCQH.mjs +0 -1
- package/dist/definitions-CT8ln6GQ.mjs +0 -1
- package/dist/definitions-D4g-MS10.mjs +0 -1
- package/dist/definitions-D5wl_8HN.mjs +0 -1
- package/dist/definitions-DAQm1Xar.mjs +0 -1
- package/dist/definitions-DP1vgxEY.mjs +0 -1
- package/dist/definitions-Ibci7e_L.mjs +0 -1
- package/dist/definitions-OeLvmlQy.mjs +0 -1
- package/dist/definitions-RZYGD_Ey.mjs +0 -1
- package/dist/definitions-Tls8c0A0.mjs +0 -1
- package/dist/definitions-bybDvnG0.mjs +0 -26
- package/dist/definitions-l7TjdE6V.mjs +0 -1
- package/dist/encoding-ycOaz8Vr.mjs +0 -2
- package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
- package/dist/factory-CKr4fAE1.mjs +0 -1
- package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
- package/dist/graphql-B2TiPEow.mjs +0 -62
- package/dist/handlers-8zN_vBIz.mjs +0 -1
- package/dist/handlers-B62K4FTc.mjs +0 -1
- package/dist/handlers-BpDlVVVU.mjs +0 -1
- package/dist/handlers-CMJK7m1c.mjs +0 -31
- package/dist/handlers-D2ZOul9p.mjs +0 -54
- package/dist/handlers-D5E40ssn.mjs +0 -5
- package/dist/handlers-DGbdQAgD.mjs +0 -4
- package/dist/handlers-DHO3rjsW.mjs +0 -1
- package/dist/handlers-FJ80VzUI.mjs +0 -2
- package/dist/handlers-VHWrxbM_.mjs +0 -1
- package/dist/handlers-l8QIKqBj.mjs +0 -2
- package/dist/handlers.impl-D9Hh8Bgl.mjs +0 -1
- package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
- package/dist/logger-sBC6IdRT.mjs +0 -1
- package/dist/maintenance-BUpIukhg.mjs +0 -1
- package/dist/manifest-0Jpt_AQa.mjs +0 -1
- package/dist/manifest-B3fZbSWR.mjs +0 -1
- package/dist/manifest-B7NB2rh2.mjs +0 -1
- package/dist/manifest-BDi4nbH1.mjs +0 -1
- package/dist/manifest-BLDfkE7n.mjs +0 -1
- package/dist/manifest-BcXbB4gf.mjs +0 -1
- package/dist/manifest-Bdnc_vrc.mjs +0 -1
- package/dist/manifest-BuYKgCnp.mjs +0 -1
- package/dist/manifest-CBfNnGPV.mjs +0 -1
- package/dist/manifest-CPS1Xv69.mjs +0 -1
- package/dist/manifest-CQH9FhwI.mjs +0 -1
- package/dist/manifest-CRryuZF4.mjs +0 -1
- package/dist/manifest-CctIumog.mjs +0 -1
- package/dist/manifest-CvTe5ZGV2.mjs +0 -1
- package/dist/manifest-D-5GH0DV.mjs +0 -1
- package/dist/manifest-D3Ssf3IC.mjs +0 -1
- package/dist/manifest-D5ck3NvC.mjs +0 -1
- package/dist/manifest-D9jUUJAu.mjs +0 -1
- package/dist/manifest-DCx6w2XV.mjs +0 -1
- package/dist/manifest-DG19q-Ld.mjs +0 -1
- package/dist/manifest-DLMlD0Zc.mjs +0 -1
- package/dist/manifest-DYpn8w_h.mjs +0 -1
- package/dist/manifest-DYzWI8Xs.mjs +0 -1
- package/dist/manifest-D_obs5F4.mjs +0 -1
- package/dist/manifest-DujQqEQR.mjs +0 -2
- package/dist/manifest-DwL2ik8P.mjs +0 -1
- package/dist/manifest-ItF5P8A12.mjs +0 -1
- package/dist/manifest-KZphqIyX.mjs +0 -1
- package/dist/manifest-LG42zPLY2.mjs +0 -1
- package/dist/manifest-LLdI5m4T.mjs +0 -1
- package/dist/manifest-QYbQXJn0.mjs +0 -1
- package/dist/manifest-RcpX_MyZ.mjs +0 -123
- package/dist/manifest-YgVd8Sgz.mjs +0 -1
- package/dist/manifest-Zy7Odg5J.mjs +0 -1
- package/dist/manifest-ff1H7Pdp.mjs +0 -1
- package/dist/manifest-iuhF6pTL2.mjs +0 -1
- package/dist/manifest-nXHmtMSp2.mjs +0 -1
- package/dist/manifest-xWfu6iLo.mjs +0 -1
- package/dist/manifest-yC16OhL2.mjs +0 -1
- package/dist/manifest-ztWJoXy4.mjs +0 -1
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
- package/dist/modules-BPBcSaM-.mjs +0 -333
- package/dist/mojo-ipc-BhwsdVUW.mjs +0 -9
- package/dist/native-j8l473zn.mjs +0 -961
- package/dist/network-T0VRwNPd.mjs +0 -7
- package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
- package/dist/parse-args-Bw413PlW.mjs +0 -1
- package/dist/platform-CzaQtISh.mjs +0 -93
- package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
- package/dist/process-CWhsCWrf.mjs +0 -2
- package/dist/proxy-DZFlDsG3.mjs +0 -2
- package/dist/renderer-pid-9tJnZ_9N.mjs +0 -1
- package/dist/response-C7rKQst4.mjs +0 -1
- package/dist/search-defaults-lYBVn_3L.mjs +0 -1
- package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
- package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
- package/dist/streaming-BcJ0B6ao.mjs +0 -1
- package/dist/transform-DOxzeWPB.mjs +0 -103
- package/dist/types-D9EiE5o9.mjs +0 -1
- package/dist/wasm-CZ_HTfKR.mjs +0 -174
- package/dist/webcrack-C1iYG_EX.mjs +0 -46
- package/dist/workflow-BdwQmARn.mjs +0 -101
- /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
- /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
- /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
- /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
- /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
- /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
- /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
- /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
- /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → rolldown-runtime-88NL7fhV.mjs} +0 -0
- /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
- /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
- /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Hr as e,Ur as t,Vr as n}from"./constants-BYj8Xek8.mjs";import{t as r}from"./factory-CKr4fAE1.mjs";import{t as i}from"./NativeMemoryManager.impl-DniBe2wf.mjs";var a=class{providerCache=null;get provider(){return this.providerCache||=r(),this.providerCache}set provider(e){this.providerCache=e}async analyzeStructure(e,t,r){let i=r?.size??n,a=BigInt(t.startsWith(`0x`)?t:`0x${t}`),o=this.provider.openProcess(e,!1);try{let t=this.provider.readMemory(o,a,i).data,n=[],s=0;for(;s<i;){let e=i-s;if(e<1)break;let r=this.classifyValue(t,o,a,s,e);n.push({offset:s,size:r.size,type:r.type,name:`field_0x${s.toString(16).padStart(2,`0`).toUpperCase()}`,value:r.value,confidence:r.confidence,notes:r.notes}),s+=r.size}let c,l,u;if(n.length>0&&n[0].type===`vtable_ptr`&&(c=n[0].value,r?.parseRtti!==!1&&c))try{let t=await this.parseRtti(e,c,o);t&&(l=t.className,u=t.baseClasses)}catch{}return{baseAddress:`0x${a.toString(16).toUpperCase()}`,totalSize:i,fields:n,vtableAddress:c,className:l,baseClasses:u,timestamp:Date.now()}}finally{this.provider.closeProcess(o)}}async parseVtable(e,n){let r=BigInt(n.startsWith(`0x`)?n:`0x${n}`),i=this.provider.openProcess(e,!1);try{let a=[],o=await this.getModuleEntries(e);for(let e=0;e<t;e++){let t=r+BigInt(e*8),n;try{n=this.provider.readMemory(i,t,8).data.readBigUInt64LE(0)}catch{break}if(!this.isValidExecutablePointer(i,n))break;let s=this.resolveToModule(n,o);a.push({index:e,address:`0x${n.toString(16).toUpperCase()}`,module:s?.module,moduleOffset:s?.offset})}let s,c;try{let t=await this.parseRtti(e,n,i);t&&(s=t.className,c=t.baseClasses)}catch{}return{address:`0x${r.toString(16).toUpperCase()}`,functionCount:a.length,functions:a,rttiName:s,baseClasses:c}}finally{this.provider.closeProcess(i)}}async parseRtti(t,n,r){let i=BigInt(n.startsWith(`0x`)?n:`0x${n}`),a=!r,o=r??this.provider.openProcess(t,!1);try{let t=this.provider.readMemory(o,i-8n,8).data.readBigUInt64LE(0);if(!this.isValidReadablePointer(o,t))return null;let n=this.provider.readMemory(o,t,24).data;if(n.readUInt32LE(0)!==1)return null;let r=n.readUInt32LE(12),a=n.readUInt32LE(16),s=n.readUInt32LE(20),c=t-BigInt(s),l=c+BigInt(r),u=this.readCString(o,l+16n,e);if(!u)return null;let d=this.demangleMsvcName(u),f=[];try{let t=c+BigInt(a),n=this.provider.readMemory(o,t,16).data,r=n.readUInt32LE(8),i=n.readUInt32LE(12);if(r>0&&r<20){let t=c+BigInt(i),n=this.provider.readMemory(o,t,r*4).data;for(let t=1;t<r;t++){let r=n.readUInt32LE(t*4),i=c+BigInt(r);try{let t=this.provider.readMemory(o,i,8).data.readUInt32LE(0),n=c+BigInt(t),r=this.readCString(o,n+16n,e);r&&f.push(this.demangleMsvcName(r))}catch{break}}}}catch{}return{className:d,baseClasses:f}}catch{return null}finally{a&&this.provider.closeProcess(o)}}exportToCStruct(e,t){let n=t??e.className??`UnknownStruct`,r=[];r.push(`struct ${n} { // size: 0x${e.totalSize.toString(16).toUpperCase()} (${e.totalSize} bytes)`);for(let t of e.fields){let e=this.fieldTypeToCType(t.type,t.size),n=`0x${t.offset.toString(16).padStart(2,`0`).toUpperCase()}`,i=t.notes?`// +${n} ${t.notes}`:`// +${n} = ${t.value}`;t.type===`padding`?r.push(` uint8_t _pad_${t.offset.toString(16)}[${t.size}]; ${i}`):r.push(` ${e} ${t.name}; ${i}`)}return r.push(`};`),{name:n,definition:r.join(`
|
|
2
|
-
`),size:e.totalSize,fieldCount:e.fields.filter(e=>e.type!==`padding`).length}}async compareInstances(e,t,r,i){let a=i??n,[o,s]=await Promise.all([this.analyzeStructure(e,t,{size:a,parseRtti:!1}),this.analyzeStructure(e,r,{size:a,parseRtti:!1})]),c=[],l=[],u=new Map(s.fields.map(e=>[e.offset,e]));for(let e of o.fields){let t=u.get(e.offset);t&&(e.value===t.value&&e.type===t.type?c.push(e):l.push({offset:e.offset,value1:e.value,value2:t.value,type:e.type}))}return{matching:c,differing:l}}classifyValue(e,t,n,r,i){if(i>=8){let n=e.readBigUInt64LE(r);if(r===0&&n!==0n&&this.isValidExecutablePointer(t,n))try{let e=this.provider.readMemory(t,n,16).data.readBigUInt64LE(0);if(this.isValidExecutablePointer(t,e))return{type:`vtable_ptr`,size:8,value:`0x${n.toString(16).toUpperCase()}`,confidence:.9,notes:`likely vtable pointer (points to array of executable pointers)`}}catch{}if(n!==0n&&n>65536n&&n<140737488355327n&&this.isValidReadablePointer(t,n)){let e=this.readCString(t,n,64);return e&&e.length>=2?{type:`string_ptr`,size:8,value:`0x${n.toString(16).toUpperCase()} → "${e.slice(0,32)}${e.length>32?`...`:``}"`,confidence:.75,notes:`string pointer: "${e.slice(0,64)}"`}:{type:`pointer`,size:8,value:`0x${n.toString(16).toUpperCase()}`,confidence:.7,notes:`valid pointer to readable memory`}}}if(i>=4){let t=e.readUInt32LE(r),n=e.readInt32LE(r),a=e.readFloatLE(r);if(t===0&&i>=8&&e.readUInt32LE(r+4)===0){let t=0;for(let n=r;n<e.length&&e[n]===0;n++)t++;let n=Math.min(t,i)&-8;return{type:`padding`,size:n,value:`0x${`00`.repeat(Math.min(n,8))}`,confidence:.6}}if(t===0)return{type:`int32`,size:4,value:`0`,confidence:.4,notes:`zero value — could be int, bool, or padding`};if(t===1)return{type:`bool`,size:4,value:`true`,confidence:.5,notes:`value is 1 — could be boolean`};if(isFinite(a)&&!isNaN(a)&&Math.abs(a)>1e-10&&Math.abs(a)<1e8){let e=t>0&&t<1e5,n=Math.abs(a-Math.round(a))>.001;if(n||!e&&Math.abs(a)<1e4)return{type:`float`,size:4,value:a.toFixed(6),confidence:n?.8:.5,notes:n?`IEEE 754 float with fractional part`:`could be float or int`}}return t<2147483648?{type:`int32`,size:4,value:n.toString(),confidence:.6}:{type:`uint32`,size:4,value:t.toString(),confidence:.5}}return i>=2?{type:`uint16`,size:2,value:e.readUInt16LE(r).toString(),confidence:.4}:{type:`uint8`,size:1,value:e.readUInt8(r).toString(),confidence:.3}}isValidReadablePointer(e,t){try{let n=this.provider.queryRegion(e,t);return n?n.isReadable:!1}catch{return!1}}isValidExecutablePointer(e,t){try{let n=this.provider.queryRegion(e,t);return n?n.isReadable&&n.isExecutable:!1}catch{return!1}}readCString(e,t,n){try{let r=this.provider.readMemory(e,t,n).data,i=r.indexOf(0);if(i<0)return null;let a=r.subarray(0,i).toString(`ascii`);return/^[\x20-\x7E]+$/.test(a)&&a.length>=1?a:null}catch{return null}}demangleMsvcName(e){let t=e.match(/\.?\?A[VU](.+?)@@/);if(t)return t[1];let n=e.match(/\.?\?AW4(.+?)@@/);return n?n[1]:e.replace(/^\./,``).replace(/@@$/,``)}fieldTypeToCType(e,t){switch(e){case`int8`:return`int8_t`;case`uint8`:return`uint8_t`;case`int16`:return`int16_t`;case`uint16`:return`uint16_t`;case`int32`:return`int32_t`;case`uint32`:return`uint32_t`;case`int64`:return`int64_t`;case`uint64`:return`uint64_t`;case`float`:return`float`;case`double`:return`double`;case`pointer`:return`void*`;case`vtable_ptr`:return`void**`;case`string_ptr`:return`char*`;case`bool`:return`bool`;case`padding`:return`uint8_t[${t}]`;case`unknown`:return`uint8_t[${t}]`;default:return`uint8_t[${t}]`}}async getModuleEntries(e){let t=new Map;try{let n=await i.enumerateModules(e);if(n.success&&n.modules)for(let e of n.modules){let n=BigInt(e.baseAddress.startsWith(`0x`)?e.baseAddress:`0x${e.baseAddress}`);t.set(e.name.toLowerCase(),{name:e.name,base:n,size:e.size})}}catch{}return t}resolveToModule(e,t){for(let n of t.values())if(e>=n.base&&e<n.base+BigInt(n.size))return{module:n.name,offset:Number(e-n.base)};return null}};const o=new a;export{a as StructureAnalyzer,o as structureAnalyzer};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";const t=[{domain:`adb-bridge`,depKey:`adbBridgeHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DwL2ik8P.mjs`)},{domain:`core`,depKey:`coreAnalysisHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DujQqEQR.mjs`)},{domain:`antidebug`,depKey:`antidebugHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Zy7Odg5J.mjs`)},{domain:`apk-packer`,depKey:`apkPackerHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-ff1H7Pdp.mjs`)},{domain:`binary-instrument`,depKey:`binaryInstrumentHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BDi4nbH1.mjs`)},{domain:`binary-secrets`,depKey:`binarySecretsHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BuYKgCnp.mjs`)},{domain:`boringssl-inspector`,depKey:`boringsslInspectorHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-B3fZbSWR.mjs`)},{domain:`browser`,depKey:`browserHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BcXbB4gf.mjs`)},{domain:`canvas`,depKey:`canvasHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D3Ssf3IC.mjs`)},{domain:`coordination`,depKey:`coordinationHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-BLDfkE7n.mjs`)},{domain:`cross-domain`,depKey:`crossDomainHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-0Jpt_AQa.mjs`)},{domain:`dart-inspector`,depKey:`dartInspectorHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CctIumog.mjs`)},{domain:`debugger`,depKey:`debuggerHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CBfNnGPV.mjs`)},{domain:`encoding`,depKey:`encodingHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CPS1Xv69.mjs`)},{domain:`evidence`,depKey:`evidenceHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-B7NB2rh2.mjs`)},{domain:`extension-registry`,depKey:`extensionRegistryHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-xWfu6iLo.mjs`)},{domain:`graphql`,depKey:`graphqlHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-nXHmtMSp2.mjs`)},{domain:`hooks`,depKey:`aiHookHandlers`,profiles:[`full`],secondaryDepKeys:[`hookPresetHandlers`],load:()=>import(`./manifest-D5ck3NvC.mjs`)},{domain:`instrumentation`,depKey:`instrumentationHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-Bdnc_vrc.mjs`)},{domain:`jadx-search`,depKey:`jadxSearchHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-ItF5P8A12.mjs`)},{domain:`macro`,depKey:`macroHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DLMlD0Zc.mjs`)},{domain:`maintenance`,depKey:`coreMaintenanceHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[`extensionManagementHandlers`],load:()=>import(`./manifest-DG19q-Ld.mjs`)},{domain:`memory`,depKey:`memoryScanHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-ztWJoXy4.mjs`)},{domain:`mojo-ipc`,depKey:`mojoIpcHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CQH9FhwI.mjs`)},{domain:`network`,depKey:`advancedHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DCx6w2XV.mjs`)},{domain:`platform`,depKey:`platformHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-LLdI5m4T.mjs`)},{domain:`process`,depKey:`processHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DYzWI8Xs.mjs`)},{domain:`protocol-analysis`,depKey:`protocolAnalysisHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D9jUUJAu.mjs`)},{domain:`proxy`,depKey:`proxyHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-DYpn8w_h.mjs`)},{domain:`sandbox`,depKey:`sandboxHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CRryuZF4.mjs`)},{domain:`shared-state-board`,depKey:`sharedStateBoardHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-yC16OhL2.mjs`)},{domain:`skia-capture`,depKey:`skiaCaptureHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D-5GH0DV.mjs`)},{domain:`sourcemap`,depKey:`sourcemapHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-D_obs5F4.mjs`)},{domain:`streaming`,depKey:`streamingHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-KZphqIyX.mjs`)},{domain:`syscall-hook`,depKey:`syscallHookHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-QYbQXJn0.mjs`)},{domain:`trace`,depKey:`traceHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-LG42zPLY2.mjs`)},{domain:`transform`,depKey:`transformHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-CvTe5ZGV2.mjs`)},{domain:`v8-inspector`,depKey:`v8InspectorHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-RcpX_MyZ.mjs`)},{domain:`wasm`,depKey:`wasmHandlers`,profiles:[`full`],secondaryDepKeys:[],load:()=>import(`./manifest-YgVd8Sgz.mjs`)},{domain:`workflow`,depKey:`workflowHandlers`,profiles:[`workflow`,`full`],secondaryDepKeys:[],load:()=>import(`./manifest-iuhF6pTL2.mjs`)}],n={"adb-bridge":[`full`],core:[`workflow`,`full`],antidebug:[`full`],"apk-packer":[`full`],"binary-instrument":[`full`],"binary-secrets":[`full`],"boringssl-inspector":[`full`],browser:[`workflow`,`full`],canvas:[`full`],coordination:[`full`],"cross-domain":[`full`],"dart-inspector":[`full`],debugger:[`workflow`,`full`],encoding:[`workflow`,`full`],evidence:[`full`],"extension-registry":[`full`],graphql:[`workflow`,`full`],hooks:[`full`],instrumentation:[`full`],"jadx-search":[`full`],macro:[`full`],maintenance:[`workflow`,`full`],memory:[`full`],"mojo-ipc":[`full`],network:[`workflow`,`full`],platform:[`full`],process:[`full`],"protocol-analysis":[`full`],proxy:[`full`],sandbox:[`full`],"shared-state-board":[`workflow`,`full`],"skia-capture":[`full`],sourcemap:[`full`],streaming:[`workflow`,`full`],"syscall-hook":[`full`],trace:[`full`],transform:[`full`],"v8-inspector":[`workflow`,`full`],wasm:[`full`],workflow:[`workflow`,`full`]};function r(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.kind===`domain-manifest`&&t.version===1&&typeof t.domain==`string`&&typeof t.depKey==`string`&&Array.isArray(t.profiles)&&Array.isArray(t.registrations)&&typeof t.ensure==`function`}function i(e){if(!e||typeof e!=`object`)return null;let t=e;for(let e of[`default`,`manifest`,`domainManifest`]){let n=t[e];if(r(n))return n}return null}function a(e){let t=new Set;for(let[r,i]of Object.entries(n))i.includes(e)&&t.add(r);return t}function o(){return new Set(Object.keys(n))}function s(){return t}async function c(n){let r=[],a=new Set,o=new Set;for(let{domain:s,load:c}of t)if(!(n&&!n.has(s)))try{let t=i(await c());if(!t){e.warn(`[discovery] Skipping domain "${s}": no valid DomainManifest export`);continue}if(a.has(t.domain)){e.warn(`[discovery] Duplicate domain "`+t.domain+`" in generated manifests - skipping`);continue}if(o.has(t.depKey)){e.warn(`[discovery] Duplicate depKey "`+t.depKey+`" in generated manifests - skipping`);continue}a.add(t.domain),o.add(t.depKey),r.push(t),e.info(`[discovery] Loaded domain "`+t.domain+`" (`+String(t.registrations.length)+` tools)`)}catch(t){if(e.error(`[discovery] Failed to load domain "${s}"`,t),process.env.DISCOVERY_STRICT===`true`)throw t}let s=r.reduce((e,t)=>e+t.registrations.length,0);return n&&r.length===0?e.info(`[discovery] No manifests loaded for the requested startup profile. Domains remain available for lazy activation.`):e.info(`[discovery] Discovered `+String(r.length)+` domains, `+String(s)+` tools total`),r}async function l(n){let r=t.find(e=>e.domain===n);if(!r)return null;try{let t=i(await r.load());return t?(e.info(`[discovery] On-demand loaded domain "`+t.domain+`" (`+String(t.registrations.length)+` tools)`),t):(e.warn(`[discovery] Domain "${n}": no valid DomainManifest export`),null)}catch(t){return e.error(`[discovery] Failed to load domain "${n}"`,t),null}}function u(e,t){let n=new Set(t);return e.every(e=>n.has(e))}let d=null,f=null,p=null,m=null,h=null,g=null;async function _(t){if(d===null){if(p){await p;return}p=(async()=>{let n=await c(t?a(t):void 0);d=n,g=new Map;for(let t of n)for(let n of t.registrations){let r=n.domain?n:{...n,domain:t.domain},i=g.get(r.tool.name);i?e.warn(`[registry] Duplicate tool name "${r.tool.name}": domain "${r.domain}" conflicts with "${i.domain}" — keeping first`):g.set(r.tool.name,r)}f=[...g.values()],m=new Set(d.map(e=>e.domain)),h=new Set(f.map(e=>e.tool.name))})(),await p}}async function v(e){await _(e)}async function y(e){if(!d)throw Error(`[registry] Not initialised - call initRegistry() first.`);if(d.some(t=>t.domain===e))return d.find(t=>t.domain===e);let t=await l(e);if(!t)return null;d.push(t),m.add(t.domain);for(let e of t.registrations){let n=e.domain?e:{...e,domain:t.domain};g.has(n.tool.name)||g.set(n.tool.name,n)}f=[...g.values()],L();for(let e of t.registrations)h.add(e.tool.name);return t}async function b(){if(!d)throw Error(`[registry] Not initialised - call initRegistry() first.`);let t=o(),n=new Set(d.map(e=>e.domain)),r=[...t].filter(e=>!n.has(e));r.length!==0&&(e.info(`[registry] Loading ${r.length} remaining domains for full discovery`),await Promise.all(r.map(e=>y(e))))}function x(){if(!d)throw Error(`[registry] Not initialised - call initRegistry() first.`);return d}function S(){if(!f)throw Error(`[registry] Not initialised - call initRegistry() first.`);return f}function C(){return x()}function w(){return S()}function T(){if(!m)throw Error(`[registry] Not initialised - call initRegistry() first.`);return m}function E(){return o()}function D(){let e={};for(let t of S())(e[t.domain]??=[]).push(t.tool);return e}function O(){let e=new Map;for(let t of S())e.has(t.tool.name)||e.set(t.tool.name,t.domain);return e}function k(){return S().map(e=>e.tool)}function A(e,t){let n=t?S().filter(e=>t.has(e.tool.name)):[...S()],r=[];for(let t of n)try{r.push([t.tool.name,t.bind(e)])}catch{}return Object.fromEntries(r)}function j(){let t={search:new Set,workflow:new Set,full:new Set};for(let[e,r]of Object.entries(n))for(let n of r)t[n]?.add(e);let r={};for(let[e,n]of Object.entries(t))r[e]=[...n];return u(r.search,r.workflow)||e.warn(`[registry] Profile hierarchy: search not subset of workflow`),u(r.workflow,r.full)||e.warn(`[registry] Profile hierarchy: workflow not subset of full`),r}let M=null,N=null,P=null,F=null;function I(){return M||=D(),M}function L(){M=null}function R(){return N||=O(),N}function z(){return P||=j(),P}const B=new Proxy([],{get(e,t){F||=k();let n=F,r=n[t];return typeof r==`function`?r.bind(n):r}});function V(e){let t=new Map;for(let n of e)t.set(n.name,n);return Array.from(t.values())}function H(e){if(!e?.trim())return null;let t=T(),n=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean).filter(e=>t.has(e));return n.length>0?Array.from(new Set(n)):null}function U(e){return V(e.flatMap(e=>I()[e]??[]))}function W(e){let t=z()[e];if(!t)return[];let n=new Set(t);return V([...w()].filter(t=>!(!n.has(t.domain)||t.profiles&&!t.profiles.includes(e))).map(e=>e.tool))}function G(e){return R().get(e)??null}function K(e){return z()[e]??[]}export{W as a,b as c,E as d,C as f,s as h,U as i,y as l,v as m,K as n,H as o,w as p,G as r,A as s,B as t,T as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{ut as t}from"./constants-BYj8Xek8.mjs";import{t as n}from"./ToolProbe-C7ZU2x7M.mjs";const r=[{name:`wabt.wasm2wat`,command:`wasm2wat`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`wabt.wasm-objdump`,command:`wasm-objdump`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`wabt.wasm-decompile`,command:`wasm-decompile`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`wabt.wasm2c`,command:`wasm2c`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`binaryen.wasm-opt`,command:`wasm-opt`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`runtime.wasmtime`,command:`wasmtime`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`runtime.wasmer`,command:`wasmer`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`miniapp.unpacker`,command:`unveilr`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`platform.jadx`,command:`jadx`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.ast-grep`,command:`ast-grep`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.wakaru`,command:`wakaru`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.restringer`,command:`restringer`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`analysis.z3`,command:`z3`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`syscall.strace`,command:`strace`,versionArgs:[`--version`],required:!1,envAllowlist:[]},{name:`syscall.bpftrace`,command:`bpftrace`,versionArgs:[`--version`],required:!1,envAllowlist:[]}];var i=class{specs=new Map;probeCache=new Map;probeCacheExpiry=0;PROBE_CACHE_TTL=t;constructor(e){for(let e of r)this.specs.set(e.name,e);if(e)for(let t of e)this.specs.set(t.name,t)}getSpec(e){let t=this.specs.get(e);if(!t)throw Error(`Tool '${e}' is not registered in the allowlist`);return t}isRegistered(e){return this.specs.has(e)}getRegisteredTools(){return Array.from(this.specs.keys())}async probeAll(t=!1){let r=Date.now();if(!t&&this.probeCache.size>0&&r<this.probeCacheExpiry)return Object.fromEntries(this.probeCache);let i={},a=[];for(let[e,t]of this.specs)a.push(n(t.command,t.versionArgs).then(t=>{i[e]=t,this.probeCache.set(e,t)}));await Promise.all(a),this.probeCacheExpiry=r+this.PROBE_CACHE_TTL;let o=Object.values(i).filter(e=>e.available).length;return e.info(`[ToolRegistry] Probed ${this.specs.size} tools: ${o} available`),i}getCachedProbe(e){return this.probeCache.get(e)}register(t){this.specs.set(t.name,t),this.probeCache.delete(t.name),e.debug(`[ToolRegistry] Registered tool: ${t.name} -> ${t.command}`)}};export{i as t};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{Fn as e,In as t,Ln as n,Mn as r,Nn as i,Pn as a,Rn as o,jn as s,zn as c}from"./constants-BYj8Xek8.mjs";import{f as l,r as u,t as d}from"./ToolCatalog-CYdD9F5f.mjs";const f=/(browser|page|navigate|click|type|screenshot|scrape|network|request|response|api|traffic|hook|capture|intercept|monitor|浏览器|页面|导航|点击|输入|截图|爬取|网络|请求|响应|接口|流量|抓包|拦截|监控)/i,p=/(token budget|cache|artifact|extension|plugin|reload|doctor|cleanup|memory|profile|tool list|令牌预算|缓存|工件|扩展|插件|重载|环境诊断|清理|内存|配置)/i,m=/(stateless|deterministic|pure compute|offline|decode|encode|hex|base64|protobuf|msgpack|checksum|hash|payload|frame|packet|bytes?|bytecode|pcap|protocol|state machine|field inference|ast transform|crypto harness|无状态|确定性|纯算|离线|解码|编码|十六进制|校验和|载荷|字节|协议|报文|帧|字段推断|状态机|构包)/i;let h=null;const g=new Map;function _(){if(h)return h;let e=[];for(let t of l())t.workflowRule&&e.push({patterns:[...t.workflowRule.patterns],domain:t.domain,priority:t.workflowRule.priority,tools:[...t.workflowRule.tools],hint:t.workflowRule.hint});return h=[...e].toSorted((e,t)=>t.priority-e.priority),g.clear(),h}function v(e){let t=g.get(e);if(t!==void 0)return t;let n=[];for(let t of _())for(let r of t.patterns)if(r.test(e)){n.push(t);break}let r=n.length===0?null:n.toSorted((e,t)=>t.priority-e.priority)[0];if(g.size>=64){let e=g.keys().next().value;e!==void 0&&g.delete(e)}return g.set(e,r),r}function y(e,t){let n=null;for(let[r,i]of t.extensionWorkflowRuntimeById.entries()){let a=i.route??i.workflow.route;if(!a)continue;let o=t.extensionWorkflowsById.get(r),s=o?.displayName??i.workflow.displayName,c=o?.description??i.workflow.description??`Workflow route`;for(let t of a.triggerPatterns){if(!t.test(e))continue;let i=a.priority/100;(!n||i>n.confidence)&&(n={workflow:{id:r,name:s,description:c,route:a},confidence:i,matchedPattern:t.source});break}}return n}function b(e,t){return t?.domain!==`browser`&&t?.domain!==`network`&&S(e)?!1:t?.domain===`browser`||t?.domain===`network`||f.test(e)}function x(e){return p.test(e)}function S(e){return m.test(e)}function C(e,t){if(e.length<2)return null;let n=l();if(n.length===0)return null;let r=new Map,i=new Map;for(let e of n)if(e.toolDependencies)for(let a of e.toolDependencies){let e=new Set(T(a,n)),o=w(a.from,n),s=w(a.to,n);if(o&&s&&o!==s){let e=r.get(o)??new Set;e.add(s),r.set(o,e);let n=i.get(o)??new Set;n.add(a.from),t.has(a.to)&&n.add(a.to),i.set(o,n)}for(let t of e)if(t!==o&&o){let e=r.get(o)??new Set;e.add(t),r.set(o,e)}}let a=new Set;for(let t of e)t.domain&&a.add(t.domain);if(a.size<2)return null;let o=[...a];for(let e=0;e<o.length;e++)for(let i=e+1;i<o.length;i++){let a=o[e],s=o[i];if(!(r.get(a)?.has(s)||r.get(s)?.has(a)))continue;let c=new Set;for(let e of n)if(e.toolDependencies)for(let r of e.toolDependencies){let e=w(r.from,n),i=w(r.to,n);(e===a&&i===s||e===s&&i===a)&&(t.has(r.from)&&c.add(r.from),t.has(r.to)&&c.add(r.to))}let l=[...c];if(!(l.length<2))return{id:`dynamic-${a}-${s}`,hint:`${a} ↔ ${s} (declared dependency)`,domains:[a,s],tools:l.slice(0,5),priority:75}}return null}function w(e,t){for(let n of t)for(let t of n.registrations)if(t.tool.name===e)return t.domain??n.domain;return null}function T(e,t){return[w(e.from,t),w(e.to,t)].filter(e=>e!==null)}function E(e){let t=e.trim();if(!t.startsWith(`mcp__`))return t;let n=t.split(`__`);return n.length<3?t:n.slice(2).join(`__`)}function D(e){let t=e.names;if(typeof t==`string`&&t.trim().startsWith(`[`))try{let e=JSON.parse(t);Array.isArray(e)&&(t=e)}catch{}if(!Array.isArray(t))return{names:[],error:`names must be an array`};let n=[];for(let e of t){if(typeof e!=`string`||e.trim().length===0)return{names:[],error:`invalid tool name: expected non-empty string`};n.push(E(e))}return{names:n}}let O=null;function k(){return O||=new Map(d.map(e=>[e.name,e])),O}function A(e,t){let n=E(e),r=k().get(n);if(r)return r.inputSchema;let i=t.extensionToolsByName.get(n);if(i)return i.tool.inputSchema;let a=t.metaToolsByName.get(n);if(a)return a.inputSchema}function j(e,t){let n=E(e),r=k().get(n);if(r?.description)return r.description.split(`
|
|
2
|
-
`)[0]||`No description available`;let i=t.extensionToolsByName.get(n);if(i?.tool?.description)return i.tool.description.split(`
|
|
3
|
-
`)[0]||`No description available`;let a=t.metaToolsByName.get(n);return a?.description&&a.description.split(`
|
|
4
|
-
`)[0]||`No description available`}function M(e,t){let n=E(e);return new Set([...t.selectedTools.map(e=>e.name),...t.activatedToolNames]).has(n)}function N(e){return new Set([...d.map(e=>e.name),...e.extensionToolsByName.keys()])}function P(e,t){return u(e)??t.extensionToolsByName.get(e)?.domain??null}async function F(e){if(!e.pageController||typeof e.pageController.getPage!=`function`)return!1;try{return!!await e.pageController.getPage()}catch{return!1}}function I(e){if(!e.consoleMonitor)return!1;try{if(typeof e.consoleMonitor.getNetworkStatus==`function`)return!!e.consoleMonitor.getNetworkStatus().enabled;if(typeof e.consoleMonitor.isNetworkEnabled==`function`)return!!e.consoleMonitor.isNetworkEnabled()}catch{}return!1}function L(e){if(!e.consoleMonitor||typeof e.consoleMonitor.getNetworkRequests!=`function`)return 0;try{let t=e.consoleMonitor.getNetworkRequests({limit:1});return Array.isArray(t)?t.length:0}catch{try{let t=e.consoleMonitor.getNetworkRequests();return Array.isArray(t)?t.length:0}catch{return 0}}}async function R(e){return{hasActivePage:await F(e),networkEnabled:I(e),capturedRequestCount:L(e)}}function z(e,t){if(!S(e))return[];let n=[],r=(e,r)=>{t.has(e)&&!n.some(t=>t.name===e)&&n.push({name:e,description:r})};return r(`binary_detect_format`,`Detect the payload encoding or container before decoding`),r(`binary_decode`,`Decode the payload into deterministic offline bytes or structured output`),r(`proto_auto_detect`,`Infer a likely protocol layout from repeated payload samples`),r(`proto_infer_fields`,`Derive stable field boundaries and candidate semantics`),r(`proto_infer_state_machine`,`Infer request/response state transitions from repeated samples`),r(`crypto_test_harness`,`Validate extracted signing or crypto logic with deterministic test vectors`),r(`crypto_compare`,`Compare competing crypto implementations against the same vectors`),r(`network_get_requests`,`Collect request or response samples only if payload bytes still need to be extracted`),n}function B(e){return e.includes(`Browser must be launched`)?e=>e.hasActivePage:e.includes(`Network monitoring must be enabled`)?e=>e.networkEnabled:e.includes(`Debugger must be enabled`)||e.includes(`Debugger must be attached`)||e.includes(`Page must be navigated`)||e.includes(`WebSocket monitoring`)?e=>e.hasActivePage:()=>!1}let V=null;function H(){if(V)return V;let e={};for(let t of l())if(t.prerequisites)for(let[n,r]of Object.entries(t.prerequisites))e[n]=r.map(e=>({condition:e.condition,check:B(e.condition),fix:e.fix}));return V=e,V}function U(e,t,n){let r=[],i=e=>{n.has(e)&&!r.includes(e)&&r.push(e)};(e.domain===`browser`||e.domain===`network`)&&!t.hasActivePage&&(i(`browser_launch`),i(`browser_attach`)),e.domain===`network`&&(t.hasActivePage&&!t.networkEnabled&&i(`network_monitor`),t.hasActivePage&&t.networkEnabled&&t.capturedRequestCount>0&&i(`network_get_requests`));for(let t of e.tools)i(t);return e.domain===`network`&&t.hasActivePage&&t.networkEnabled&&i(`network_get_requests`),r}function W(e,t,n){let r=[],i=new Set,a=e.workflow.route.requiredDomains.includes(`browser`)||e.workflow.route.requiredDomains.includes(`network`),o=(e,t)=>{!n.has(e)||i.has(e)||(i.add(e),r.push({name:e,description:t}))};!t.hasActivePage&&a&&(o(`browser_launch`,`Launch a browser session before executing the preset`),o(`browser_attach`,`Attach preset tooling to the active browser session before capture begins`));for(let t of e.workflow.route.steps)o(t.toolName,t.description);return r}function G(e,t,n,r){return W(e,t,r).map((t,r)=>({name:t.name,domain:P(t.name,n),shortDescription:t.description,score:e.workflow.route.priority+e.confidence-r*.01,isActive:M(t.name,n)}))}function K(e,t,n){return z(e,n).map((e,n)=>({name:e.name,domain:P(e.name,t),shortDescription:e.description,score:90-n*.01,isActive:M(e.name,t)}))}function q(e,t){return{name:`run_extension_workflow`,domain:P(`run_extension_workflow`,t),shortDescription:`Execute routed workflow ${e.workflow.name} (${e.workflow.id}) via run_extension_workflow`,score:e.workflow.route.priority+e.confidence,isActive:M(`run_extension_workflow`,t)}}function J(e,t){return{kind:e.workflow.route.kind,id:e.workflow.id,name:e.workflow.name,description:e.workflow.description,confidence:e.confidence,matchedPattern:e.matchedPattern,requiredDomains:[...e.workflow.route.requiredDomains],steps:e.workflow.route.steps.map(e=>({id:e.id,toolName:e.toolName,domain:u(e.toolName)??t.extensionToolsByName.get(e.toolName)?.domain??null,description:e.description,prerequisites:[...e.prerequisites],parallel:e.parallel,isActive:M(e.toolName,t)}))}}function Y(l,u,d,f){let p=b(u,d),m=x(u),h=S(u),g=l.map(l=>{let u=l.score;return p&&!m&&l.domain===`maintenance`&&(u*=i),h&&((l.domain===`browser`||l.domain===`network`||l.domain===`debugger`||l.domain===`hooks`||l.domain===`maintenance`)&&(u*=o),(l.domain===`core`||l.domain===`streaming`||l.domain===`workflow`)&&(u*=n),(l.domain===`encoding`||l.domain===`transform`||l.domain===`protocol-analysis`||l.domain===`sourcemap`||l.domain===`core`)&&(u*=t),(l.name===`binary_detect_format`||l.name===`binary_decode`||l.name===`crypto_test_harness`||l.name===`ast_transform_apply`||l.name===`proto_auto_detect`||l.name===`proto_infer_fields`||l.name===`proto_infer_state_machine`||l.name===`proto_fingerprint`)&&(u*=c)),p&&(!f.hasActivePage&&l.name===`browser_launch`&&(u*=r),!f.hasActivePage&&l.name===`browser_attach`&&(u*=s),f.hasActivePage&&!f.networkEnabled&&l.name===`network_monitor`&&(u*=e),f.hasActivePage&&f.networkEnabled&&f.capturedRequestCount>0&&l.name===`network_get_requests`&&(u*=a)),{...l,score:u}});return g.sort((e,t)=>t.score-e.score),g}export{v as _,U as a,S as b,N as c,P as d,A as f,C as g,D as h,q as i,R as l,E as m,J as n,H as o,M as p,K as r,Y as s,G as t,j as u,b as v,y as x,x as y};
|
|
@@ -1,272 +0,0 @@
|
|
|
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};
|
|
@@ -1,9 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1,6 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{a as t,n}from"./parse-args-Bw413PlW.mjs";import{n as r}from"./ResponseBuilder-BfWP-uaT.mjs";import"./definitions-Tls8c0A0.mjs";import{createHash as i}from"node:crypto";import{basename as a,join as o}from"node:path";import{open as s,readdir as c,stat as l}from"node:fs/promises";import{open as u}from"yauzl";const d=Object.freeze([]),f=(e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=parseInt(n,10);return Number.isFinite(r)?r:t},p=f(`APK_PACKER_MAX_APK_BYTES`,512*1024*1024),m=f(`APK_PACKER_MAX_ZIP_ENTRIES`,2e5),h=f(`APK_PACKER_MAX_REGEX_PATTERN_LENGTH`,256),g=f(`APK_PACKER_REGEX_TIMEOUT_MS`,50),_=f(`APK_SIGBLOCK_EOCD_SCAN_BYTES`,65536),v=f(`APK_SIGBLOCK_MAX_BYTES`,1024*1024),y=f(`APK_SIGBLOCK_DEX_PREFIX_HEAD_BYTES`,4),b=Object.freeze([/\([^()]*[+*][^()]*\)[+*]/,/\([^()]*\|[^()]*\)[+*][^()]*[+*]/]);function x(t,n){return new e(`VALIDATION`,t,{details:n})}function S(e){return/[\^$*+?()[\]{}|]/.test(e)}function C(e){if(!e.name||e.name.length===0)throw x(`customSignature.name must be a non-empty string`);if(e.category!==void 0&&typeof e.category!=`string`)throw x(`customSignature.category, when present, must be a string`,{name:e.name});if(!Array.isArray(e.libPatterns)||e.libPatterns.length===0)throw x(`customSignature.libPatterns must be a non-empty array`,{name:e.name});let t=[];for(let n=0;n<e.libPatterns.length;n++){let r=e.libPatterns[n];if(typeof r!=`string`||r.length===0)throw x(`customSignature.libPatterns[${n}] must be a non-empty string`,{name:e.name});if(r.length>h)throw x(`customSignature.libPatterns[${n}] exceeds APK_PACKER_MAX_REGEX_PATTERN_LENGTH (${h})`,{name:e.name,length:r.length});S(r)?(w(r,e.name),t.push(T(r,`i`,e.name))):t.push(r.toLowerCase())}return{name:e.name,libPatterns:t,...e.category?{category:e.category}:{},...e.confidence?{confidence:e.confidence}:{},...e.notes?{notes:e.notes}:{}}}function w(e,t){for(let n of b)if(n.test(e))throw x(`customSignature pattern rejected as potentially catastrophic (ReDoS heuristic match)`,{name:t,pattern:e})}function T(t,n,r){try{return new RegExp(t,n)}catch(i){throw new e(`VALIDATION`,`customSignature regex failed to compile: ${i.message}`,{details:{name:r,pattern:t,flags:n},cause:i})}}function E(e,t,n){return n===`replace`?Object.freeze([...t??[]]):!t||t.length===0?Object.freeze([...e]):Object.freeze(n===`prepend`?[...t,...e]:[...e,...t])}function D(t,n,r=g,i){let a=performance.now(),o=t.test(n),s=performance.now()-a;if(s>r)throw new e(`TIMEOUT`,`Regex match exceeded APK_PACKER_REGEX_TIMEOUT_MS (${r} ms): ${s.toFixed(2)} ms`,{details:{signatureName:i,pattern:t.source,flags:t.flags,elapsedMs:s,timeoutMs:r}});return o}const O=/^lib\/[^/]+\/(lib[^/]+\.so)$/i;var k=class{defaults;constructor(e=d){this.defaults=e}async detectFromApk(t,n={}){if(!t||t.length===0)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);let r;try{r=await l(t)}catch(n){throw new e(`NOT_FOUND`,`APK not found: ${t}`,{details:{apkPath:t},cause:n})}if(!r.isFile())throw new e(`VALIDATION`,`APK path is not a regular file: ${t}`,{details:{apkPath:t}});if(r.size>p)throw new e(`VALIDATION`,`APK exceeds APK_PACKER_MAX_APK_BYTES (${p} bytes): ${r.size}`,{details:{apkPath:t,size:r.size,max:p}});let i=await M(t);return this.matchBasenames(i,n)}async detectFromDir(t,n={}){if(!t||t.length===0)throw new e(`VALIDATION`,`dirPath must be a non-empty string`);let r;try{r=await l(t)}catch(n){throw new e(`NOT_FOUND`,`Directory not found: ${t}`,{details:{dirPath:t},cause:n})}if(!r.isDirectory())throw new e(`VALIDATION`,`Path is not a directory: ${t}`,{details:{dirPath:t}});let i=await N(t);return this.matchBasenames(i,n)}matchBasenames(e,t={}){let n=E(this.defaults,t.customSignatures,t.ruleMode??`append`),r=[];for(let t of n){let n=new Set;for(let r of e)A(r,t)&&n.add(r.path);if(n.size===0)continue;let i=t.confidence??`medium`,a=n.size>=2?`high`:i;r.push({name:t.name,...t.category?{category:t.category}:{},matchedLibs:[...n].toSorted(),confidence:a})}let i=r.length;return{packers:r,confidence:j(r),layerCount:i}}};function A(e,t){for(let n of t.libPatterns)if(typeof n==`string`){if(e.basename===n)return!0}else if(D(n,e.basename,g,t.name))return!0;return!1}function j(e){if(e.length===0)return 0;let t=.5;return e.some(e=>e.confidence===`high`)&&(t+=.25),e.length>=2&&(t+=.25),Math.min(t,1)}async function M(t){return new Promise((n,r)=>{u(t,{lazyEntries:!0,autoClose:!0},(i,a)=>{if(i||!a){r(new e(`VALIDATION`,`Failed to open APK as ZIP: ${i?.message??`unknown`}`,{details:{apkPath:t},cause:i??void 0}));return}let o=[],s=0,c=a,l=n=>{if(s+=1,s>m){c.close(),r(new e(`VALIDATION`,`APK has too many ZIP entries (> ${m})`,{details:{apkPath:t}}));return}let i=n.fileName,a=O.exec(i);if(a){let e=a[1].toLowerCase();o.push({path:i.toLowerCase(),basename:e})}c.readEntry()},u=()=>{f(),n(o)},d=n=>{f(),c.close(),r(new e(`RUNTIME`,`ZIP read failed: ${n.message}`,{details:{apkPath:t},cause:n}))};function f(){c.removeListener(`entry`,l),c.removeListener(`end`,u),c.removeListener(`error`,d)}c.on(`entry`,l),c.on(`end`,u),c.on(`error`,d),c.readEntry()})})}async function N(e){let t=o(e,`lib`),n;try{n=await c(t)}catch{return[]}let r=[];for(let e of n){let n=o(t,e),i;try{if(!(await l(n)).isDirectory())continue;i=await c(n)}catch{continue}for(let t of i){if(!t.toLowerCase().endsWith(`.so`))continue;let n=`lib/${e}/${t}`.toLowerCase();r.push({path:n,basename:a(t).toLowerCase()})}}return r}const P=`APK Sig Block 42`,F=Buffer.from(P,`utf8`);var I=class{async parse(t){if(!t||typeof t!=`string`)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);let n;try{n=await l(t)}catch(n){throw new e(`NOT_FOUND`,`APK not found: ${t}`,{details:{apkPath:t},cause:n})}if(!n.isFile())throw new e(`VALIDATION`,`Path is not a regular file: ${t}`,{details:{apkPath:t}});if(n.size>p)throw new e(`VALIDATION`,`APK exceeds APK_PACKER_MAX_APK_BYTES (${p} bytes): ${n.size}`,{details:{apkPath:t,size:n.size,max:p}});let r;try{return r=await s(t,`r`),await this.parseHandle(r,t,n.size)}finally{r&&await r.close()}}async parseHandle(e,t,n){let r={schemes:{},unknownBlocks:[],warnings:[],anomalies:[]},i=Math.min(_,n),a=Buffer.alloc(i);await e.read(a,0,i,n-i);let o=R(a);if(o<0)return r.anomalies.push({kind:`eocd-not-found`,evidence:`Scanned trailing ${i} bytes — no EOCD signature 0x06054b50`}),L(t,n,r,!1);let s=a.readUInt32LE(o+16);if(s>=n-i+o||s<24)return r.warnings.push(`Implausible centralDirOffset ${s} given file size ${n}`),L(t,n,r,!1);let c=Buffer.alloc(24);if(await e.read(c,0,24,s-24),!c.subarray(8).equals(F)){let i=Math.min(s,_),a=Buffer.alloc(i);await e.read(a,0,i,s-i);let o=a.indexOf(F);if(o<0)return L(t,n,r,!1);let c=i-(o+F.length);return r.anomalies.push({kind:`magic-offset`,evidence:`APK Sig Block 42 magic located ${c} bytes before expected position`}),L(t,n,r,!1)}let l;try{l=J(c,0)}catch(e){return r.warnings.push(`Signing block size field unreadable: ${e.message}`),L(t,n,r,!1)}if(l<=0||l>v)return r.warnings.push(`Signing block size ${l} outside [1, ${v}] — refusing to read`),L(t,n,r,!1);let u=s-l-8;if(u<0)return r.warnings.push(`Computed signing block start offset is negative — refusing to read`),L(t,n,r,!1);let d=l+8;if(d>v)return r.warnings.push(`Signing block total length ${d} exceeds APK_SIGBLOCK_MAX_BYTES — refusing to read`),L(t,n,r,!1);let f=Buffer.alloc(Number(d));if(await e.read(f,0,Number(d),u),z(f,r),n>=4){let t=Math.min(y,n),i=Buffer.alloc(t);await e.read(i,0,t,0),i.length>=4&&i.readUInt32BE(0)===1684371466&&r.anomalies.push({kind:`dex-prefix-anomaly`,evidence:`DEX magic (0x6465780a) at file head with a valid Signing Block — possible dex-prefix injection pattern`})}return L(t,n,r,!0,{magic:P,size:Number(d),offset:u})}};function L(e,t,n,r,i){return{apkPath:e,fileSize:t,signingBlock:r&&i?{found:!0,magic:i.magic,size:i.size,offset:i.offset}:{found:!1},schemes:n.schemes,unknownBlocks:n.unknownBlocks,warnings:n.warnings,anomalies:n.anomalies}}function R(e){if(e.length<22)return-1;for(let t=e.length-22;t>=0;t--)if(e.readUInt32LE(t)===101010256){let n=e.readUInt16LE(t+20);if(t+22+n===e.length)return t}return-1}function z(e,t){let n=e.length-24,r=8;for(;r+12<=n;){let i=J(e,r);if(i<4||r+8+i>n){t.warnings.push(`Truncated ID-value pair at offset ${r} (pairSize ${i})`);return}let a=e.readUInt32LE(r+8),o=r+12,s=r+8+i;B(a,e.subarray(o,s),t),r=s}}function B(e,t,n){switch(e){case 1896449818:{let e=V(t,!1,n);n.schemes.v2?(n.anomalies.push({kind:`duplicate-scheme`,evidence:`v2 signers block (0x7109871a) appears more than once`}),n.schemes.v2.signers.push(...e)):n.schemes.v2={signers:e};return}case 4031998144:{let e=V(t,!0,n),r=U(e);n.schemes.v3=r?{signers:e,keyRotation:r}:{signers:e};return}case 462663009:{let e=V(t,!0,n);n.schemes.v3_1={signers:e};return}case 1114793335:{let e=W(t);e&&(n.schemes.v4=e);return}case 1347109971:return;case 1111638594:n.unknownBlocks.push({id:q(e),size:t.length}),n.anomalies.push({kind:`extra-block-anomaly`,evidence:`Block ID 0x42424242 present (size=${t.length}) — non-standard residue marker`}),n.warnings.push(`Unknown block 0x42424242 detected — non-standard block ID observed in some legacy tooling. Manual review recommended.`);return;default:n.unknownBlocks.push({id:q(e),size:t.length}),n.anomalies.push({kind:`extra-block`,evidence:`Unknown block id ${q(e)} size=${t.length}`});return}}function V(e,t,n){let r=new Y(e,`signers`),i=r.readU32();if(i===0)return[];let a=r.readSlice(i,`signersBuf`),o=[],s=new Y(a,`signers-inner`);for(;s.remaining()>0;){let e=s.readU32(),r=s.readSlice(e,`signer`);try{o.push(H(r,t))}catch(e){n.warnings.push(`Skipped malformed signer: ${e.message}`)}}return o}function H(e,t){let n=new Y(e,`signer`),r=n.readU32(),i=n.readSlice(r,`signedData`),a=0,o=0;t&&(a=n.readU32(),o=n.readU32());let s=n.readU32(),c=n.readSlice(s,`signatures`),l=[],u=new Y(c,`signatures-inner`);for(;u.remaining()>0;){let e=u.readU32(),t=u.readSlice(e,`signature`);if(t.length<4)continue;let n=t.readUInt32LE(0);l.push({algorithm:K(n),algorithmId:n})}let d=new Y(i,`signedData`),f=d.readU32(),p=d.readSlice(f,`digests`),m=[],h=new Y(p,`digests-inner`);for(;h.remaining()>0;){let e=h.readU32(),t=h.readSlice(e,`digest`);if(t.length<4)continue;let n=t.readUInt32LE(0);m.push({algorithm:K(n),algorithmId:n})}let g=d.readU32(),_=d.readSlice(g,`certificates`),v=[],y=new Y(_,`certs-inner`);for(;y.remaining()>0;){let e=y.readU32(),t=y.readSlice(e,`certificate`);v.push(G(t))}let b=d.readU32(),x=d.readSlice(b,`attributes`),S=[],C=new Y(x,`attrs-inner`);for(;C.remaining()>0;){let e=C.readU32(),t=C.readSlice(e,`attribute`);if(t.length<4)continue;let n=t.readUInt32LE(0);S.push({id:q(n),size:t.length})}let w={digests:m,signatures:l,certificates:v,additionalAttributes:S};return t?{...w,minSdkVersion:a,maxSdkVersion:o}:w}function U(e){for(let t of e)for(let e of t.additionalAttributes)if(e.id===q(1000370060))return{levels:[]}}function W(e){try{let t=new Y(e,`v4`),n=t.readU32(),r=t.readU32(),i=t.readSlice(r,`v4-hash`),a=0;return t.remaining()>=8?a=J(e,t.position()):t.remaining()>=4&&(a=t.readU32()),{algorithm:K(n),rootHash:i.toString(`hex`),treeSize:a}}catch{return}}function G(e){let t=i(`sha256`).update(e).digest(`hex`),n=e.subarray(0,Math.min(32,e.length)).toString(`hex`);return{sha256Fingerprint:t,derLength:e.length,derPreview:n}}function K(e){switch(e){case 257:return`RSA_PSS_SHA256`;case 258:return`RSA_PSS_SHA512`;case 259:return`RSA_PKCS1_V1_5_SHA256`;case 260:return`RSA_PKCS1_V1_5_SHA512`;case 513:return`ECDSA_SHA256`;case 514:return`ECDSA_SHA512`;case 769:return`DSA_SHA256`;case 1057:return`VERITY_RSA_PKCS1_V1_5_SHA256`;case 1059:return`VERITY_ECDSA_SHA256`;case 1061:return`VERITY_DSA_SHA256`;default:return`UNKNOWN`}}function q(e){return`0x${(e>>>0).toString(16).padStart(8,`0`)}`}function J(t,n){let r=t.readUInt32LE(n),i=t.readUInt32LE(n+4);if(i>2097151)throw new e(`VALIDATION`,`u64 length exceeds Number.MAX_SAFE_INTEGER at offset ${n}`);return i*4294967296+r}var Y=class{buf;label;cursor=0;constructor(e,t){this.buf=e,this.label=t}position(){return this.cursor}remaining(){return this.buf.length-this.cursor}readU32(){if(this.remaining()<4)throw new e(`VALIDATION`,`Underflow reading u32 in ${this.label}`);let t=this.buf.readUInt32LE(this.cursor);return this.cursor+=4,t}readSlice(t,n){if(t<0||t>this.remaining())throw new e(`VALIDATION`,`Underflow reading slice "${n}" (need ${t}, have ${this.remaining()}) in ${this.label}`);let r=this.buf.subarray(this.cursor,this.cursor+t);return this.cursor+=t,r}};const X=new Set([`append`,`prepend`,`replace`]),Z=new Set([`high`,`medium`,`low`]);function Q(t){if(t!=null){if(!Array.isArray(t))throw new e(`VALIDATION`,`customSignatures must be an array of signature objects`);return t.map((t,n)=>{if(typeof t!=`object`||!t||Array.isArray(t))throw new e(`VALIDATION`,`customSignatures[${n}] must be an object`);let{name:r,category:i,libPatterns:a,confidence:o,notes:s}=t;if(typeof r!=`string`)throw new e(`VALIDATION`,`customSignatures[${n}].name must be a string`);if(i!==void 0&&typeof i!=`string`)throw new e(`VALIDATION`,`customSignatures[${n}].category, when present, must be a string`);if(!Array.isArray(a))throw new e(`VALIDATION`,`customSignatures[${n}].libPatterns must be a string array`);for(let t=0;t<a.length;t++)if(typeof a[t]!=`string`)throw new e(`VALIDATION`,`customSignatures[${n}].libPatterns[${t}] must be a string`);let c={name:r,libPatterns:a};if(typeof i==`string`&&(c.category=i),typeof o==`string`){if(!Z.has(o))throw new e(`VALIDATION`,`customSignatures[${n}].confidence must be one of: high, medium, low`);c.confidence=o}return typeof s==`string`&&(c.notes=s),C(c)})}}function $(e){return{name:e.name,...e.category?{category:e.category}:{},libPatterns:e.libPatterns.map(e=>typeof e==`string`?{type:`literal`,value:e}:{type:`regex`,value:e.source}),...e.category?{category:e.category}:{},...e.confidence?{confidence:e.confidence}:{},...e.notes?{notes:e.notes}:{}}}var ee=class{detector;signingBlockParser;constructor(e=new k,t=new I){this.detector=e,this.signingBlockParser=t}handleApkPackerDetect(i){return r(async()=>{let r=t(i,`apkPath`),a=t(i,`dirPath`);if(!r&&!a)throw new e(`VALIDATION`,`Either apkPath or dirPath must be provided`);if(r&&a)throw new e(`VALIDATION`,`Provide only one of apkPath or dirPath, not both`);let o=Q(i.customSignatures),s=n(i,`ruleMode`,X),c={...o===void 0?{}:{customSignatures:o},...s===void 0?{}:{ruleMode:s}},l=r?await this.detector.detectFromApk(r,c):await this.detector.detectFromDir(a,c);return{packers:l.packers,confidence:l.confidence,layerCount:l.layerCount}})}handleApkPackerListSignatures(e){return r(async()=>{let n=t(e,`category`);return{signatures:(n?d.filter(e=>(e.category??``).toLowerCase().includes(n.toLowerCase())):d).map($)}})}handleApkSigningBlockParse(n){return r(async()=>{let r=t(n,`apkPath`);if(!r)throw new e(`VALIDATION`,`apkPath must be a non-empty string`);return{report:await this.signingBlockParser.parse(r)}})}};export{ee as ApkPackerHandlers};
|