@jshookmcp/jshook 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -661
- package/README.md +32 -49
- package/README.zh.md +32 -47
- package/dist/AntiCheatDetector-B6d4Qe9D.mjs +1 -0
- package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
- package/dist/CacheAdapters-CsNtQIR8.mjs +1 -0
- package/dist/CodeInjector-Cll_7bLJ.mjs +1 -0
- package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
- package/dist/DOMInspector-C19J4zeq.mjs +95 -0
- package/dist/DarwinAPI-ZfQdpLNI.mjs +1 -0
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
- package/dist/EventBus-DL8iLA09.mjs +1 -0
- package/dist/EvidenceGraphBridge-BtbwXsLC.mjs +1 -0
- package/dist/ExtensionManager-BD724zkO.mjs +1 -0
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
- package/dist/FingerprintManager-DT0EAUEo.mjs +1 -0
- package/dist/HardwareBreakpoint-BUfPdp0f.mjs +1 -0
- package/dist/HeapAnalyzer-B_aqY8oj.mjs +1 -0
- package/dist/{HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +66 -101
- package/dist/InstrumentationSession-D_G1ZPyd.mjs +1 -0
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
- package/dist/MemoryController-X1XNSn1n.mjs +2 -0
- package/dist/MemoryScanSession-DG_F-PjE.mjs +1 -0
- package/dist/MemoryScanner-g1_L1ub5.mjs +1 -0
- package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +1 -0
- package/dist/NativeMemoryManager.utils-BHy1P_jM.mjs +1 -0
- package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
- package/dist/PEAnalyzer-yWQaGrcx.mjs +1 -0
- package/dist/PageController-Dfsm1_o7.mjs +1 -0
- package/dist/PointerChainEngine-BhCUkmxY.mjs +1 -0
- package/dist/PrerequisiteError-BjCQA-gK.mjs +1 -0
- package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
- package/dist/ResponseBuilder-BfWP-uaT.mjs +1 -0
- package/dist/ReverseEvidenceGraph-BhSYYdiI.mjs +2 -0
- package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
- package/dist/ScriptManager-LWGPTdvD.mjs +7 -0
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
- package/dist/Speedhack-yseDPSZ9.mjs +1 -0
- package/dist/StealthVerifier-BmcxfwSF.mjs +1 -0
- package/dist/StructureAnalyzer-C5lpuZkg.mjs +2 -0
- package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
- package/dist/ToolError-DWU_z7gp.mjs +1 -0
- package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
- package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
- package/dist/ToolRouter.policy-CfhJczkt.mjs +4 -0
- package/dist/TraceRecorder-BiJWBXHX.mjs +272 -0
- package/dist/VersionDetector-CHT36Az0.mjs +9 -0
- package/dist/Win32API-eUCF57l_.mjs +1 -0
- package/dist/Win32Debug-CYrIQBvr.mjs +1 -0
- package/dist/WorkflowEngine-D876meOO.mjs +1 -0
- package/dist/analysis-D4swdMvq.mjs +6 -0
- package/dist/{antidebug-BRKeyt27.mjs → antidebug-7L3ygj_9.mjs} +8 -259
- package/dist/apk-packer-BqXcInnX.mjs +1 -0
- package/dist/artifactRetention-BCPQASm7.mjs +1 -0
- package/dist/artifacts-CkodUM4j.mjs +1 -0
- package/dist/authorization-schema-BOFwSXUN.mjs +1 -0
- package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
- package/dist/binary-instrument-DU7V6TUM.mjs +7 -0
- package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
- package/dist/bind-helpers-m2U8glkF.mjs +1 -0
- package/dist/boringssl-inspector-BBaJwwkU.mjs +2 -0
- package/dist/browser-Qqco2rOT.mjs +11 -0
- package/dist/capabilities-CyXuKUl1.mjs +1 -0
- package/dist/chunk-C_pMuVsO.mjs +1 -0
- package/dist/collector-Bpl6qy2L.mjs +1 -0
- package/dist/concurrency-DCr8WQ2M.mjs +1 -0
- package/dist/constants-BYj8Xek8.mjs +1 -0
- package/dist/coordination-CWXW1o8K.mjs +1 -0
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/debugger-DyALjYMk.mjs +1 -0
- package/dist/definitions-BWxBke3r.mjs +1 -0
- package/dist/definitions-BYwATKc-.mjs +1 -0
- package/dist/definitions-B_83XfNQ.mjs +1 -0
- package/dist/definitions-Bf3H1EwV.mjs +1 -0
- package/dist/definitions-BftdXgXI.mjs +1 -0
- package/dist/definitions-Bio5XJYy.mjs +1 -0
- package/dist/definitions-C3qNgSn1.mjs +1 -0
- package/dist/definitions-CB6vmOer.mjs +1 -0
- package/dist/definitions-CMZRSy3k.mjs +1 -0
- package/dist/definitions-CQd7yCQH.mjs +1 -0
- package/dist/definitions-CT8ln6GQ.mjs +1 -0
- package/dist/definitions-Cenu6mxo.mjs +1 -0
- package/dist/definitions-D4g-MS10.mjs +1 -0
- package/dist/definitions-D5wl_8HN.mjs +1 -0
- package/dist/definitions-DAQm1Xar.mjs +1 -0
- package/dist/definitions-DP1vgxEY.mjs +1 -0
- package/dist/definitions-DxFNRQNK2.mjs +1 -0
- package/dist/definitions-Ibci7e_L.mjs +1 -0
- package/dist/definitions-OeLvmlQy.mjs +1 -0
- package/dist/definitions-RZYGD_Ey.mjs +1 -0
- package/dist/definitions-Tls8c0A0.mjs +1 -0
- package/dist/definitions-bybDvnG0.mjs +26 -0
- package/dist/definitions-l7TjdE6V.mjs +1 -0
- package/dist/encoding-ycOaz8Vr.mjs +2 -0
- package/dist/ensure-browser-core-DxWC-NTp.mjs +1 -0
- package/dist/evidence-graph-bridge-CV_UdYqj.mjs +1 -0
- package/dist/factory-CKr4fAE1.mjs +1 -0
- package/dist/flat-target-session-DvcQX7J5.mjs +1 -0
- package/dist/formatAddress-vLA_hOJt.mjs +1 -0
- package/dist/graphql-B2TiPEow.mjs +62 -0
- package/dist/handlers-0yKLRIfo.mjs +2 -0
- package/dist/handlers-8zN_vBIz.mjs +1 -0
- package/dist/handlers-B62K4FTc.mjs +1 -0
- package/dist/handlers-BpDlVVVU.mjs +1 -0
- package/dist/handlers-CMJK7m1c.mjs +31 -0
- package/dist/handlers-D2ZOul9p.mjs +54 -0
- package/dist/handlers-D5E40ssn.mjs +5 -0
- package/dist/handlers-DGbdQAgD.mjs +4 -0
- package/dist/handlers-DHO3rjsW.mjs +1 -0
- package/dist/handlers-FJ80VzUI.mjs +2 -0
- package/dist/handlers-VHWrxbM_.mjs +1 -0
- package/dist/handlers-l8QIKqBj.mjs +2 -0
- package/dist/handlers-mPFiNPe8.mjs +302 -0
- package/dist/{handlers-Dz9PYsCa.mjs → handlers-yo_xYzT8.mjs} +118 -904
- package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
- package/dist/hooks-D4XLfgtV.mjs +600 -0
- package/dist/index.mjs +13 -5240
- package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
- package/dist/logger-sBC6IdRT.mjs +1 -0
- package/dist/maintenance-BUpIukhg.mjs +1 -0
- package/dist/manifest-0Jpt_AQa.mjs +1 -0
- package/dist/manifest-B3fZbSWR.mjs +1 -0
- package/dist/manifest-B7NB2rh2.mjs +1 -0
- package/dist/manifest-BDi4nbH1.mjs +1 -0
- package/dist/manifest-BLDfkE7n.mjs +1 -0
- package/dist/manifest-BcXbB4gf.mjs +1 -0
- package/dist/manifest-Bdnc_vrc.mjs +1 -0
- package/dist/manifest-BuYKgCnp.mjs +1 -0
- package/dist/manifest-CBfNnGPV.mjs +1 -0
- package/dist/manifest-CPS1Xv69.mjs +1 -0
- package/dist/manifest-CQH9FhwI.mjs +1 -0
- package/dist/manifest-CRryuZF4.mjs +1 -0
- package/dist/manifest-CctIumog.mjs +1 -0
- package/dist/manifest-CvTe5ZGV2.mjs +1 -0
- package/dist/manifest-D-5GH0DV.mjs +1 -0
- package/dist/manifest-D3Ssf3IC.mjs +1 -0
- package/dist/manifest-D5ck3NvC.mjs +1 -0
- package/dist/manifest-D9jUUJAu.mjs +1 -0
- package/dist/manifest-DCx6w2XV.mjs +1 -0
- package/dist/manifest-DG19q-Ld.mjs +1 -0
- package/dist/manifest-DLMlD0Zc.mjs +1 -0
- package/dist/manifest-DYpn8w_h.mjs +1 -0
- package/dist/manifest-DYzWI8Xs.mjs +1 -0
- package/dist/manifest-D_obs5F4.mjs +1 -0
- package/dist/manifest-DujQqEQR.mjs +2 -0
- package/dist/manifest-DwL2ik8P.mjs +1 -0
- package/dist/manifest-ItF5P8A12.mjs +1 -0
- package/dist/manifest-KZphqIyX.mjs +1 -0
- package/dist/manifest-LG42zPLY2.mjs +1 -0
- package/dist/manifest-LLdI5m4T.mjs +1 -0
- package/dist/manifest-QYbQXJn0.mjs +1 -0
- package/dist/manifest-RcpX_MyZ.mjs +123 -0
- package/dist/manifest-YgVd8Sgz.mjs +1 -0
- package/dist/manifest-Zy7Odg5J.mjs +1 -0
- package/dist/manifest-ff1H7Pdp.mjs +1 -0
- package/dist/manifest-iuhF6pTL2.mjs +1 -0
- package/dist/manifest-nXHmtMSp2.mjs +1 -0
- package/dist/manifest-xWfu6iLo.mjs +1 -0
- package/dist/manifest-yC16OhL2.mjs +1 -0
- package/dist/manifest-ztWJoXy4.mjs +1 -0
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +1 -0
- package/dist/modules-BPBcSaM-.mjs +333 -0
- package/dist/mojo-ipc-BhwsdVUW.mjs +9 -0
- package/dist/native/scripts/linux/enum-windows.sh +12 -12
- package/dist/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/native-j8l473zn.mjs +961 -0
- package/dist/network-T0VRwNPd.mjs +7 -0
- package/dist/outputPaths-B4Ic4RZh.mjs +2 -0
- package/dist/parse-args-Bw413PlW.mjs +1 -0
- package/dist/platform-CzaQtISh.mjs +93 -0
- package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +1 -0
- package/dist/process-CWhsCWrf.mjs +2 -0
- package/dist/proxy-DZFlDsG3.mjs +2 -0
- package/dist/registry-DH4sc1dt.mjs +1 -0
- package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
- package/dist/response-C7rKQst4.mjs +1 -0
- package/dist/search-defaults-lYBVn_3L.mjs +1 -0
- package/dist/server/plugin-api.d.mts +19 -36
- package/dist/server/plugin-api.mjs +1 -293
- package/dist/shared-state-board-BSjXLUV1.mjs +1 -0
- package/dist/sourcemap-Dh3Ai_ur.mjs +1 -0
- package/dist/ssrf-policy-CsIJGkpd.mjs +1 -0
- package/dist/streaming-BcJ0B6ao.mjs +1 -0
- package/dist/tool-builder-qif8M9-K.mjs +1 -0
- package/dist/transform-DOxzeWPB.mjs +103 -0
- package/dist/types-D9EiE5o9.mjs +1 -0
- package/dist/types-Fz69RzbZ.mjs +1 -0
- package/dist/wasm-CZ_HTfKR.mjs +174 -0
- package/dist/webcrack-C1iYG_EX.mjs +46 -0
- package/dist/workflow-BdwQmARn.mjs +101 -0
- package/package.json +55 -82
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/AntiCheatDetector-CqGDXmfc.mjs +0 -350
- package/dist/CacheAdapters-jJFy20G-.mjs +0 -80
- package/dist/CodeInjector-BdjRfNx7.mjs +0 -150
- package/dist/ConsoleMonitor-DykL3IAw.mjs +0 -2269
- package/dist/DarwinAPI-ETyy0xyo.mjs +0 -363
- package/dist/DetailedDataManager-HT49OrvF.mjs +0 -217
- package/dist/EventBus-DFKvADm3.mjs +0 -141
- package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +0 -153
- package/dist/ExtensionManager-BDMsY2Dz.mjs +0 -721
- package/dist/FingerprintManager-BN4UQWnX.mjs +0 -96
- package/dist/HardwareBreakpoint-Cc2AFq1Y.mjs +0 -239
- package/dist/HeapAnalyzer-DruMgsgj.mjs +0 -284
- package/dist/InstrumentationSession-DLH0vd-z.mjs +0 -244
- package/dist/MemoryController-CMtviNW_.mjs +0 -167
- package/dist/MemoryScanSession-ITgb_NMi.mjs +0 -278
- package/dist/MemoryScanner-CiL7Z3ey.mjs +0 -428
- package/dist/NativeMemoryManager.impl-D9Lkovvn.mjs +0 -485
- package/dist/NativeMemoryManager.utils-BBlAixF5.mjs +0 -165
- package/dist/PEAnalyzer-DMQ44gen.mjs +0 -385
- package/dist/PageController-BPJNqqBN.mjs +0 -431
- package/dist/PointerChainEngine-K7wN8Z-w.mjs +0 -325
- package/dist/PrerequisiteError-TuyZIs6n.mjs +0 -20
- package/dist/ProcessRegistry-zGg12QbE.mjs +0 -74
- package/dist/ResponseBuilder-CJXWmWNw.mjs +0 -143
- package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +0 -269
- package/dist/ScriptManager-ZuWD-0Jg.mjs +0 -3003
- package/dist/Speedhack-D-z0umeT.mjs +0 -156
- package/dist/StealthVerifier-BWmPgQsv.mjs +0 -135
- package/dist/StructureAnalyzer-Cav5AVSL.mjs +0 -429
- package/dist/ToolCatalog-5OJdMiF0.mjs +0 -582
- package/dist/ToolError-jh9whhMd.mjs +0 -15
- package/dist/ToolProbe-DbCFGyrg.mjs +0 -45
- package/dist/ToolRegistry-B9krbTtI.mjs +0 -180
- package/dist/ToolRouter.policy-BGDAGyeH.mjs +0 -344
- package/dist/TraceRecorder-B41Z5XBj.mjs +0 -1286
- package/dist/VersionDetector-K3V4vGsw.mjs +0 -104
- package/dist/Win32API-C2kjj0ze.mjs +0 -346
- package/dist/Win32Debug-CKrGOTpo.mjs +0 -274
- package/dist/WorkflowEngine-DJ6M4opp.mjs +0 -569
- package/dist/analysis-BHeJW2Nb.mjs +0 -1234
- package/dist/artifactRetention-CPXkUJXp.mjs +0 -598
- package/dist/artifacts-DkfosXH3.mjs +0 -59
- package/dist/authorization-schema-DRqyJMSk.mjs +0 -31
- package/dist/betterSqlite3-DLSBZodi.mjs +0 -74
- package/dist/binary-instrument--V3MAhJ4.mjs +0 -971
- package/dist/bind-helpers-ClV34xdn.mjs +0 -42
- package/dist/boringssl-inspector-Bo_LOLaS.mjs +0 -180
- package/dist/browser-Dx3_S2cG.mjs +0 -4369
- package/dist/capabilities-CcHlvWgK.mjs +0 -33
- package/dist/chunk-CjcI7cDX.mjs +0 -15
- package/dist/concurrency-Drev_Vz9.mjs +0 -41
- package/dist/constants-CDZLOoVv.mjs +0 -534
- package/dist/coordination-DgItD9DL.mjs +0 -259
- package/dist/debugger-RS3RSAqs.mjs +0 -1288
- package/dist/definitions-BEoYofW5.mjs +0 -47
- package/dist/definitions-BRaefg3u.mjs +0 -365
- package/dist/definitions-BbkvZkiv.mjs +0 -96
- package/dist/definitions-BtWSHJ3o.mjs +0 -17
- package/dist/definitions-C1gCHO0i.mjs +0 -43
- package/dist/definitions-CDOg_b-l.mjs +0 -138
- package/dist/definitions-CVPD9hzZ.mjs +0 -54
- package/dist/definitions-Cea8Lgl7.mjs +0 -94
- package/dist/definitions-DAgIyjxM.mjs +0 -10
- package/dist/definitions-DJA27nsL.mjs +0 -66
- package/dist/definitions-DKPFU3LW.mjs +0 -25
- package/dist/definitions-DPRpZQ96.mjs +0 -47
- package/dist/definitions-DUE5gmdn.mjs +0 -18
- package/dist/definitions-DYVjOtxa.mjs +0 -26
- package/dist/definitions-DcYLVLCo.mjs +0 -37
- package/dist/definitions-Pp5LI2H4.mjs +0 -27
- package/dist/definitions-j9KdHVNR.mjs +0 -14
- package/dist/definitions-uzkjBwa7.mjs +0 -258
- package/dist/definitions-va-AnLuQ.mjs +0 -28
- package/dist/encoding-DJeqHmpd.mjs +0 -1079
- package/dist/evidence-graph-bridge-DcYizFk2.mjs +0 -136
- package/dist/factory-C90tBff6.mjs +0 -575
- package/dist/flat-target-session-Dgax2Cy3.mjs +0 -29
- package/dist/formatAddress-nnMvEohD.mjs +0 -17
- package/dist/graphql-CoHrhweh.mjs +0 -1197
- package/dist/handlers-4jmR0nMs.mjs +0 -898
- package/dist/handlers-BAHPxcch.mjs +0 -789
- package/dist/handlers-BOs9b907.mjs +0 -2600
- package/dist/handlers-BWXEy6ef.mjs +0 -917
- package/dist/handlers-Bndn6QvE.mjs +0 -111
- package/dist/handlers-BqC4bD4s.mjs +0 -681
- package/dist/handlers-BtYq60bM2.mjs +0 -276
- package/dist/handlers-BzgcB4iv.mjs +0 -799
- package/dist/handlers-CRyRWj2b.mjs +0 -859
- package/dist/handlers-CVv2H1uq.mjs +0 -592
- package/dist/handlers-Dl5a7JS4.mjs +0 -572
- package/dist/handlers-Dx2d7jt7.mjs +0 -2537
- package/dist/handlers-HujRKC3b.mjs +0 -661
- package/dist/handlers.impl-XWXkQfyi.mjs +0 -807
- package/dist/hooks-B1B8NRHL.mjs +0 -898
- package/dist/logger-Dh_xb7_2.mjs +0 -93
- package/dist/maintenance-PRMkLVRW.mjs +0 -835
- package/dist/manifest-67Bok-Si.mjs +0 -58
- package/dist/manifest-6lNTMZAB2.mjs +0 -87
- package/dist/manifest-B2duEHiH.mjs +0 -90
- package/dist/manifest-B6EY9Vm8.mjs +0 -57
- package/dist/manifest-B6nKSbyY.mjs +0 -95
- package/dist/manifest-BL8AQNPF.mjs +0 -106
- package/dist/manifest-BSZvJJmV.mjs +0 -47
- package/dist/manifest-BU7qzUyX.mjs +0 -418
- package/dist/manifest-Bl62e8WK.mjs +0 -49
- package/dist/manifest-Bo5cXjdt.mjs +0 -82
- package/dist/manifest-BpS4gtUK.mjs +0 -1347
- package/dist/manifest-Bv65_e2W.mjs +0 -101
- package/dist/manifest-BytNIF4Z.mjs +0 -117
- package/dist/manifest-C-xtsjS3.mjs +0 -81
- package/dist/manifest-CDYl7OhA.mjs +0 -66
- package/dist/manifest-CRZ3xmkD.mjs +0 -61
- package/dist/manifest-CoW6u4Tp.mjs +0 -132
- package/dist/manifest-Cq5zN_8A.mjs +0 -50
- package/dist/manifest-D7YZM_2e.mjs +0 -194
- package/dist/manifest-DE_VrAeQ.mjs +0 -314
- package/dist/manifest-DGsXSCpT.mjs +0 -39
- package/dist/manifest-DJ2vfEuW.mjs +0 -156
- package/dist/manifest-DPXDYhEu.mjs +0 -80
- package/dist/manifest-Dd4fQb0a.mjs +0 -322
- package/dist/manifest-Deq6opGg.mjs +0 -223
- package/dist/manifest-DfJTafJK.mjs +0 -37
- package/dist/manifest-DgOdgN_j.mjs +0 -50
- package/dist/manifest-DlbMW4v4.mjs +0 -47
- package/dist/manifest-DmVfbH0w.mjs +0 -374
- package/dist/manifest-Dog6Ddjr.mjs +0 -109
- package/dist/manifest-DvgU5FWb.mjs +0 -58
- package/dist/manifest-HsfDBs7j.mjs +0 -50
- package/dist/manifest-I8oQHvCG.mjs +0 -186
- package/dist/manifest-NvH_a-av.mjs +0 -786
- package/dist/manifest-cEJU1v0Z.mjs +0 -129
- package/dist/manifest-wOl5XLB12.mjs +0 -112
- package/dist/modules-tZozf0LQ.mjs +0 -10635
- package/dist/mojo-ipc-DXNEXEqb.mjs +0 -640
- package/dist/network-CPVvwvFg.mjs +0 -3852
- package/dist/outputPaths-um7lCRY3.mjs +0 -1141
- package/dist/parse-args-B4cY5Vx5.mjs +0 -39
- package/dist/platform-CYeFoTWp.mjs +0 -2161
- package/dist/process-BTbgcVc6.mjs +0 -1306
- package/dist/proxy-r8YN6nP1.mjs +0 -192
- package/dist/registry-Bl8ZQW61.mjs +0 -34
- package/dist/response-CWhh2aLo.mjs +0 -34
- package/dist/shared-state-board-BoZnSoj-.mjs +0 -586
- package/dist/sourcemap-BIDHUVXy.mjs +0 -934
- package/dist/ssrf-policy-Dsqd-DTX.mjs +0 -166
- package/dist/streaming-Dal6utPp.mjs +0 -725
- package/dist/tool-builder-BHJp32mV.mjs +0 -186
- package/dist/transform-DRVgGG90.mjs +0 -1011
- package/dist/types-Bx92KJfT.mjs +0 -4
- package/dist/types-DDBWs9UP.mjs +0 -37
- package/dist/wasm-BYx5UOeG.mjs +0 -1044
- package/dist/webcrack-Be0_FccV.mjs +0 -747
- package/dist/workflow-BpuKEtvn.mjs +0 -725
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { o as evaluateOnNewDocumentWithTimeout, s as evaluateWithTimeout } from "./PageController-BPJNqqBN.mjs";
|
|
3
|
-
import "./definitions-DUE5gmdn.mjs";
|
|
4
|
-
//#region src/server/domains/antidebug/scripts.data.bypass-core.ts
|
|
5
|
-
const ANTI_DEBUG_BYPASS_CORE_SCRIPTS = {
|
|
6
|
-
bypassDebuggerStatement: `(function () {
|
|
1
|
+
import{o as e,r as t,t as n}from"./parse-args-Bw413PlW.mjs";import{o as r,s as i}from"./PageController-Dfsm1_o7.mjs";import{n as a}from"./ResponseBuilder-BfWP-uaT.mjs";import"./definitions-Cenu6mxo.mjs";const o={bypassDebuggerStatement:`(function () {
|
|
7
2
|
var globalObj = typeof window !== 'undefined' ? window : globalThis;
|
|
8
3
|
var installFlag = '__ANTI_DEBUGGER_STATEMENT_INSTALLED__';
|
|
9
4
|
if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
|
|
@@ -155,8 +150,7 @@ const ANTI_DEBUG_BYPASS_CORE_SCRIPTS = {
|
|
|
155
150
|
for (var i = 0; i < existingScripts.length; i += 1) {
|
|
156
151
|
patchScriptElement(existingScripts[i]);
|
|
157
152
|
}
|
|
158
|
-
})();`,
|
|
159
|
-
bypassTiming: `(function () {
|
|
153
|
+
})();`,bypassTiming:`(function () {
|
|
160
154
|
var globalObj = typeof window !== 'undefined' ? window : globalThis;
|
|
161
155
|
var installFlag = '__ANTI_DEBUG_TIMING_INSTALLED__';
|
|
162
156
|
if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
|
|
@@ -292,8 +286,7 @@ const ANTI_DEBUG_BYPASS_CORE_SCRIPTS = {
|
|
|
292
286
|
console.timeEnd = wrappedTimeEnd;
|
|
293
287
|
} catch (_) {}
|
|
294
288
|
}
|
|
295
|
-
})();`,
|
|
296
|
-
bypassStackTrace: `(function () {
|
|
289
|
+
})();`,bypassStackTrace:`(function () {
|
|
297
290
|
var globalObj = typeof window !== 'undefined' ? window : globalThis;
|
|
298
291
|
var installFlag = '__ANTI_DEBUG_STACK_TRACE_INSTALLED__';
|
|
299
292
|
if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
|
|
@@ -493,11 +486,7 @@ const ANTI_DEBUG_BYPASS_CORE_SCRIPTS = {
|
|
|
493
486
|
globalObj.Error = PatchedError;
|
|
494
487
|
} catch (_) {}
|
|
495
488
|
}
|
|
496
|
-
})();`
|
|
497
|
-
};
|
|
498
|
-
//#endregion
|
|
499
|
-
//#region src/server/domains/antidebug/scripts.data.bypass-console.ts
|
|
500
|
-
const ANTI_DEBUG_BYPASS_CONSOLE_SCRIPT = { bypassConsoleDetect: `(function () {
|
|
489
|
+
})();`},s={bypassConsoleDetect:`(function () {
|
|
501
490
|
var globalObj = typeof window !== 'undefined' ? window : globalThis;
|
|
502
491
|
var installFlag = '__ANTI_DEBUG_CONSOLE_INSTALLED__';
|
|
503
492
|
if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
|
|
@@ -574,7 +563,8 @@ const ANTI_DEBUG_BYPASS_CONSOLE_SCRIPT = { bypassConsoleDetect: `(function () {
|
|
|
574
563
|
}
|
|
575
564
|
|
|
576
565
|
var valueType = typeof value;
|
|
577
|
-
if (value == null || valueType === 'string' || valueType === 'number' || valueType === 'boolean' || valueType === 'bigint')
|
|
566
|
+
if (value == null || valueType === 'string' || valueType === 'number' || valueType === 'boolean' || valueType === 'bigint')
|
|
567
|
+
{
|
|
578
568
|
return value;
|
|
579
569
|
}
|
|
580
570
|
|
|
@@ -682,10 +672,7 @@ const ANTI_DEBUG_BYPASS_CONSOLE_SCRIPT = { bypassConsoleDetect: `(function () {
|
|
|
682
672
|
} catch (_) {}
|
|
683
673
|
}
|
|
684
674
|
}
|
|
685
|
-
})();`
|
|
686
|
-
//#endregion
|
|
687
|
-
//#region src/server/domains/antidebug/scripts.data.detect.ts
|
|
688
|
-
const ANTI_DEBUG_DETECT_SCRIPTS = { detectProtections: `(async function () {
|
|
675
|
+
})();`},c={detectProtections:`(async function () {
|
|
689
676
|
function pushUnique(list, value) {
|
|
690
677
|
if (list.indexOf(value) === -1) {
|
|
691
678
|
list.push(value);
|
|
@@ -840,242 +827,4 @@ const ANTI_DEBUG_DETECT_SCRIPTS = { detectProtections: `(async function () {
|
|
|
840
827
|
sourceBytesApprox: sourceBlob.length
|
|
841
828
|
}
|
|
842
829
|
};
|
|
843
|
-
})();` };
|
|
844
|
-
//#endregion
|
|
845
|
-
//#region src/server/domains/antidebug/scripts.data.ts
|
|
846
|
-
const ANTI_DEBUG_SCRIPTS = {
|
|
847
|
-
...ANTI_DEBUG_BYPASS_CORE_SCRIPTS,
|
|
848
|
-
...ANTI_DEBUG_BYPASS_CONSOLE_SCRIPT,
|
|
849
|
-
...ANTI_DEBUG_DETECT_SCRIPTS
|
|
850
|
-
};
|
|
851
|
-
//#endregion
|
|
852
|
-
//#region src/server/domains/antidebug/handlers.ts
|
|
853
|
-
var AntiDebugToolHandlers = class AntiDebugToolHandlers {
|
|
854
|
-
static DEFAULT_DEBUGGER_MODE = "remove";
|
|
855
|
-
static DEFAULT_MAX_DRIFT = 50;
|
|
856
|
-
static DEFAULT_STACK_FILTER_PATTERNS = [
|
|
857
|
-
"puppeteer",
|
|
858
|
-
"devtools",
|
|
859
|
-
"__puppeteer",
|
|
860
|
-
"CDP"
|
|
861
|
-
];
|
|
862
|
-
constructor(collector) {
|
|
863
|
-
this.collector = collector;
|
|
864
|
-
}
|
|
865
|
-
toTextResponse(payload) {
|
|
866
|
-
return { content: [{
|
|
867
|
-
type: "text",
|
|
868
|
-
text: JSON.stringify(payload, null, 2)
|
|
869
|
-
}] };
|
|
870
|
-
}
|
|
871
|
-
parseDebuggerMode(value) {
|
|
872
|
-
if (value === "remove" || value === "noop") return value;
|
|
873
|
-
if (typeof value === "string") {
|
|
874
|
-
const normalized = value.trim().toLowerCase();
|
|
875
|
-
if (normalized === "remove" || normalized === "noop") return normalized;
|
|
876
|
-
}
|
|
877
|
-
return AntiDebugToolHandlers.DEFAULT_DEBUGGER_MODE;
|
|
878
|
-
}
|
|
879
|
-
mergeStackFilterPatterns(extraPatterns) {
|
|
880
|
-
const merged = [...AntiDebugToolHandlers.DEFAULT_STACK_FILTER_PATTERNS, ...extraPatterns].map((item) => item.trim());
|
|
881
|
-
return Array.from(new Set(merged.filter((item) => item.length > 0)));
|
|
882
|
-
}
|
|
883
|
-
buildScript(template, replacements) {
|
|
884
|
-
let output = template;
|
|
885
|
-
for (const [token, value] of Object.entries(replacements)) output = output.split(token).join(value);
|
|
886
|
-
return output;
|
|
887
|
-
}
|
|
888
|
-
buildDebuggerBypassScript(mode) {
|
|
889
|
-
return this.buildScript(ANTI_DEBUG_SCRIPTS.bypassDebuggerStatement, { __ANTI_DEBUG_MODE__: JSON.stringify(mode) });
|
|
890
|
-
}
|
|
891
|
-
buildTimingBypassScript(maxDrift) {
|
|
892
|
-
return this.buildScript(ANTI_DEBUG_SCRIPTS.bypassTiming, { __ANTI_DEBUG_MAX_DRIFT__: String(maxDrift) });
|
|
893
|
-
}
|
|
894
|
-
buildStackTraceBypassScript(filterPatterns) {
|
|
895
|
-
return this.buildScript(ANTI_DEBUG_SCRIPTS.bypassStackTrace, { __ANTI_DEBUG_FILTER_PATTERNS__: JSON.stringify(filterPatterns) });
|
|
896
|
-
}
|
|
897
|
-
async injectScripts(page, scripts, persistent) {
|
|
898
|
-
if (persistent) for (const script of scripts) await evaluateOnNewDocumentWithTimeout(page, script);
|
|
899
|
-
for (const script of scripts) await evaluateWithTimeout(page, script);
|
|
900
|
-
}
|
|
901
|
-
async getPage() {
|
|
902
|
-
return this.collector.getActivePage();
|
|
903
|
-
}
|
|
904
|
-
async handleAntiDebugBypassAll(args) {
|
|
905
|
-
try {
|
|
906
|
-
const persistent = argBool(args, "persistent", true);
|
|
907
|
-
const page = await this.getPage();
|
|
908
|
-
const scripts = [
|
|
909
|
-
this.buildDebuggerBypassScript(AntiDebugToolHandlers.DEFAULT_DEBUGGER_MODE),
|
|
910
|
-
this.buildTimingBypassScript(AntiDebugToolHandlers.DEFAULT_MAX_DRIFT),
|
|
911
|
-
this.buildStackTraceBypassScript(this.mergeStackFilterPatterns([])),
|
|
912
|
-
ANTI_DEBUG_SCRIPTS.bypassConsoleDetect
|
|
913
|
-
];
|
|
914
|
-
await this.injectScripts(page, scripts, persistent);
|
|
915
|
-
return this.toTextResponse({
|
|
916
|
-
success: true,
|
|
917
|
-
tool: "antidebug_bypass_all",
|
|
918
|
-
persistent,
|
|
919
|
-
injectedCount: scripts.length,
|
|
920
|
-
injected: [
|
|
921
|
-
"bypassDebuggerStatement",
|
|
922
|
-
"bypassTiming",
|
|
923
|
-
"bypassStackTrace",
|
|
924
|
-
"bypassConsoleDetect"
|
|
925
|
-
]
|
|
926
|
-
});
|
|
927
|
-
} catch (error) {
|
|
928
|
-
return this.toTextResponse({
|
|
929
|
-
success: false,
|
|
930
|
-
tool: "antidebug_bypass_all",
|
|
931
|
-
error: error instanceof Error ? error.message : String(error)
|
|
932
|
-
});
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
async handleAntiDebugBypassDebuggerStatement(args) {
|
|
936
|
-
try {
|
|
937
|
-
const mode = this.parseDebuggerMode(args.mode);
|
|
938
|
-
const page = await this.getPage();
|
|
939
|
-
const script = this.buildDebuggerBypassScript(mode);
|
|
940
|
-
await this.injectScripts(page, [script], true);
|
|
941
|
-
return this.toTextResponse({
|
|
942
|
-
success: true,
|
|
943
|
-
tool: "antidebug_bypass_debugger_statement",
|
|
944
|
-
mode,
|
|
945
|
-
persistent: true
|
|
946
|
-
});
|
|
947
|
-
} catch (error) {
|
|
948
|
-
return this.toTextResponse({
|
|
949
|
-
success: false,
|
|
950
|
-
tool: "antidebug_bypass_debugger_statement",
|
|
951
|
-
error: error instanceof Error ? error.message : String(error)
|
|
952
|
-
});
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
async handleAntiDebugBypassTiming(args) {
|
|
956
|
-
try {
|
|
957
|
-
const maxDrift = argNumber(args, "maxDrift", AntiDebugToolHandlers.DEFAULT_MAX_DRIFT) ?? AntiDebugToolHandlers.DEFAULT_MAX_DRIFT;
|
|
958
|
-
const page = await this.getPage();
|
|
959
|
-
const script = this.buildTimingBypassScript(maxDrift);
|
|
960
|
-
await this.injectScripts(page, [script], true);
|
|
961
|
-
return this.toTextResponse({
|
|
962
|
-
success: true,
|
|
963
|
-
tool: "antidebug_bypass_timing",
|
|
964
|
-
maxDrift,
|
|
965
|
-
persistent: true
|
|
966
|
-
});
|
|
967
|
-
} catch (error) {
|
|
968
|
-
return this.toTextResponse({
|
|
969
|
-
success: false,
|
|
970
|
-
tool: "antidebug_bypass_timing",
|
|
971
|
-
error: error instanceof Error ? error.message : String(error)
|
|
972
|
-
});
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
async handleAntiDebugBypassStackTrace(args) {
|
|
976
|
-
try {
|
|
977
|
-
const userPatterns = argStringArray(args, "filterPatterns");
|
|
978
|
-
const mergedPatterns = this.mergeStackFilterPatterns(userPatterns);
|
|
979
|
-
const page = await this.getPage();
|
|
980
|
-
const script = this.buildStackTraceBypassScript(mergedPatterns);
|
|
981
|
-
await this.injectScripts(page, [script], true);
|
|
982
|
-
return this.toTextResponse({
|
|
983
|
-
success: true,
|
|
984
|
-
tool: "antidebug_bypass_stack_trace",
|
|
985
|
-
filterPatterns: mergedPatterns,
|
|
986
|
-
persistent: true
|
|
987
|
-
});
|
|
988
|
-
} catch (error) {
|
|
989
|
-
return this.toTextResponse({
|
|
990
|
-
success: false,
|
|
991
|
-
tool: "antidebug_bypass_stack_trace",
|
|
992
|
-
error: error instanceof Error ? error.message : String(error)
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
async handleAntiDebugBypassConsoleDetect(_args) {
|
|
997
|
-
try {
|
|
998
|
-
const page = await this.getPage();
|
|
999
|
-
await this.injectScripts(page, [ANTI_DEBUG_SCRIPTS.bypassConsoleDetect], true);
|
|
1000
|
-
return this.toTextResponse({
|
|
1001
|
-
success: true,
|
|
1002
|
-
tool: "antidebug_bypass_console_detect",
|
|
1003
|
-
persistent: true
|
|
1004
|
-
});
|
|
1005
|
-
} catch (error) {
|
|
1006
|
-
return this.toTextResponse({
|
|
1007
|
-
success: false,
|
|
1008
|
-
tool: "antidebug_bypass_console_detect",
|
|
1009
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1010
|
-
});
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
async handleAntiDebugDetectProtections(_args) {
|
|
1014
|
-
try {
|
|
1015
|
-
const result = await evaluateWithTimeout(await this.getPage(), ANTI_DEBUG_SCRIPTS.detectProtections);
|
|
1016
|
-
return this.toTextResponse({
|
|
1017
|
-
success: result?.success ?? true,
|
|
1018
|
-
tool: "antidebug_detect_protections",
|
|
1019
|
-
detected: result?.detected ?? false,
|
|
1020
|
-
count: result?.count ?? 0,
|
|
1021
|
-
protections: result?.protections ?? [],
|
|
1022
|
-
recommendations: result?.recommendations ?? [],
|
|
1023
|
-
evidence: result?.evidence ?? {}
|
|
1024
|
-
});
|
|
1025
|
-
} catch (error) {
|
|
1026
|
-
return this.toTextResponse({
|
|
1027
|
-
success: false,
|
|
1028
|
-
tool: "antidebug_detect_protections",
|
|
1029
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1030
|
-
});
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
async handleAntidebugBypass(args) {
|
|
1034
|
-
const rawTypes = args["types"];
|
|
1035
|
-
const typesArr = Array.isArray(rawTypes) ? rawTypes : ["all"];
|
|
1036
|
-
const types = typesArr.length === 0 ? ["all"] : typesArr;
|
|
1037
|
-
if (types.includes("all")) return this.handleAntiDebugBypassAll(args);
|
|
1038
|
-
const persistent = argBool(args, "persistent", true);
|
|
1039
|
-
const mode = this.parseDebuggerMode(args["mode"]);
|
|
1040
|
-
const maxDrift = argNumber(args, "maxDrift", AntiDebugToolHandlers.DEFAULT_MAX_DRIFT) ?? AntiDebugToolHandlers.DEFAULT_MAX_DRIFT;
|
|
1041
|
-
const userPatterns = argStringArray(args, "filterPatterns");
|
|
1042
|
-
const applied = [];
|
|
1043
|
-
try {
|
|
1044
|
-
const page = await this.getPage();
|
|
1045
|
-
if (types.includes("debugger_statement")) {
|
|
1046
|
-
const script = this.buildDebuggerBypassScript(mode);
|
|
1047
|
-
await this.injectScripts(page, [script], persistent);
|
|
1048
|
-
applied.push("debugger_statement");
|
|
1049
|
-
}
|
|
1050
|
-
if (types.includes("timing")) {
|
|
1051
|
-
const script = this.buildTimingBypassScript(maxDrift);
|
|
1052
|
-
await this.injectScripts(page, [script], persistent);
|
|
1053
|
-
applied.push("timing");
|
|
1054
|
-
}
|
|
1055
|
-
if (types.includes("stack_trace")) {
|
|
1056
|
-
const mergedPatterns = this.mergeStackFilterPatterns(userPatterns);
|
|
1057
|
-
const script = this.buildStackTraceBypassScript(mergedPatterns);
|
|
1058
|
-
await this.injectScripts(page, [script], persistent);
|
|
1059
|
-
applied.push("stack_trace");
|
|
1060
|
-
}
|
|
1061
|
-
if (types.includes("console_detect")) {
|
|
1062
|
-
await this.injectScripts(page, [ANTI_DEBUG_SCRIPTS.bypassConsoleDetect], persistent);
|
|
1063
|
-
applied.push("console_detect");
|
|
1064
|
-
}
|
|
1065
|
-
return this.toTextResponse({
|
|
1066
|
-
success: true,
|
|
1067
|
-
tool: "antidebug_bypass",
|
|
1068
|
-
applied,
|
|
1069
|
-
persistent
|
|
1070
|
-
});
|
|
1071
|
-
} catch (error) {
|
|
1072
|
-
return this.toTextResponse({
|
|
1073
|
-
success: false,
|
|
1074
|
-
tool: "antidebug_bypass",
|
|
1075
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1076
|
-
});
|
|
1077
|
-
}
|
|
1078
|
-
}
|
|
1079
|
-
};
|
|
1080
|
-
//#endregion
|
|
1081
|
-
export { AntiDebugToolHandlers };
|
|
830
|
+
})();`},l={...o,...s,...c};var u=class o{collector;static DEFAULT_DEBUGGER_MODE=`remove`;static DEFAULT_MAX_DRIFT=50;static DEFAULT_STACK_FILTER_PATTERNS=[`puppeteer`,`devtools`,`__puppeteer`,`CDP`];constructor(e){this.collector=e}parseDebuggerMode(e){if(e===`remove`||e===`noop`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`remove`||t===`noop`)return t}return o.DEFAULT_DEBUGGER_MODE}mergeStackFilterPatterns(e){let t=[...o.DEFAULT_STACK_FILTER_PATTERNS,...e].map(e=>e.trim());return Array.from(new Set(t.filter(e=>e.length>0)))}buildScript(e,t){let n=e;for(let[e,r]of Object.entries(t))n=n.split(e).join(r);return n}buildDebuggerBypassScript(e){return this.buildScript(l.bypassDebuggerStatement,{__ANTI_DEBUG_MODE__:JSON.stringify(e)})}buildTimingBypassScript(e){return this.buildScript(l.bypassTiming,{__ANTI_DEBUG_MAX_DRIFT__:String(e)})}buildStackTraceBypassScript(e){return this.buildScript(l.bypassStackTrace,{__ANTI_DEBUG_FILTER_PATTERNS__:JSON.stringify(e)})}async injectScripts(e,t,n){if(n)for(let n of t)await r(e,n);for(let n of t)await i(e,n)}async getPage(){return this.collector.getActivePage()}async handleAntiDebugBypassAll(e){return a(async()=>{let t=n(e,`persistent`,!0),r=await this.getPage(),i=[this.buildDebuggerBypassScript(o.DEFAULT_DEBUGGER_MODE),this.buildTimingBypassScript(o.DEFAULT_MAX_DRIFT),this.buildStackTraceBypassScript(this.mergeStackFilterPatterns([])),l.bypassConsoleDetect];return await this.injectScripts(r,i,t),{tool:`antidebug_bypass_all`,persistent:t,injectedCount:i.length,injected:[`bypassDebuggerStatement`,`bypassTiming`,`bypassStackTrace`,`bypassConsoleDetect`]}})}async handleAntiDebugBypassDebuggerStatement(e){return a(async()=>{let t=this.parseDebuggerMode(e.mode),n=await this.getPage(),r=this.buildDebuggerBypassScript(t);return await this.injectScripts(n,[r],!0),{tool:`antidebug_bypass_debugger_statement`,mode:t,persistent:!0}})}async handleAntiDebugBypassTiming(e){return a(async()=>{let n=t(e,`maxDrift`,o.DEFAULT_MAX_DRIFT)??o.DEFAULT_MAX_DRIFT,r=await this.getPage(),i=this.buildTimingBypassScript(n);return await this.injectScripts(r,[i],!0),{tool:`antidebug_bypass_timing`,maxDrift:n,persistent:!0}})}async handleAntiDebugBypassStackTrace(t){return a(async()=>{let n=e(t,`filterPatterns`),r=this.mergeStackFilterPatterns(n),i=await this.getPage(),a=this.buildStackTraceBypassScript(r);return await this.injectScripts(i,[a],!0),{tool:`antidebug_bypass_stack_trace`,filterPatterns:r,persistent:!0}})}async handleAntiDebugBypassConsoleDetect(e){return a(async()=>{let e=await this.getPage();return await this.injectScripts(e,[l.bypassConsoleDetect],!0),{tool:`antidebug_bypass_console_detect`,persistent:!0}})}async handleAntiDebugDetectProtections(e){return a(async()=>{let e=await i(await this.getPage(),l.detectProtections);return{tool:`antidebug_detect_protections`,detected:e?.detected??!1,count:e?.count??0,protections:e?.protections??[],recommendations:e?.recommendations??[],evidence:e?.evidence??{}}})}async handleAntidebugBypass(r){let i=r.types,s=Array.isArray(i)?i:[`all`],c=s.length===0?[`all`]:s;if(c.includes(`all`))return this.handleAntiDebugBypassAll(r);let u=n(r,`persistent`,!0),d=this.parseDebuggerMode(r.mode),f=t(r,`maxDrift`,o.DEFAULT_MAX_DRIFT)??o.DEFAULT_MAX_DRIFT,p=e(r,`filterPatterns`);return a(async()=>{let e=await this.getPage(),t=[];if(c.includes(`debugger_statement`)){let n=this.buildDebuggerBypassScript(d);await this.injectScripts(e,[n],u),t.push(`debugger_statement`)}if(c.includes(`timing`)){let n=this.buildTimingBypassScript(f);await this.injectScripts(e,[n],u),t.push(`timing`)}if(c.includes(`stack_trace`)){let n=this.mergeStackFilterPatterns(p),r=this.buildStackTraceBypassScript(n);await this.injectScripts(e,[r],u),t.push(`stack_trace`)}return c.includes(`console_detect`)&&(await this.injectScripts(e,[l.bypassConsoleDetect],u),t.push(`console_detect`)),{tool:`antidebug_bypass`,applied:t,persistent:u}})}};export{u as AntiDebugToolHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{Xr as t,g as n,h as r}from"./constants-BYj8Xek8.mjs";import{i,l as a,n as o}from"./outputPaths-B4Ic4RZh.mjs";import{n as s,r as c}from"./artifacts-CkodUM4j.mjs";import{join as l,resolve as u}from"node:path";import{readdir as d,rm as f,stat as p}from"node:fs/promises";var m=class n{static instance;MAX_TOKENS=t;WARNING_THRESHOLDS=[.8,.9,.95];BYTES_PER_TOKEN=4;AUTO_CLEANUP_THRESHOLD=.9;HISTORY_RETENTION=300*1e3;currentUsage=0;toolCallHistory=[];warnings=new Set;sessionStartTime=Date.now();trackingEnabled=!0;MAX_ESTIMATION_DEPTH=4;MAX_ESTIMATION_ARRAY_ITEMS=50;MAX_ESTIMATION_OBJECT_KEYS=50;MAX_ESTIMATION_STRING_LENGTH=2e3;MAX_ESTIMATION_BYTES=256*1024;externalCleanupFn=null;constructor(){e.info(`TokenBudgetManager initialized`)}static getInstance(){return this.instance||=new n,this.instance}setExternalCleanup(e){this.externalCleanupFn=e}recordToolCall(t,n,r){if(this.trackingEnabled)try{let i=this.calculateSize(n),a=this.calculateSize(r),o=i+a,s=this.estimateTokens(o);this.currentUsage+=s;let c={toolName:t,timestamp:Date.now(),requestSize:i,responseSize:a,estimatedTokens:s,cumulativeTokens:this.currentUsage};this.toolCallHistory.push(c),e.debug(`Token usage: ${this.currentUsage}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%) | Tool: ${t} | Size: ${(o/1024).toFixed(1)}KB | Tokens: ${s}`),this.checkWarnings(),this.shouldAutoCleanup()&&this.autoCleanup()}catch(t){e.error(`Failed to record tool call:`,t)}}isRecord(e){return typeof e==`object`&&!!e}hasDetailedSummarySize(e){if(!this.isRecord(e)||!(`detailId`in e))return!1;let t=e.summary;if(!this.isRecord(t))return!1;let{size:n}=t;return typeof n==`number`&&Number.isFinite(n)&&n>0}tryEstimateMcpEnvelope(e){if(!this.isRecord(e))return null;let t=e.content;if(!Array.isArray(t)||t.length===0)return null;let n=t[0];if(!this.isRecord(n)||n.type!==`text`||typeof n.text!=`string`)return null;let r=n.text,i=r.length>this.MAX_ESTIMATION_STRING_LENGTH?`${r.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)}...[truncated:${r.length}]`:r,a=42+(e.isError===!0?14:0),o=Buffer.byteLength(i,`utf8`);return Math.min(a+o,this.MAX_ESTIMATION_BYTES)}calculateSize(t){try{if(this.hasDetailedSummarySize(t))return Math.min(t.summary.size,this.MAX_ESTIMATION_BYTES);let e=this.tryEstimateMcpEnvelope(t);if(e!==null)return e;let n=this.normalizeForSizeEstimate(t,0,new WeakSet),r=JSON.stringify(n);return r?Math.min(Buffer.byteLength(r,`utf8`),this.MAX_ESTIMATION_BYTES):0}catch(t){return e.warn(`Failed to calculate data size:`,t),0}}normalizeForSizeEstimate(e,t,n){if(e==null)return e;let r=typeof e;if(r===`boolean`||r===`number`)return e;if(r===`string`){let t=e;if(t.length<=this.MAX_ESTIMATION_STRING_LENGTH)return t;let n=`...[truncated:${t.length}]`,r=Math.max(this.MAX_ESTIMATION_STRING_LENGTH-n.length,0);return`${t.slice(0,r)}${n}`}if(r===`bigint`||r===`symbol`)return e.toString();if(r===`function`)return`[Function]`;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack?.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)};if(Buffer.isBuffer(e))return`[Buffer:${e.byteLength}]`;if(t>=this.MAX_ESTIMATION_DEPTH)return Array.isArray(e)?`[Array:${e.length}]`:`[Object]`;if(Array.isArray(e)){let r=e.slice(0,this.MAX_ESTIMATION_ARRAY_ITEMS).map(e=>this.normalizeForSizeEstimate(e,t+1,n));return e.length>this.MAX_ESTIMATION_ARRAY_ITEMS&&r.push(`[truncated:${e.length-this.MAX_ESTIMATION_ARRAY_ITEMS}]`),r}if(r===`object`){if(!this.isRecord(e))return`[Object]`;if(n.has(e))return`[Circular]`;n.add(e);let r=Object.entries(e),i=r.slice(0,this.MAX_ESTIMATION_OBJECT_KEYS),a={};for(let[e,r]of i)a[e]=this.normalizeForSizeEstimate(r,t+1,n);return r.length>this.MAX_ESTIMATION_OBJECT_KEYS&&(a.__truncatedKeys=r.length-this.MAX_ESTIMATION_OBJECT_KEYS),a}return String(e)}estimateTokens(e){return Math.ceil(e/this.BYTES_PER_TOKEN)}getUsagePercentage(){return Math.round(this.currentUsage/this.MAX_TOKENS*100)}checkWarnings(){let e=this.currentUsage/this.MAX_TOKENS;for(let t of this.WARNING_THRESHOLDS)e>=t&&!this.warnings.has(t)&&(this.emitWarning(t),this.warnings.add(t))}emitWarning(t){let n=Math.round(t*100),r=this.MAX_TOKENS-this.currentUsage;e.warn(`Token Budget Warning: ${n}% used! (${this.currentUsage}/${this.MAX_TOKENS}, ${r} tokens remaining)`),t>=.95?e.warn(`CRITICAL: Consider clearing caches or starting a new session.`):t>=.9?e.warn(`HIGH: Auto-cleanup will trigger soon. Consider using summary modes.`):t>=.8&&e.warn(`MODERATE: Monitor usage. Use get_token_budget_stats for details.`)}shouldAutoCleanup(){return this.currentUsage/this.MAX_TOKENS>=this.AUTO_CLEANUP_THRESHOLD}autoCleanup(){e.info(`Auto-cleanup triggered at 90% usage.`);let t=this.currentUsage;if(this.externalCleanupFn)try{this.externalCleanupFn(),e.info(`External cleanup callback invoked`)}catch(t){e.warn(`External cleanup callback failed:`,t)}let n=Date.now()-this.HISTORY_RETENTION,r=this.toolCallHistory.length;this.toolCallHistory=this.toolCallHistory.filter(e=>e.timestamp>n);let i=r-this.toolCallHistory.length;e.info(`Removed ${i} old tool call records`),this.recalculateUsage();let a=this.currentUsage,o=t-a,s=Math.round(o/this.MAX_TOKENS*100);e.info(`Cleanup complete. Freed ${o} tokens (${s}%). Usage: ${a}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%)`);let c=a/this.MAX_TOKENS;this.warnings=new Set(Array.from(this.warnings).filter(e=>c>=e))}recalculateUsage(){this.currentUsage=this.toolCallHistory.reduce((e,t)=>e+t.estimatedTokens,0)}getStats(){let e=new Map;for(let t of this.toolCallHistory){let n=e.get(t.toolName)||0;e.set(t.toolName,n+t.estimatedTokens)}let t=Array.from(e.entries()).map(([e,t])=>({tool:e,tokens:t,percentage:Math.round(t/this.currentUsage*100)})).toSorted((e,t)=>t.tokens-e.tokens).slice(0,10),n=this.generateSuggestions(t),r=this.toolCallHistory.slice(-20);return{currentUsage:this.currentUsage,maxTokens:this.MAX_TOKENS,usagePercentage:this.getUsagePercentage(),toolCallCount:this.toolCallHistory.length,topTools:t,warnings:Array.from(this.warnings).map(e=>Math.round(e*100)),recentCalls:r,suggestions:n,sessionStartTime:this.sessionStartTime}}generateSuggestions(e){let t=[],n=this.currentUsage/this.MAX_TOKENS;n>=.95?t.push(` CRITICAL: Clear all caches immediately or start a new session`):n>=.9?t.push(`HIGH: Auto-cleanup triggered. Consider manual cleanup for better control`):n>=.8&&t.push(`MODERATE: Monitor usage closely. Use summary modes for large data`);for(let{tool:n,percentage:r}of e)r>30&&(n.includes(`collect_code`)?t.push(` ${n} uses ${r}% tokens. Try smartMode="summary" or "priority"`):n.includes(`get_script_source`)?t.push(` ${n} uses ${r}% tokens. Try preview=true first`):n.includes(`network_get_requests`)?t.push(` ${n} uses ${r}% tokens. Reduce limit or use filters`):n.includes(`page_evaluate`)&&t.push(` ${n} uses ${r}% tokens. Query specific properties instead of full objects`));return t.length===0&&t.push(` Token usage is healthy. Continue monitoring.`),t}manualCleanup(){e.info(`Manual cleanup requested.`),this.autoCleanup()}setTrackingEnabled(t){this.trackingEnabled!==t&&(this.trackingEnabled=t,e.warn(`Token budget tracking ${t?`enabled`:`disabled`}`))}isTrackingEnabled(){return this.trackingEnabled}reset(){e.info(`Resetting token budget...`),this.currentUsage=0,this.toolCallHistory=[],this.warnings.clear(),this.sessionStartTime=Date.now(),e.info(`Token budget reset complete`)}},h=class t{static instance;GLOBAL_MAX_SIZE=r;LOW_HIT_RATE_THRESHOLD=n;caches=new Map;constructor(){e.info(`UnifiedCacheManager initialized`)}static getInstance(){return this.instance||=new t,this.instance}registerCache(t){this.caches.set(t.name,t),e.info(`Registered cache: ${t.name}`)}unregisterCache(t){this.caches.delete(t),e.info(`Unregistered cache: ${t}`)}async getGlobalStats(){let t=0,n=0,r=0,i=0,a=[];for(let[o,s]of this.caches)try{let e=await s.getStats();t+=e.entries,n+=e.size,r+=e.hits||0,i+=e.misses||0,a.push({name:o,entries:e.entries,size:e.size,sizeMB:(e.size/1024/1024).toFixed(2),hitRate:e.hitRate,ttl:e.ttl})}catch(t){e.error(`Failed to get stats for cache ${o}:`,t)}let o=r+i>0?r/(r+i):0,s=this.generateRecommendations(n,o,a);return{totalEntries:t,totalSize:n,totalSizeMB:(n/1024/1024).toFixed(2),hitRate:o,caches:a,recommendations:s}}async smartCleanup(t){let n=t||this.GLOBAL_MAX_SIZE*.7,r=await this.getGlobalStats(),i=r.totalSize;if(i<=n)return e.info(`No cleanup needed`),{before:i,after:i,freed:0,freedPercentage:0};e.info(`Smart cleanup: current ${r.totalSizeMB}MB, target ${(n/1024/1024).toFixed(2)}MB`),await this.cleanupExpired();let a=await this.getGlobalStats();if(a.totalSize<=n||(await this.cleanupLowHitRate(),a=await this.getGlobalStats(),a.totalSize<=n))return this.calculateCleanupResult(i,a.totalSize);await this.cleanupLargeItems();let o=await this.getGlobalStats();return this.calculateCleanupResult(i,o.totalSize)}async cleanupExpired(){e.info(`Cleaning up expired data...`);for(let[t,n]of this.caches)if(n.cleanup)try{await n.cleanup(),e.debug(`Cleaned up expired data in ${t}`)}catch(n){e.error(`Failed to cleanup ${t}:`,n)}}async cleanupLowHitRate(){e.info(`Cleaning up low hit rate caches...`);let t=await this.getGlobalStats(),n=t.hitRate;for(let r of t.caches)if(r.hitRate!==void 0&&r.hitRate<n*this.LOW_HIT_RATE_THRESHOLD){let t=this.caches.get(r.name);if(t?.clear)try{await t.clear(),e.info(`Cleared low hit rate cache: ${r.name} (${(r.hitRate*100).toFixed(1)}%)`)}catch(t){e.error(`Failed to clear ${r.name}:`,t)}}}async cleanupLargeItems(){e.info(`Cleaning up large caches...`);let t=(await this.getGlobalStats()).caches.toSorted((e,t)=>t.size-e.size);for(let n of t.slice(0,2)){let t=this.caches.get(n.name);if(t?.clear)try{await t.clear(),e.info(`Cleared large cache: ${n.name} (${n.sizeMB}MB)`)}catch(t){e.error(`Failed to clear ${n.name}:`,t)}}}calculateCleanupResult(t,n){let r=t-n,i=Math.round(r/this.GLOBAL_MAX_SIZE*100);return e.info(`Cleanup complete! Freed ${(r/1024/1024).toFixed(2)}MB (${i}%). Usage: ${(n/1024/1024).toFixed(2)}MB/${(this.GLOBAL_MAX_SIZE/1024/1024).toFixed(0)}MB`),{before:t,after:n,freed:r,freedPercentage:i}}async clearAll(){e.info(`Clearing all caches...`);for(let[t,n]of this.caches)if(n.clear)try{await n.clear(),e.info(`Cleared cache: ${t}`)}catch(n){e.error(`Failed to clear ${t}:`,n)}e.success(`All caches cleared`)}async preheat(t){e.info(`Preheating cache for ${t.length} URLs...`),e.info(`Cache preheat completed`)}generateRecommendations(e,t,n){let r=[],i=e/this.GLOBAL_MAX_SIZE;i>=.9?r.push(` CRITICAL: Cache size at 90%. Run smart_cache_cleanup immediately!`):i>=.7?r.push(`WARNING: Cache size at 70%. Consider cleanup soon.`):i>=.5&&r.push(`INFO: Cache size at 50%. Monitor usage.`),t<.3?r.push(` Low cache hit rate (<30%). Consider adjusting TTL or cache strategy.`):t>.7&&r.push(` Good cache hit rate (>70%). Cache is working well.`);for(let t of n){let n=t.size/e;n>.5&&r.push(` ${t.name} uses ${Math.round(n*100)}% of total cache. Consider cleanup.`),t.hitRate!==void 0&&t.hitRate<.2&&r.push(` ${t.name} has low hit rate (${(t.hitRate*100).toFixed(1)}%). Consider disabling or adjusting.`)}return r.length===0&&r.push(` Cache health is good. No action needed.`),r}};function g(e=process.env){let t=Math.max(0,parseInt(e.MCP_ARTIFACT_RETENTION_DAYS??`0`,10)||0),n=Math.max(0,parseInt(e.MCP_ARTIFACT_MAX_TOTAL_MB??`0`,10)||0),r=Math.max(0,parseInt(e.MCP_ARTIFACT_CLEANUP_INTERVAL_MINUTES??`0`,10)||0),i=[`1`,`true`].includes((e.MCP_ARTIFACT_CLEANUP_ON_START??``).toLowerCase());return{enabled:t>0||n>0,retentionDays:t,maxTotalBytes:n*1024*1024,cleanupOnStart:i,cleanupIntervalMinutes:r}}async function _(e){let t=g(),n={...t,retentionDays:e?.retentionDays??t.retentionDays,maxTotalBytes:e?.maxTotalBytes??t.maxTotalBytes},r=e?.now??Date.now(),a=e?.dryRun??!1,o=e?.directories??y(),s=n.retentionDays>0?r-n.retentionDays*864e5:0,c=0,l=0,u=0,d=0,p=0,m=[],h=[],_=i(),v=[];function S(e){v.push(f(e,{force:!0}).then(()=>void 0).catch(()=>void 0))}for(let e of o)await b(e,_,s,a,e=>{c++,s>0&&e.mtimeMs<s?(l++,u+=e.size,d+=e.size,h.length<20&&h.push(e.relativePath),a||S(e.path)):m.push(e)});if(n.maxTotalBytes>0){let e=m.reduce((e,t)=>e+t.size,0);if(e>n.maxTotalBytes){m.sort((e,t)=>e.mtimeMs-t.mtimeMs);let t=0;for(;t<m.length&&e>n.maxTotalBytes;){let n=m[t];e-=n.size,l++,u+=n.size,p+=n.size,h.length<20&&h.push(n.relativePath),a||S(n.path),t++}m.splice(0,t)}}return a||(await Promise.all(v),await Promise.all(o.map(e=>x(e)))),{success:!0,scannedFiles:c,removedFiles:l,removedBytes:u,removedByAge:d,removedBySize:p,remainingFiles:m.length,remainingBytes:m.reduce((e,t)=>e+t.size,0),dryRun:a,directories:o,removedSample:h,config:n}}function v(){let t=g();if(!t.enabled||t.cleanupIntervalMinutes<=0)return null;let n=setInterval(()=>{_().then(t=>{t.removedFiles>0&&e.info(`[artifacts] retention cleanup removed ${t.removedFiles} files (${t.removedBytes} bytes)`)}).catch(t=>{e.warn(`[artifacts] retention cleanup failed`,t)})},t.cleanupIntervalMinutes*60*1e3);return n.unref(),()=>clearInterval(n)}function y(){let e=i(),t=u(process.cwd(),`debugger-sessions`),n=u(e,`debugger-sessions`),r=new Set([c(),a().paths.screenshotDir,o(),t,n]);for(let e of[`wasm`,`traces`,`profiles`,`dumps`,`reports`,`har`,`sessions`,`tmp`])r.add(s(e));return[...r]}async function b(e,t,n,r,i){let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=l(e,o.name);if(o.isDirectory())await b(a,t,n,r,i);else if(o.isFile()){let e;try{e=await p(a)}catch{continue}i({path:a,relativePath:S(t,a),size:e.size,mtimeMs:e.mtimeMs})}}}async function x(e){let t;try{t=await d(e,{withFileTypes:!0})}catch{return}await Promise.all(t.filter(e=>e.isDirectory()).map(t=>x(l(e,t.name))));try{(await d(e)).length===0&&await f(e,{recursive:!0,force:!0})}catch{}}function S(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^[\\/]/,``).replace(/\\/g,`/`):t.replace(/\\/g,`/`)}export{m as a,h as i,g as n,v as r,_ as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{i as t}from"./outputPaths-B4Ic4RZh.mjs";import{isAbsolute as n,normalize as r,relative as i,resolve as a,sep as o}from"node:path";import{mkdir as s}from"node:fs/promises";var c=e({getArtifactDir:()=>f,getArtifactsRoot:()=>d,resolveArtifactPath:()=>u});const l=`artifacts`;async function u(e){let{category:c,toolName:u,target:d,ext:f,customDir:m}=e,h=t(),g=m?a(h,m):a(h,l,c),_=i(r(h),r(g));if(_===`..`||_.startsWith(`..${o}`)||n(_))throw Error(`Path traversal blocked: artifact directory "${m}" escapes project root`);await s(g,{recursive:!0});let v=new Date().toISOString().replace(/[:.]/g,`-`).replace(`T`,`_`).slice(0,19),y=Math.random().toString(36).substring(2,8),b=a(g,`${p(u)}${d?`-${p(d)}`:``}-${v}-${y}.${f.replace(/^\./,``)}`);return{absolutePath:b,displayPath:i(h,b).replace(/\\/g,`/`)}}function d(){return a(t(),l)}function f(e){return a(t(),l,e)}function p(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_|_$/g,``).substring(0,60)}export{u as i,f as n,d as r,c as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e={allowedHosts:{type:`array`,items:{type:`string`},description:`Exact hostnames or IP literals allowed for this request.`},allowedCidrs:{type:`array`,items:{type:`string`},description:`Explicit CIDR ranges allowed for this request.`},allowPrivateNetwork:{type:`boolean`,description:`Allow access to private or reserved network targets, but only when the resolved host matches allowedHosts or allowedCidrs.`},allowInsecureHttp:{type:`boolean`,description:`Allow plain HTTP access to explicitly authorized targets in allowedHosts or allowedCidrs.`},expiresAt:{type:`string`,description:`Optional ISO-8601 expiry time for this authorization.`},reason:{type:`string`,description:`Short audit note describing why this authorization is needed.`}};export{e as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";const t=e(import.meta.url),n=`pnpm add -O better-sqlite3@12.10.0`,r=`npm rebuild better-sqlite3 --foreground-scripts`;function i(e){return e instanceof Error?e.message:String(e)}function a(e){return/better-sqlite3|better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version/i.test(i(e))}function o(e){let t=i(e);return/Cannot find module 'better-sqlite3'|Cannot find package 'better-sqlite3'|better-sqlite3 is not installed/i.test(t)?`missing`:/better_sqlite3\.node|NODE_MODULE_VERSION|compiled against a different Node\.js version|module was compiled against/i.test(t)?`abi-mismatch`:`load-failed`}function s(e){let t=o(e),a=i(e);return t===`missing`?`GRACEFUL: better-sqlite3 is not installed. Install the optional trace backend with \`${n}\`.`:t===`abi-mismatch`?`GRACEFUL: better-sqlite3 is installed but its native binary is incompatible with the current Node.js runtime (${process.version}, ABI ${process.versions.modules}). Rebuild it with \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`:`GRACEFUL: better-sqlite3 failed to initialize. Try \`${r}\` or reinstall dependencies under the active Node version. Original error: ${a}`}function c(){try{return t(t.resolve(`better-sqlite3/package.json`)).version??null}catch{return null}}function l(){let e=c();if(!e)return{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:null,issue:`missing`};try{let n=new(t(`better-sqlite3`))(`:memory:`);try{n.prepare(`SELECT 1 AS ok`).get()}finally{n.close()}return{status:`ok`,detail:`installed (${e}) — native trace backend healthy`,version:e}}catch(t){let r=o(t);return r===`missing`?{status:`missing`,detail:`GRACEFUL: Optional SQLite backend for trace tools is not installed. Install it with: ${n}`,version:e,issue:r}:{status:`warn`,detail:`installed (${e}) but ${s(t)}`,version:e,issue:r}}}export{a as n,l as r,s as t};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{gt as n,mt as r,ni as i}from"./constants-BYj8Xek8.mjs";import{t as a}from"./ToolError-DWU_z7gp.mjs";import{t as o}from"./ToolProbe-C7ZU2x7M.mjs";import{t as s}from"./PrerequisiteError-BjCQA-gK.mjs";import{tmpdir as c}from"node:os";import{randomUUID as l}from"node:crypto";import{basename as u,dirname as d,join as f}from"node:path";import{access as p,mkdtemp as m,readFile as h,rm as g,writeFile as _}from"node:fs/promises";import{execFile as v}from"node:child_process";var y=class{sessions=new Map;activeSessionId;fridaProbe;probePromise;async attach(e){let t=await this.getAvailability();if(!t.available)throw new s(t.reason??`Frida CLI is not available`);let n=await this.runFridaCommand(e,`console.log("__frida_attach_ok__");`);if(n.error)throw new a(`CONNECTION`,n.error);let r=l(),i={id:r,target:e,pid:this.resolvePid(e),status:`attached`,attachedAt:new Date().toISOString()};return this.sessions.set(r,i),this.activeSessionId=r,r}async detach(){let e=this.getActiveSessionRecord();e&&(e.status=`detached`,this.activeSessionId=void 0)}async executeScript(e){let t=this.requireActiveSession(),n=await this.runFridaCommand(t.target,e);return n.error&&(t.status=`error`,t.lastError=n.error),n}async enumerateModules(){let e=this.requireActiveSession(),t=await this.runFridaCommand(e.target,`console.log(JSON.stringify(Process.enumerateModules()));`),n=this.parseModuleList(t.output);return n.length>0?n:(t.error&&(e.status=`error`,e.lastError=t.error),[])}async enumerateFunctions(e){let t=this.requireActiveSession(),n=JSON.stringify(e),r=await this.runFridaCommand(t.target,[`const entries = Process.getModuleByName(${n}).enumerateExports()`,`.filter(function (entry) { return entry.type === "function"; })`,`.map(function (entry) {`,` return { name: entry.name, address: String(entry.address), size: 0 };`,`});`,`console.log(JSON.stringify(entries));`].join(``)),i=this.parseFunctionList(r.output);return i.length>0?i:(r.error&&(t.status=`error`,t.lastError=r.error),[])}async findSymbols(e){let t=this.requireActiveSession(),n=e.trim(),r=n.includes(`:`)?n:n.includes(`!`)?`exports:${n}`:`exports:*!${n}*`,i=JSON.stringify(r),a=await this.runFridaCommand(t.target,[`const resolver = new ApiResolver("module");`,`const matches = resolver.enumerateMatches(${i});`,`const mapped = matches.map(function (entry) {`,` const resolvedName = typeof entry.name === "string" ? entry.name : "unknown";`,` const resolvedAddress = entry.address ? String(entry.address) : "0x0";`,` return { name: resolvedName, address: resolvedAddress, demangled: resolvedName };`,`});`,`console.log(JSON.stringify(mapped));`].join(``)),o=this.parseSymbolList(a.output);return o.length>0?o:(a.error&&(t.status=`error`,t.lastError=a.error),[])}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,target:e.target,pid:e.pid,status:e.status}))}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.fridaProbe)return this.fridaProbe;this.probePromise||=o(`frida`);let e=await this.probePromise;return this.fridaProbe=e,this.probePromise=void 0,e}useSession(e){return this.sessions.has(e)?(this.activeSessionId=e,!0):!1}hasSession(e){return this.sessions.has(e)}getSessionDiagnostics(e){let t=this.sessions.get(e);if(t)return{status:t.status,lastError:t.lastError}}getActiveSessionRecord(){if(this.activeSessionId)return this.sessions.get(this.activeSessionId)}requireActiveSession(){let e=this.getActiveSessionRecord();if(!e)throw new s(`No active Frida session. Call attach() first.`);return e}resolvePid(e){if(!/^\d+$/.test(e))return null;let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}async runFridaCommand(e,n){let i=await this.getAvailability();if(!i.available)return{output:``,error:i.reason??`Frida CLI is not available`};let a=i.path??`frida`,o=[...this.buildTargetArgs(e),`--runtime=v8`,`-q`,`-e`,n];try{let e=await this.execFileUtf8(a,o,r),t=e.stdout.trim(),n=e.stderr.trim();return n?{output:t,error:n}:{output:t}}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Frida command failed`,{target:e,message:r}),{output:``,error:r}}}buildTargetArgs(e){return/^\d+$/.test(e)?[`-p`,e]:e.includes(`/`)||e.includes(`\\`)?[`-f`,e]:[`-n`,e]}parseModuleList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.readStringField(e,`path`),i=this.normalizeHex(e.base),a=this.readNumberField(e,`size`);!t||!r||!i||a===void 0||n.push({name:t,base:i,size:a,path:r})}return n}parseFunctionList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readNumberField(e,`size`)??0;!t||!r||n.push({name:t,address:r,size:i})}return n}parseSymbolList(e){let t=this.extractJsonPayload(e);if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!this.isRecord(e))continue;let t=this.readStringField(e,`name`),r=this.normalizeHex(e.address),i=this.readStringField(e,`demangled`);!t||!r||(i?n.push({name:t,address:r,demangled:i}):n.push({name:t,address:r}))}return n}extractJsonPayload(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.startsWith(`{`)||e.startsWith(`[`)).toReversed();for(let e of t)try{return JSON.parse(e)}catch{continue}}readStringField(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}readNumberField(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}normalizeHex(e){if(typeof e==`number`&&Number.isFinite(e))return`0x${e.toString(16)}`;if(typeof e==`string`&&e.length>0)return e.startsWith(`0x`)?e:`0x${e}`}isRecord(e){return typeof e==`object`&&!!e}execFileUtf8(e,t,n){return new Promise((r,i)=>{v(e,t,{timeout:n,windowsHide:!0,maxBuffer:5242880,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}},b=class{ghidraProbe;probePromise;async analyze(e,r){await p(e);let i=await h(e),a=this.extractPrintableStrings(i),o=this.deriveImports(a),s=this.deriveExports(a);if(!(await this.getAvailability()).available)return{functions:[],imports:o,exports:s,strings:a};let l=typeof r?.timeout==`number`&&Number.isFinite(r.timeout)?r.timeout:n,u=await m(f(c(),`jshook-ghidra-script-`)),d=f(u,`BinaryInstrumentDump.py`);try{await _(d,this.buildDefaultScript(),`utf8`);let t=await this.headlessAnalyze(d,e,l);return{functions:this.parseDecompiledOutput(t),imports:o,exports:s,strings:a}}catch(n){let r=n instanceof Error?n.message:String(n);return t.warn(`[binary-instrument] Ghidra analyze fallback`,{binaryPath:e,message:r}),{functions:[],imports:o,exports:s,strings:a}}finally{await g(u,{recursive:!0,force:!0})}}async headlessAnalyze(e,t,r=n){let i=await this.getAvailability();if(!i.available)throw new s(i.reason??`Ghidra analyzeHeadless is not available`);await p(t),await p(e);let a=i.path??`analyzeHeadless`,o=await m(f(c(),`jshook-ghidra-project-`));try{let n=await this.execFileUtf8(a,[o,`binary-instrument`,`-import`,t,`-scriptPath`,d(e),`-postScript`,u(e)],r);return[n.stdout.trim(),n.stderr.trim()].filter(e=>e.length>0).join(`
|
|
2
|
+
`)}finally{await g(o,{recursive:!0,force:!0})}}parseDecompiledOutput(e){let t=[],n=/FUNCTION_START\s*[\r\n]+NAME:(.+?)\s*[\r\n]+ADDRESS:(.+?)\s*[\r\n]+SIGNATURE:(.+?)\s*[\r\n]+DECOMPILED_START\s*[\r\n]+([\s\S]*?)\s*[\r\n]+DECOMPILED_END\s*[\r\n]+FUNCTION_END/g,r=n.exec(e);for(;r;){let i=r[1]??``,a=r[2]??``,o=r[3]??``,s=r[4]??``,c=i.trim(),l=this.normalizeHex(a.trim()),u=o.trim(),d=s.trim();c.length>0&&l.length>0&&u.length>0&&t.push({name:c,address:l,signature:u,decompiled:d}),r=n.exec(e)}return t}async isAvailable(){return(await this.getAvailability()).available}async getAvailability(){if(this.ghidraProbe)return this.ghidraProbe;this.probePromise||=o(`analyzeHeadless`,[`-help`]);let e=await this.probePromise;return this.ghidraProbe=e,this.probePromise=void 0,e}buildDefaultScript(){return[`# @category BinaryInstrument`,`from ghidra.app.decompiler import DecompInterface`,``,`program = currentProgram`,`interface = DecompInterface()`,`interface.openProgram(program)`,`function_manager = program.getFunctionManager()`,`functions = function_manager.getFunctions(True)`,``,`for function in functions:`,` print("FUNCTION_START")`,` print("NAME:" + str(function.getName()))`,` print("ADDRESS:" + str(function.getEntryPoint()))`,` try:`,` signature = str(function.getSignature())`,` except:`,` signature = str(function.getName()) + "()"`,` print("SIGNATURE:" + signature)`,` print("DECOMPILED_START")`,` try:`,` decompiled = interface.decompileFunction(function, 30, monitor).getDecompiledFunction()`,` if decompiled:`,` print(str(decompiled.getC()))`,` else:`,` print("// no decompiled output")`,` except:`,` print("// decompile failed")`,` print("DECOMPILED_END")`,` print("FUNCTION_END")`].join(`
|
|
3
|
+
`)}extractPrintableStrings(e){let t=[],n=``;for(let r of e.values()){if(r>=32&&r<=126){n+=String.fromCharCode(r);continue}n.length>=4&&t.push(n),n=``}return n.length>=4&&t.push(n),Array.from(new Set(t)).slice(0,1e3)}deriveImports(e){return e.filter(e=>/(?:\.dll|\.so|\.dylib|kernel32|user32|libc|printf|malloc|LoadLibrary)/i.test(e)).slice(0,100)}deriveExports(e){return e.filter(e=>/^[A-Za-z_][A-Za-z0-9_@?$]{2,}$/.test(e)).slice(0,100)}normalizeHex(e){return e.startsWith(`0x`)?e:`0x${e}`}execFileUtf8(e,t,n){return new Promise((r,i)=>{v(e,t,{timeout:n,windowsHide:!0,maxBuffer:16777216,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}},x=class{generateHooks(e){let t=[];for(let n of e.functions){let r=this.classifyFunction(n,e);r!==`unknown`&&t.push({functionName:n.name,description:this.describeCategory(r,e),hookCode:this.buildHookCode(n,r),parameters:this.buildParameters(n)})}return t}exportScript(e,t){if(t!==`frida`)throw new a(`VALIDATION`,`Unsupported export format: "${t}". Only "frida" is supported.`);let n=[`// Frida hook script`,`// auto-generated by HookCodeGenerator`,`// Hook count: ${e.length}`,``];for(let t of e)n.push(`// ${t.functionName}: ${t.description}`),n.push(t.hookCode),n.push(``);return n.join(`
|
|
4
|
+
`)}classifyFunction(e,t){let n=e.name.toLowerCase(),r=t.imports.map(e=>e.toLowerCase()),i=t.strings.map(e=>e.toLowerCase());return e.name.startsWith(`Java_`)?`jni`:n.includes(`aes`)?`aes`:n.includes(`md5`)?`md5`:n.includes(`sha`)?`sha`:n.includes(`rsa`)?`rsa`:n.includes(`base64`)?`base64`:n.includes(`send`)||n.includes(`recv`)||n.includes(`socket`)||n.includes(`http`)?`network`:n.includes(`open`)||n.includes(`read`)||n.includes(`write`)||n.includes(`fopen`)?`file-io`:(n.includes(`decrypt`)||n.includes(`encrypt`))&&i.some(e=>e.includes(`obfuscation`)||e.includes(`encryption`))?`obfuscation`:n.includes(`memcpy`)||n.includes(`strcpy`)||n.includes(`memmove`)||n.includes(`string`)?`string`:r.some(e=>e.includes(`aes`))?`aes`:`unknown`}describeCategory(e,t){switch(e){case`jni`:return`JNI bridge hook for Java/native boundary inspection`;case`aes`:return`AES crypto hook for key/plaintext capture`;case`md5`:return`MD5 crypto hook for digest inspection`;case`sha`:return`SHA crypto hook for digest inspection`;case`rsa`:return`RSA crypto hook for key operation tracing`;case`base64`:return`Base64 transform hook for encoded payload tracing`;case`network`:return`Network hook for request and payload tracing`;case`file-io`:return`File I/O hook for filesystem access tracing`;case`string`:return`String operation hook for buffer tracing`;case`obfuscation`:return t.strings.some(e=>e.toLowerCase().includes(`obfuscation`))?`Potential obfuscation hook for runtime string decryption tracing`:`Potential obfuscation hook`;case`unknown`:return`Unknown hook`}}buildHookCode(e,t){if(t===`jni`)return[`Java.perform(function () {`,` const target = ptr("${e.address}");`,` Interceptor.attach(target, {`,` onEnter(args) {`,` console.log("[jni] ${e.name}");`,` },`,` });`,`});`].join(`
|
|
5
|
+
`);let n=t===`aes`||t===`md5`||t===`sha`||t===`rsa`||t===`base64`?` console.log(hexdump(args[0]));`:` console.log("[trace] entering");`,r=e.name.replace(/[^A-Za-z0-9_]/g,`_`);return[`const target_${r} = ptr("${e.address}");`,`Interceptor.attach(target_${r}, {`,` onEnter(args) {`,` console.log("[hook] ${e.name}");`,n,` },`,`});`].join(`
|
|
6
|
+
`)}buildParameters(e){return e.parameters.length>0?e.parameters.map((e,t)=>({name:e.name||`arg${t}`,type:e.type||`pointer`,description:`Captured parameter ${t}`})):[{name:`arg0`,type:`pointer`,description:`Captured parameter 0`}]}};async function S(e,t){let n=C(e),r=w(t.pluginId),i=T(r,n);if(!i)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${r} is not installed`};let a=E(e,i);if(!a?.lifecycleContext)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin ${i} is installed but has no runtime`};try{let e=(await a.lifecycleContext.invokeTool(t.toolName,t.args)).content?.find(e=>e.type===`text`)?.text;if(!e)return{success:!1,tool:`binary-instrument`,action:t.toolName,error:`Plugin returned no text content`};try{let n=JSON.parse(e);if(O(n))return{tool:`binary-instrument`,action:t.toolName,success:k(n,`success`)??!0,data:n.data,error:A(n,`error`)}}catch{return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}return{success:!0,tool:`binary-instrument`,action:t.toolName,data:e}}catch(e){return{success:!1,tool:`binary-instrument`,action:t.toolName,error:e instanceof Error?e.message:String(e)}}}function C(e){return Array.from(e.extensionPluginsById.keys()).map(w)}function w(e){return e.replaceAll(`_`,`-`)}function T(e,t){let n=e.replace(/^plugin-/,``);for(let r of t){let t=r.replace(/^plugin-/,``);if(r===e||t===n)return r}}function E(e,t){for(let[n,r]of e.extensionPluginRuntimeById.entries())if(w(n)===t)return D(r)?r:void 0}function D(e){return typeof e==`object`&&!!e}function O(e){return typeof e==`object`&&!!e}function k(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function A(e,t){let n=e[t];return typeof n==`string`?n:void 0}var j=class{generateFridaHookScript(e,t){let n=t?.includeArgs??!0,r=t?.includeRetAddr??!1,i=[`'use strict';`,``,`function resolveTarget(name) {`,` try {`,` const exported = Module.findExportByName(null, name);`,` if (exported) {`,` return exported;`,` }`,` } catch (error) {}`,` try {`,` const symbol = DebugSymbol.fromName(name);`,` if (symbol && symbol.address) {`,` return symbol.address;`,` }`,` } catch (error) {}`,` return null;`,`}`,``,`const installedHooks = [];`];for(let t=0;t<e.length;t+=1){let a=this.toDescriptor(e[t]),o=`target_${t}`,s=a.demangled??a.name,c=a.address?`const ${o} = ptr("${this.escapeForDoubleQuotes(a.address)}");`:`const ${o} = resolveTarget("${this.escapeForDoubleQuotes(a.name)}");`;i.push(c),i.push(`if (${o}) {`),i.push(` Interceptor.attach(${o}, {`),i.push(` onEnter(args) {`),r?i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)} ret=" + this.returnAddress);`):i.push(` console.log("[binary-instrument] enter ${this.escapeForDoubleQuotes(s)}");`),n&&(i.push(` const renderedArgs = [];`),i.push(` for (let i = 0; i < 6; i += 1) {`),i.push(` try {`),i.push(` renderedArgs.push(String(args[i]));`),i.push(` } catch (error) {`),i.push(` renderedArgs.push("<unreadable>");`),i.push(` }`),i.push(` }`),i.push(` console.log("[binary-instrument] args " + JSON.stringify(renderedArgs));`)),i.push(` },`),i.push(` onLeave(retval) {`),i.push(` console.log("[binary-instrument] leave ${this.escapeForDoubleQuotes(s)} retval=" + retval);`),i.push(` },`),i.push(` });`),i.push(` installedHooks.push({ name: "${this.escapeForDoubleQuotes(s)}", address: String(${o}) });`),i.push(`} else {`),i.push(` console.log("[binary-instrument] unresolved ${this.escapeForDoubleQuotes(s)}");`),i.push(`}`),i.push(``)}return i.push(`console.log("[binary-instrument] hooks=" + JSON.stringify(installedHooks));`),i.join(`
|
|
7
|
+
`)}generateInterceptorScript(e){return this.generateFridaHookScript(e,{includeArgs:!0,includeRetAddr:!1})}toDescriptor(e){return typeof e==`string`?{name:e}:e}escapeForDoubleQuotes(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}},M=class{sessions=new Map;close(){for(let e of this.sessions.values())if(e.childProcess)try{process.kill(e.childProcess.pid,`SIGTERM`)}catch{}this.sessions.clear()}async launch(e,n=`arm`,r){let o=r??process.env.UNIDBG_JAR;if(!o)throw new s(`UNIDBG_JAR is not configured. Set the UNIDBG_JAR env var or pass jarPath.`);try{await p(o)}catch{throw new a(`NOT_FOUND`,`Unidbg JAR not found: ${o}`)}try{await p(e)}catch{throw new a(`NOT_FOUND`,`Shared library not found: ${e}`)}let c=l(),u=this.getJavaCommand(),d=[`-jar`,o,`--so`,e,`--arch`,n,`--server`];try{let t=await this.execFileUtf8(u,d,i),r=this.parseLaunchOutput(t.stdout,c),a={id:r.id,soPath:e,arch:n,startedAt:new Date().toISOString(),childProcess:r.pid?{pid:r.pid}:void 0};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}catch(r){let i=r instanceof Error?r.message:String(r);t.warn(`[binary-instrument] Unidbg launch failed, registering stub session`,{soPath:e,message:i});let a={id:c,soPath:e,arch:n,startedAt:new Date().toISOString()};return this.sessions.set(c,a),{sessionId:c,soPath:e,arch:n}}}async callFunction(e,t,n={}){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let r=process.env.UNIDBG_JAR;if(!r)return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:``,trace:[`mock-unidbg-unavailable`],_note:`Unidbg emulation requires UNIDBG_JAR to be configured`};let o=this.getJavaCommand(),s=[`-jar`,r,`--session`,e,`--call`,t,`--args`,JSON.stringify(n)];try{let r=await this.execFileUtf8(o,s,i);return{sessionId:e,functionName:t,args:n,returnValue:this.extractReturnValue(r.stdout),stdout:r.stdout.trim(),stderr:r.stderr.trim(),trace:[]}}catch(r){return{sessionId:e,functionName:t,args:n,returnValue:`0x0`,stdout:``,stderr:r instanceof Error?r.message:String(r),trace:[`error`]}}}async trace(e){if(!this.sessions.get(e))throw new a(`NOT_FOUND`,`No unidbg session found for ${e}`);let t=process.env.UNIDBG_JAR;if(!t)return{sessionId:e,trace:[`mock-unidbg-unavailable`],_note:`Unidbg tracing requires UNIDBG_JAR to be configured`};let n=this.getJavaCommand(),r=[`-jar`,t,`--session`,e,`--trace`];try{let t=await this.execFileUtf8(n,r,i);return{sessionId:e,trace:this.parseTraceOutput(t.stdout),instructionCount:this.countInstructions(t.stdout)}}catch(t){return{sessionId:e,trace:[`error`],error:t instanceof Error?t.message:String(t)}}}getSessionInfo(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values()).map(e=>({id:e.id,soPath:e.soPath,arch:e.arch,startedAt:e.startedAt}))}getJavaCommand(){return process.env.JAVA_HOME?`${process.env.JAVA_HOME}/bin/java`:`java`}parseLaunchOutput(e,t){let n=e.split(/\r?\n/).filter(e=>e.trim().length>0);for(let e of n.toReversed())try{let t=JSON.parse(e);if(typeof t.id==`string`)return{id:t.id,pid:typeof t.pid==`number`?t.pid:null}}catch{}return{id:t,pid:null}}extractReturnValue(e){let t=/return[=:\s]+(0x[0-9a-fA-F]+|-?\d+)/.exec(e);return t?.[1]?t[1]:`0x0`}parseTraceOutput(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)).slice(0,1e4)}countInstructions(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`{`)&&/\b(ldr|str|mov|bl|b|add|sub)\b/i.test(e)).length}async execFileUtf8(e,t,n){return new Promise((r,i)=>{v(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``,exitCode:0})})})}},N=e({GhidraAnalyzer:()=>b,HookGenerator:()=>j});export{S as a,y as c,C as i,M as n,x as o,j as r,b as s,N as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t,r as n,s as r,t as i}from"./parse-args-Bw413PlW.mjs";import{n as a}from"./ResponseBuilder-BfWP-uaT.mjs";import"./definitions-Bio5XJYy.mjs";import{createReadStream as o}from"node:fs";import{stat as s}from"node:fs/promises";import{Buffer as c}from"node:buffer";const l=(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},u=((e,t)=>{let n=process.env[e];if(n===void 0||n===``)return t;let r=n.split(`,`).map(e=>parseInt(e.trim(),10)).filter(e=>Number.isFinite(e)&&e>0);return r.length>0?r:t})(`BINARY_SECRETS_DEFAULT_KEY_LENGTHS`,[16,24,32,64]),d=l(`BINARY_SECRETS_MAX_RESULTS`,500),f=l(`BINARY_SECRETS_MIN_ENTROPY_X10`,70);l(`BINARY_SECRETS_REGEX_TIMEOUT_MS`,50);const p=l(`BINARY_SECRETS_MAX_CHUNK_BYTES`,16*1024*1024),m=l(`BINARY_SECRETS_CHUNK_OVERLAP_BYTES`,1024),h=l(`BINARY_SECRETS_CONTEXT_BYTES`,16),g=l(`BINARY_SECRETS_VALUE_PREVIEW_BYTES`,256),_=l(`BINARY_SECRETS_MIN_BASE64_LENGTH`,24),v=l(`BINARY_SECRETS_MAX_BASE64_LENGTH`,1024),y=l(`BINARY_SECRETS_MIN_HEX_LENGTH`,32),b=l(`BINARY_SECRETS_MAX_HEX_LENGTH`,1024),x=l(`BINARY_SECRETS_MAX_EXTRACT_DURATION_MS`,6e4);function S(e,t,n){if(n<=0)return 0;let r=t+n;if(r>e.length)return 0;let i=new Uint32Array(256);for(let n=t;n<r;n++)i[e[n]]=i[e[n]]+1>>>0;let a=1/n,o=0;for(let e=0;e<256;e++){let t=i[e];if(t===0)continue;let n=t*a;o-=n*Math.log2(n)}return o>8?8:o<0?0:o}function*C(e,t){if(t<=0||t>e.length)return;let n=new Uint32Array(256);for(let r=0;r<t;r++)n[e[r]]=n[e[r]]+1>>>0;yield[0,w(n,t)];for(let r=t;r<e.length;r++){let i=e[r-t],a=e[r];n[i]=n[i]-1>>>0,n[a]=n[a]+1>>>0,yield[r-t+1,w(n,t)]}}function w(e,t){let n=1/t,r=0;for(let t=0;t<256;t++){let i=e[t];if(i===0)continue;let a=i*n;r-=a*Math.log2(a)}return r>8?8:r<0?0:r}const T=p;var E=class{async extractFromFile(t,n={}){if(typeof t!=`string`||t.length===0)throw new e(`VALIDATION`,`filePath must be a non-empty string`);let r=0;try{r=(await s(t)).size}catch(n){throw new e(`NOT_FOUND`,`File not found: ${t}`,{details:{filePath:t},cause:n})}let i=D(n),a=performance.now(),l=Math.max(0,Math.min(i.scanWindowStart,r)),u=Math.max(l,Math.min(i.scanWindowEnd,r)),d=u-l,f=[],p=new Set;if(d===0)return{candidates:[],scannedBytes:0,durationMs:performance.now()-a};let m=c.alloc(0),h=l,g=l,_=o(t,{highWaterMark:i.maxChunkBytes,start:l,end:u-1});for await(let t of _){if(performance.now()-a>x)throw new e(`TIMEOUT`,`binary_key_extract exceeded BINARY_SECRETS_MAX_EXTRACT_DURATION_MS (${x} ms)`);let n=t,r=m.length===0?n:c.concat([m,n]);O(r,h,i,e=>{let t=`${e.format}@${e.absOffset}:${e.length}`;p.has(t)||(p.add(t),f.push(e))}),g+=n.length;let o=Math.min(r.length,i.overlapBytes);m=c.from(r.subarray(r.length-o)),h=g-o}let v=f.map(e=>({hit:e,entropy:S(e.bytes,0,e.length)}));v.sort((e,t)=>e.entropy===t.entropy?e.hit.absOffset-t.hit.absOffset:t.entropy-e.entropy);let y=v.length>i.maxResults;return{candidates:await P(t,y?v.slice(0,i.maxResults):v,i,r),scannedBytes:d,durationMs:performance.now()-a,...y?{truncated:!0}:{}}}};function D(t){let n=(()=>{if(!t.keyLengths)return u;if(!Array.isArray(t.keyLengths))throw new e(`VALIDATION`,`keyLengths must be an array of positive integers`);let n=t.keyLengths.map(t=>{if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new e(`VALIDATION`,`keyLengths entries must be positive integers (got ${String(t)})`);return t}).filter((e,t,n)=>n.indexOf(e)===t);if(n.length===0)throw new e(`VALIDATION`,`keyLengths must contain at least one positive integer`);return n})(),r=(()=>{if(t.minEntropy===void 0)return f/10;if(typeof t.minEntropy!=`number`||!Number.isFinite(t.minEntropy))throw new e(`VALIDATION`,`minEntropy must be a finite number in [0, 8]`);if(t.minEntropy<0||t.minEntropy>8)throw new e(`VALIDATION`,`minEntropy must be in [0, 8] (got ${t.minEntropy})`);return t.minEntropy})(),i=new Set(t.formats??[`raw`,`base64`,`hex`]);for(let t of i)if(t!==`raw`&&t!==`base64`&&t!==`hex`)throw new e(`VALIDATION`,`Invalid formats entry: "${t}". Expected one of: raw, base64, hex`);let a=t.includeContext??!0,o=(()=>{if(t.contextBytes===void 0)return h;if(typeof t.contextBytes!=`number`||!Number.isInteger(t.contextBytes)||t.contextBytes<0||t.contextBytes>1024)throw new e(`VALIDATION`,`contextBytes must be an integer in [0, 1024] (got ${String(t.contextBytes)})`);return t.contextBytes})(),s=(()=>{if(t.maxResults===void 0)return d;if(typeof t.maxResults!=`number`||!Number.isInteger(t.maxResults)||t.maxResults<=0)throw new e(`VALIDATION`,`maxResults must be a positive integer (got ${String(t.maxResults)})`);return t.maxResults})(),c=Math.max(t.maxChunkBytes??T,8192),l=Math.min(m,c-1),p=t.scanWindow?.start??0,g=t.scanWindow?.end??2**53-1;if(!Number.isFinite(p)||!Number.isFinite(g)||p<0||g<=p)throw new e(`VALIDATION`,`scanWindow must satisfy 0 <= start < end (got start=${p}, end=${g})`);return{keyLengths:n,maxRawWindow:Math.max(...n),minRawWindow:Math.min(...n),minEntropy:r,formats:i,includeContext:a,contextBytes:o,maxResults:s,maxChunkBytes:c,overlapBytes:l,scanWindowStart:p,scanWindowEnd:g}}function O(e,t,n,r){if(n.formats.has(`raw`)){for(let i of n.keyLengths)if(!(i>e.length))for(let[a,o]of C(e,i)){if(o<n.minEntropy)continue;let s=e.subarray(a,a+i);r({absOffset:t+a,length:i,format:`raw`,bytes:Uint8Array.from(s)})}}if(n.formats.has(`base64`))for(let i of j(e,t,n))r(i);if(n.formats.has(`hex`))for(let i of M(e,t,n))r(i)}function k(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47}function A(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function*j(e,t,n){let r=_,i=v,a=new Set(n.keyLengths),o=-1;for(let n=0;n<=e.length;n++){let s=n<e.length?e[n]:-1;if(s!==-1&&k(s)){o===-1&&(o=n);continue}if(o===-1)continue;let l=o;o=-1;let u=n,d=0;for(;d<2&&u<e.length&&e[u]===61;)u++,d++;let f=u-l;if(f<r||f>i||N(e,l,f)<5)continue;let p=e.subarray(l,u),m;try{m=c.from(p.toString(`ascii`),`base64`)}catch{continue}m.length!==0&&a.has(m.length)&&(yield{absOffset:t+l,length:m.length,format:`base64`,bytes:Uint8Array.from(m)})}}function*M(e,t,n){let r=y,i=b,a=new Set(n.keyLengths),o=-1;for(let n=0;n<=e.length;n++){let s=n<e.length?e[n]:-1;if(s!==-1&&A(s)){o===-1&&(o=n);continue}if(o===-1)continue;let l=n-o;l%2==1&&--l;let u=o;if(o=-1,l<r||l>i)continue;let d=l/2;if(!a.has(d))continue;let f=e.subarray(u,u+l),p=c.from(f.toString(`ascii`),`hex`);p.length===d&&(yield{absOffset:t+u,length:d,format:`hex`,bytes:Uint8Array.from(p)})}}function N(e,t,n){let r=new Uint8Array(256),i=0;for(let a=t;a<t+n;a++){let t=e[a];r[t]===0&&(r[t]=1,i++)}return i}async function P(e,t,n,r){let i=[];for(let{hit:a,entropy:o}of t){let t=Math.min(a.length,g),s=c.from(a.bytes.subarray(0,t)).toString(`hex`),l={offset:a.absOffset,length:a.length,format:a.format,entropy:o,value:s,...a.length>t?{valueTruncated:!0}:{},...n.includeContext?{context:await F(e,a,n.contextBytes,r)}:{}};i.push(l)}return i}async function F(e,t,n,r){if(n===0)return{before:``,after:``,beforeAscii:``,afterAscii:``};let i=t.format===`hex`?t.length*2:t.format===`base64`?Math.ceil(t.length/3)*4:t.length,a=Math.max(0,t.absOffset-n),o=t.absOffset,s=Math.min(r,t.absOffset+i),c=Math.min(r,s+n),l=await I(e,a,o),u=await I(e,s,c);return{before:l.toString(`hex`),after:u.toString(`hex`),beforeAscii:L(l),afterAscii:L(u)}}async function I(e,t,n){if(n<=t)return c.alloc(0);let r=[],i=o(e,{start:t,end:n-1});for await(let e of i)r.push(e);return c.concat(r)}function L(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];t+=r>=32&&r<=126?String.fromCharCode(r):`.`}return t}const R=new Set([`raw`,`base64`,`hex`]);function z(t){if(t==null)return;if(!Array.isArray(t))throw new e(`VALIDATION`,`keyLengths must be an array of positive integers`);let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(typeof i!=`number`||!Number.isFinite(i)||!Number.isInteger(i)||i<=0)throw new e(`VALIDATION`,`keyLengths[${r}] must be a positive integer (got ${String(i)})`);n.push(i)}return n}function B(t){if(t==null)return;if(!Array.isArray(t))throw new e(`VALIDATION`,`formats must be an array of strings`);let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(typeof i!=`string`||!R.has(i))throw new e(`VALIDATION`,`formats[${r}] must be one of: raw, base64, hex (got ${String(i)})`);n.push(i)}return n}var V=class{extractor;constructor(e=new E){this.extractor=e}handleBinaryKeyExtract(e){return a(async()=>{let a=r(e,`filePath`),o={},s=z(e.keyLengths);s!==void 0&&(o.keyLengths=s);let c=n(e,`minEntropy`);c!==void 0&&(o.minEntropy=c);let l=B(e.formats);l!==void 0&&(o.formats=l);let u=i(e,`includeContext`);u!==void 0&&(o.includeContext=u);let d=n(e,`contextBytes`);d!==void 0&&(o.contextBytes=d);let f=n(e,`maxResults`);f!==void 0&&(o.maxResults=f);let p=n(e,`maxChunkBytes`);p!==void 0&&(o.maxChunkBytes=p);let m=t(e,`scanWindow`);return m!==void 0&&(o.scanWindow={start:typeof m.start==`number`?m.start:void 0,end:typeof m.end==`number`?m.end:void 0}),{result:await this.extractor.extractFromFile(a,o)}})}};export{V as BinarySecretsHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e,t){let n=e[t];if(!n)throw Error(`[registry] Missing dependency: "${t}". Is the domain enabled?`);return n}function t(t,n){return r=>i=>n(e(r,t),i)}function n(e,n,r){return t(e,async(e,t)=>{let i=e[n],a=r?.mapArgs?r.mapArgs(t):[t],o=await i.apply(e,a);return r?.wrapResult?r.wrapResult(o):o})}function r(e){let{domain:t,depKey:r,lookup:i,entries:a,wrapResult:o}=e;return a.map(e=>({tool:i(e.tool),domain:t,...e.profiles?{profiles:e.profiles}:{},bind:`mapArgs`in e?n(r,e.method,{wrapResult:o,mapArgs:e.mapArgs}):n(r,e.method,{wrapResult:o})}))}export{r as n,t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{a as t}from"./outputPaths-B4Ic4RZh.mjs";import{createDecipheriv as n,randomUUID as r}from"node:crypto";import{existsSync as i,readFileSync as a}from"node:fs";import{dirname as o,resolve as s}from"node:path";import{mkdir as c,writeFile as l}from"node:fs/promises";function u(e){return e.replace(/\s+/g,``).toUpperCase()}function d(e){return e.length>0&&e.length%2==0&&/^[0-9A-F]+$/i.test(e)}function f(e){if(!e)return;let t=new Date(e);if(!Number.isNaN(t.valueOf()))return t.toISOString()}function p(){return s(t(),`jshook-boringssl-${r()}.log`)}function m(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(e.length===0||e.startsWith(`#`))continue;let r=e.split(/\s+/),i=r[0],a=r[1],o=r[2],s=f(r[3]);if(!i||!a||!o)continue;let c=u(a),l=u(o);if(!d(c)||!d(l))continue;let p={label:i,clientRandom:c,secret:l};s&&(p.timestamp=s),t.push(p)}return t}var h=class{keyLogPath;cachedEntries=[];secretByClientRandom=new Map;constructor(e){this.keyLogPath=s(e??p())}async enableKeyLog(){return await c(o(this.keyLogPath),{recursive:!0}),await l(this.keyLogPath,``,{flag:`a`}),process.env.SSLKEYLOGFILE=this.keyLogPath,this.keyLogPath}async disableKeyLog(){if(process.env.SSLKEYLOGFILE===this.keyLogPath){delete process.env.SSLKEYLOGFILE;return}delete process.env.SSLKEYLOGFILE}getKeyLogFilePath(){return this.keyLogPath}parseKeyLog(e){let t=s(e??this.keyLogPath);if(!i(t))return this.cachedEntries=[],this.secretByClientRandom.clear(),[];let n=m(a(t,`utf8`));this.cachedEntries=n,this.secretByClientRandom.clear();for(let e of n)this.secretByClientRandom.set(e.clientRandom,e.secret);return n}decryptPayload(e,t){let n=u(e);if(!d(n)||t.length===0||!t.some(e=>e.secret.length>0))return null;try{return Buffer.from(n,`hex`)}catch{return null}}summarizeKeyLog(e){let t=this.parseKeyLog(e),n={},r=[];for(let e of t)n[e.label]=(n[e.label]??0)+1,e.timestamp&&r.push(e.timestamp);r.sort((e,t)=>e.localeCompare(t));let i={totalEntries:t.length,entriesByLabel:n};if(r.length>0){let e=r[0],t=r[r.length-1];e&&(i.firstSeen=e),t&&(i.lastSeen=t)}return i}lookupSecret(e){let t=u(e),n=this.secretByClientRandom.get(t);if(n)return n;for(let e of this.cachedEntries.length>0?this.cachedEntries:this.parseKeyLog())if(e.clientRandom===t)return e.secret;return null}};function g(e=`/tmp/sslkeylog.log`){return process.env.SSLKEYLOGFILE=e,e}function _(){delete process.env.SSLKEYLOGFILE}function v(){let e=process.env.SSLKEYLOGFILE;return!e||e.trim().length===0?null:e}function y(e){return e.length===0?[]:e.includes(`
|
|
2
|
+
`)||e.includes(`\r`)||e.includes(`CLIENT_`)||e.trim().startsWith(`#`)?m(e):new h(e).parseKeyLog()}function b(e){let t=[...new Set(e.map(e=>e.label))],n=new Set(e.map(e=>e.clientRandom)).size,r=e.some(e=>e.label.includes(`TRAFFIC_SECRET`));return{totalEntries:e.length,uniqueClients:n,hasClientRandom:t.includes(`CLIENT_RANDOM`),hasTrafficSecrets:r,labels:t}}function x(e,t,n){let r=u(t),i=n?.trim();for(let t of e)if(t.clientRandom===r&&!(i&&t.label!==i))return t.secret;return null}function S(e,t,r,i=`aes-256-gcm`,a){try{let o=Buffer.from(u(e),`hex`),s=n(i,Buffer.from(u(t),`hex`),Buffer.from(u(r),`hex`));if(a){let e=Reflect.get(s,`setAuthTag`);typeof e==`function`&&e.call(s,Buffer.from(u(a),`hex`))}return Buffer.concat([s.update(o),s.final()]).toString(`utf8`)}catch{return`DECRYPTION_FAILED:${i}`}}var C=e({TLSKeyLogExtractor:()=>h});export{g as a,y as c,_ as i,b as l,h as n,v as o,S as r,x as s,C as t};
|