@jshookmcp/jshook 0.3.1 → 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 +11 -3
- package/README.zh.md +11 -3
- package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-B6d4Qe9D.mjs} +1 -1
- package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
- package/dist/{CodeInjector-BlgyqTOk.mjs → CodeInjector-Cll_7bLJ.mjs} +1 -1
- package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
- package/dist/DOMInspector-C19J4zeq.mjs +95 -0
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
- package/dist/ExtensionManager-BD724zkO.mjs +1 -0
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
- package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-BUfPdp0f.mjs} +1 -1
- package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-B_aqY8oj.mjs} +1 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
- package/dist/MemoryController-X1XNSn1n.mjs +2 -0
- package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-DG_F-PjE.mjs} +1 -1
- package/dist/{MemoryScanner-BLYnMJy6.mjs → MemoryScanner-g1_L1ub5.mjs} +1 -1
- package/dist/{NativeMemoryManager.impl-CI554XbY.mjs → NativeMemoryManager.impl-DniBe2wf.mjs} +1 -1
- package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-BHy1P_jM.mjs} +1 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
- package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-yWQaGrcx.mjs} +1 -1
- package/dist/PageController-Dfsm1_o7.mjs +1 -0
- package/dist/{PointerChainEngine-5nF9eNlu.mjs → PointerChainEngine-BhCUkmxY.mjs} +1 -1
- package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
- package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-BfWP-uaT.mjs} +1 -1
- package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
- package/dist/{ScriptManager-fgqiALgj.mjs → ScriptManager-LWGPTdvD.mjs} +1 -1
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
- package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-yseDPSZ9.mjs} +1 -1
- package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-C5lpuZkg.mjs} +1 -1
- package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
- package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
- package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
- package/dist/{ToolRouter.policy-CFHoN_Lw.mjs → ToolRouter.policy-CfhJczkt.mjs} +2 -2
- package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-BiJWBXHX.mjs} +1 -1
- package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-CYrIQBvr.mjs} +1 -1
- package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-D876meOO.mjs} +1 -1
- package/dist/analysis-D4swdMvq.mjs +6 -0
- package/dist/{antidebug-BOTZH6-0.mjs → antidebug-7L3ygj_9.mjs} +4 -4
- package/dist/apk-packer-BqXcInnX.mjs +1 -0
- package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-BCPQASm7.mjs} +1 -1
- package/dist/{artifacts-B5xQuEa_.mjs → artifacts-CkodUM4j.mjs} +1 -1
- package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
- package/dist/{binary-instrument-Cf9qqLlM.mjs → binary-instrument-DU7V6TUM.mjs} +1 -1
- package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
- package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-BBaJwwkU.mjs} +1 -1
- package/dist/browser-Qqco2rOT.mjs +11 -0
- package/dist/collector-Bpl6qy2L.mjs +1 -0
- package/dist/constants-BYj8Xek8.mjs +1 -0
- package/dist/{coordination-BbijHEHH.mjs → coordination-CWXW1o8K.mjs} +1 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/{debugger-CRJq_krh.mjs → debugger-DyALjYMk.mjs} +1 -1
- package/dist/{definitions-DZ8uKusP.mjs → definitions-BWxBke3r.mjs} +1 -1
- package/dist/{definitions-CYFbewnd.mjs → definitions-BYwATKc-.mjs} +1 -1
- package/dist/{definitions-DJklW2sS.mjs → definitions-B_83XfNQ.mjs} +1 -1
- package/dist/definitions-Bf3H1EwV.mjs +1 -0
- package/dist/{definitions-BGobEDQa.mjs → definitions-BftdXgXI.mjs} +1 -1
- package/dist/definitions-Bio5XJYy.mjs +1 -0
- package/dist/definitions-C3qNgSn1.mjs +1 -0
- package/dist/{definitions-NoVp_9Pm.mjs → definitions-CB6vmOer.mjs} +1 -1
- package/dist/{definitions-CoQFbggH.mjs → definitions-CMZRSy3k.mjs} +1 -1
- package/dist/{definitions-DI9YXsJk.mjs → definitions-CQd7yCQH.mjs} +1 -1
- package/dist/{definitions-CIO9O-Sw.mjs → definitions-CT8ln6GQ.mjs} +1 -1
- package/dist/{definitions-BGwNSkVm.mjs → definitions-Cenu6mxo.mjs} +1 -1
- package/dist/definitions-D4g-MS10.mjs +1 -0
- package/dist/{definitions-CuJRsJ6N.mjs → definitions-D5wl_8HN.mjs} +1 -1
- package/dist/{definitions-jXPaVy4P.mjs → definitions-DAQm1Xar.mjs} +1 -1
- package/dist/definitions-DP1vgxEY.mjs +1 -0
- package/dist/{definitions-Dds_zrWx.mjs → definitions-DxFNRQNK2.mjs} +1 -1
- package/dist/{definitions-DtE0XLrT.mjs → definitions-Ibci7e_L.mjs} +1 -1
- package/dist/{definitions-CCP9gphV.mjs → definitions-OeLvmlQy.mjs} +1 -1
- package/dist/{definitions-BbxOUiP-.mjs → definitions-RZYGD_Ey.mjs} +1 -1
- package/dist/definitions-Tls8c0A0.mjs +1 -0
- package/dist/{definitions-LaYTuwQd.mjs → definitions-bybDvnG0.mjs} +1 -1
- package/dist/{definitions-Dgrg7f3D.mjs → definitions-l7TjdE6V.mjs} +1 -1
- package/dist/{encoding-DGcr6Aj_.mjs → encoding-ycOaz8Vr.mjs} +1 -1
- package/dist/{ensure-browser-core-Buls24LQ.mjs → ensure-browser-core-DxWC-NTp.mjs} +1 -1
- package/dist/{factory-Cx_1LorX.mjs → factory-CKr4fAE1.mjs} +1 -1
- package/dist/{graphql-HLf3MS8H.mjs → graphql-B2TiPEow.mjs} +4 -4
- package/dist/{handlers-D49r1-1P.mjs → handlers-8zN_vBIz.mjs} +1 -1
- package/dist/handlers-B62K4FTc.mjs +1 -0
- package/dist/{handlers-BZoPla6E.mjs → handlers-BpDlVVVU.mjs} +1 -1
- package/dist/{handlers-DmQzIc44.mjs → handlers-CMJK7m1c.mjs} +1 -1
- package/dist/{handlers-BLMa4X7l.mjs → handlers-D2ZOul9p.mjs} +2 -2
- package/dist/{handlers-DW5AbYs5.mjs → handlers-D5E40ssn.mjs} +3 -3
- package/dist/{handlers-BP12ZsWc.mjs → handlers-DGbdQAgD.mjs} +2 -2
- package/dist/handlers-DHO3rjsW.mjs +1 -0
- package/dist/{handlers-DCE45Ww8.mjs → handlers-FJ80VzUI.mjs} +1 -1
- package/dist/handlers-VHWrxbM_.mjs +1 -0
- package/dist/{handlers-BggKiVx9.mjs → handlers-l8QIKqBj.mjs} +1 -1
- package/dist/{handlers-DnJRGp7t.mjs → handlers-mPFiNPe8.mjs} +1 -1
- package/dist/{handlers-pVNpaw4A.mjs → handlers-yo_xYzT8.mjs} +1 -1
- package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
- package/dist/{hooks-DDKppogd.mjs → hooks-D4XLfgtV.mjs} +1 -1
- package/dist/index.mjs +11 -15
- package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
- package/dist/maintenance-BUpIukhg.mjs +1 -0
- package/dist/{manifest-yu2xiQqe.mjs → manifest-0Jpt_AQa.mjs} +1 -1
- package/dist/{manifest-DMJlcsTR.mjs → manifest-B3fZbSWR.mjs} +1 -1
- package/dist/{manifest-De-6Wf2R.mjs → manifest-B7NB2rh2.mjs} +1 -1
- package/dist/manifest-BDi4nbH1.mjs +1 -0
- package/dist/{manifest-ais9Afrw.mjs → manifest-BLDfkE7n.mjs} +1 -1
- package/dist/manifest-BcXbB4gf.mjs +1 -0
- package/dist/{manifest-DsVh7Y4U.mjs → manifest-Bdnc_vrc.mjs} +1 -1
- package/dist/manifest-BuYKgCnp.mjs +1 -0
- package/dist/{manifest-Cx2IVMUY.mjs → manifest-CBfNnGPV.mjs} +1 -1
- package/dist/{manifest-DC-SMF6b.mjs → manifest-CPS1Xv69.mjs} +1 -1
- package/dist/{manifest-CGq4NpqH2.mjs → manifest-CQH9FhwI.mjs} +1 -1
- package/dist/{manifest-CRIJq4Hs.mjs → manifest-CRryuZF4.mjs} +1 -1
- package/dist/manifest-CctIumog.mjs +1 -0
- package/dist/manifest-CvTe5ZGV2.mjs +1 -0
- package/dist/{manifest-H-EpAyZQ.mjs → manifest-D-5GH0DV.mjs} +1 -1
- package/dist/{manifest-CtPmHAdn.mjs → manifest-D3Ssf3IC.mjs} +1 -1
- package/dist/{manifest-BeP_zJGb2.mjs → manifest-D5ck3NvC.mjs} +1 -1
- package/dist/{manifest-CeQmtQOY.mjs → manifest-D9jUUJAu.mjs} +1 -1
- package/dist/{manifest-C7qV1z7F.mjs → manifest-DCx6w2XV.mjs} +1 -1
- package/dist/{manifest-CFn0359q2.mjs → manifest-DG19q-Ld.mjs} +1 -1
- package/dist/{manifest-CJMGt7Qy.mjs → manifest-DLMlD0Zc.mjs} +1 -1
- package/dist/{manifest-CDeUZGUZ.mjs → manifest-DYpn8w_h.mjs} +1 -1
- package/dist/manifest-DYzWI8Xs.mjs +1 -0
- package/dist/{manifest-DKUorv5M.mjs → manifest-D_obs5F4.mjs} +1 -1
- package/dist/{manifest-D610kxZr.mjs → manifest-DujQqEQR.mjs} +2 -2
- package/dist/manifest-DwL2ik8P.mjs +1 -0
- package/dist/manifest-ItF5P8A12.mjs +1 -0
- package/dist/{manifest-tmb54wmA.mjs → manifest-KZphqIyX.mjs} +1 -1
- package/dist/{manifest-BPuE6oH2.mjs → manifest-LG42zPLY2.mjs} +1 -1
- package/dist/{manifest-D44TaRJU.mjs → manifest-LLdI5m4T.mjs} +1 -1
- package/dist/{manifest-Dgh0uDW-.mjs → manifest-QYbQXJn0.mjs} +1 -1
- package/dist/{manifest-BFGxlDRh.mjs → manifest-RcpX_MyZ.mjs} +2 -2
- package/dist/{manifest-CDiCtaQT.mjs → manifest-YgVd8Sgz.mjs} +1 -1
- package/dist/{manifest-D16xPXro.mjs → manifest-Zy7Odg5J.mjs} +1 -1
- package/dist/manifest-ff1H7Pdp.mjs +1 -0
- package/dist/{manifest-C_hEIjSx.mjs → manifest-iuhF6pTL2.mjs} +1 -1
- package/dist/{manifest-DWUUWBz0.mjs → manifest-nXHmtMSp2.mjs} +1 -1
- package/dist/{manifest-C1nZkTkO.mjs → manifest-xWfu6iLo.mjs} +1 -1
- package/dist/{manifest-C0g67k6U.mjs → manifest-yC16OhL2.mjs} +1 -1
- package/dist/manifest-ztWJoXy4.mjs +1 -0
- package/dist/modules-BPBcSaM-.mjs +333 -0
- package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-BhwsdVUW.mjs} +1 -1
- 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-BonGThuc.mjs → outputPaths-B4Ic4RZh.mjs} +2 -2
- package/dist/platform-CzaQtISh.mjs +93 -0
- package/dist/process-CWhsCWrf.mjs +2 -0
- package/dist/proxy-DZFlDsG3.mjs +2 -0
- package/dist/{registry-DUHIPE-v.mjs → registry-DH4sc1dt.mjs} +1 -1
- package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
- package/dist/{search-defaults-D2bY-rzH.mjs → search-defaults-lYBVn_3L.mjs} +1 -1
- package/dist/server/plugin-api.d.mts +19 -36
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/{shared-state-board-Cyg-xh_k.mjs → shared-state-board-BSjXLUV1.mjs} +1 -1
- package/dist/{sourcemap-D6Q1UuAp.mjs → sourcemap-Dh3Ai_ur.mjs} +1 -1
- package/dist/streaming-BcJ0B6ao.mjs +1 -0
- package/dist/transform-DOxzeWPB.mjs +103 -0
- package/dist/wasm-CZ_HTfKR.mjs +174 -0
- package/dist/{webcrack-CsLLJIs9.mjs → webcrack-C1iYG_EX.mjs} +3 -3
- package/dist/{workflow-CYIXtrWD.mjs → workflow-BdwQmARn.mjs} +4 -4
- package/package.json +16 -15
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
- package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
- package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
- package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
- package/dist/MemoryController-BaqstM5w.mjs +0 -2
- package/dist/PageController-D9jVkH0i.mjs +0 -1
- package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
- package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
- package/dist/ToolProbe-xsfALmN3.mjs +0 -1
- package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
- package/dist/analysis-BuR-NgX8.mjs +0 -5
- package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
- package/dist/browser-C4Le3xqA.mjs +0 -11
- package/dist/collector-CKO8RPK8.mjs +0 -1
- package/dist/constants-Cp6hBrrx.mjs +0 -1
- package/dist/definitions-CdWEuIkI.mjs +0 -1
- package/dist/definitions-OvGsfxdt.mjs +0 -1
- package/dist/handlers-D3iev8g1.mjs +0 -1
- package/dist/handlers-De5u62Ga2.mjs +0 -1
- package/dist/handlers-S9Ws0IGy.mjs +0 -2
- package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
- package/dist/maintenance-CutEO84j.mjs +0 -1
- package/dist/manifest-BXry5N09.mjs +0 -1
- package/dist/manifest-Cq0j7GZt.mjs +0 -1
- package/dist/manifest-DD3rtxvV.mjs +0 -1
- package/dist/manifest-Dm0o3i2U.mjs +0 -1
- package/dist/manifest-DtEFSRaq.mjs +0 -1
- package/dist/manifest-zrbrpKCC.mjs +0 -1
- package/dist/modules-p-PUNv9r.mjs +0 -332
- package/dist/network-BjZ1Y-GB.mjs +0 -7
- package/dist/platform-C446Lf97.mjs +0 -93
- package/dist/process-C9f2A5zk.mjs +0 -962
- package/dist/proxy-CvRepxgV.mjs +0 -1
- package/dist/streaming-CTX58tbb.mjs +0 -1
- package/dist/transform-Cv9P2vVD.mjs +0 -103
- package/dist/wasm-DaJa8J0V.mjs +0 -174
- /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-CsNtQIR8.mjs} +0 -0
- /package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-ZfQdpLNI.mjs} +0 -0
- /package/dist/{EventBus-DgciURGg.mjs → EventBus-DL8iLA09.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-BtbwXsLC.mjs} +0 -0
- /package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-DT0EAUEo.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +0 -0
- /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-D_G1ZPyd.mjs} +0 -0
- /package/dist/{PrerequisiteError-Bl3dK8XA.mjs → PrerequisiteError-BjCQA-gK.mjs} +0 -0
- /package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BhSYYdiI.mjs} +0 -0
- /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-BmcxfwSF.mjs} +0 -0
- /package/dist/{VersionDetector-DMoUWyNm.mjs → VersionDetector-CHT36Az0.mjs} +0 -0
- /package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-eUCF57l_.mjs} +0 -0
- /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-BOFwSXUN.mjs} +0 -0
- /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-m2U8glkF.mjs} +0 -0
- /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-CyXuKUl1.mjs} +0 -0
- /package/dist/{concurrency-CcK46d0h.mjs → concurrency-DCr8WQ2M.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-CV_UdYqj.mjs} +0 -0
- /package/dist/{flat-target-session-CO5g78k3.mjs → flat-target-session-DvcQX7J5.mjs} +0 -0
- /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-vLA_hOJt.mjs} +0 -0
- /package/dist/{handlers-Dv_runVv.mjs → handlers-0yKLRIfo.mjs} +0 -0
- /package/dist/{matchesWildcardPattern-BGqLSmEs.mjs → matchesWildcardPattern-BAG6LvX5.mjs} +0 -0
- /package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-Bw413PlW.mjs} +0 -0
- /package/dist/{playwright-cdp-fallback-BwVR-_T3.mjs → playwright-cdp-fallback-DqFdx9-s.mjs} +0 -0
- /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-CsIJGkpd.mjs} +0 -0
- /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-qif8M9-K.mjs} +0 -0
- /package/dist/{types-DtThH00r.mjs → types-D9EiE5o9.mjs} +0 -0
- /package/dist/{types-CuyefmGT.mjs → types-Fz69RzbZ.mjs} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{l as n,o as r}from"./ToolRouter.policy-
|
|
1
|
+
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{l as n,o as r}from"./ToolRouter.policy-CfhJczkt.mjs";import{randomUUID as i}from"node:crypto";var a=class{store=new Map;set(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}getValueAtPath(e,t){let n=this.store.get(e);if(!n||typeof n!=`object`)return n;let r=o(n)||n;return t.split(`.`).reduce((e,t)=>{if(e&&typeof e==`object`){let n=t.match(/^(\d+)$/);return n&&Array.isArray(e)?e[Number(n[1])]:e[t]}},r)}resolve(e){let t=e.match(/^\$\{(.+)\}$/);if(!t||!t[1])return e;let n=t[1],r=n.indexOf(`.`);return r===-1?this.store.get(n):this.getValueAtPath(n.slice(0,r),n.slice(r+1))}};function o(e){if(!e||typeof e!=`object`)return;let t=e.content?.find(e=>e.type===`text`)?.text;if(typeof t==`string`)try{let e=JSON.parse(t);return e&&typeof e==`object`?e:void 0}catch{return}}function s(e){if(!e||typeof e!=`object`)return;if(e.isError)return`Tool returned MCP error response`;let t=o(e);if(t?.success===!1)return typeof t.error==`string`?t.error:`Tool reported success=false`}function c(e){if(Array.isArray(e))return e.reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0});if(!e||typeof e!=`object`)return{success:0,failure:0};let t=e;if(Array.isArray(t.__order))return t.__order.reduce((e,n)=>{let r=c(t[n]);return e.success+=r.success,e.failure+=r.failure,e},{success:0,failure:0});let n=o(e);return n?.success===!0?{success:1,failure:0}:n?.success===!1||`error`in t?{success:0,failure:1}:{success:0,failure:0}}function l(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=i.startsWith("${")?i:`\${${i}}`;n[r]=t.resolve(e)}return n}function u(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}function d(e,t){if(typeof e==`string`)return t.resolve(e);if(Array.isArray(e))return e.map(e=>d(e,t));if(e&&typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=d(i,t);return n}return e}function f(e,t){if(e.has(t))return e.get(t);let[n,...r]=t.split(`.`);if(!n||!e.has(n))return;let i=e.get(n);if(i&&typeof i==`object`){let e=o(i);e&&(i=e)}for(let e of r){if(i&&typeof i==`object`){let t=e.match(/^(\d+)$/);if(t&&Array.isArray(i)){i=i[Number(t[1])];continue}i=i[e];continue}return}return i}function p(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){let n=e,r=t;return n.length===r.length&&n.every((e,t)=>p(e,r[t]))}let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>p(e[n],t[n])):!1}return!1}async function m(e,t){if(e.predicateFn)return await e.predicateFn(t);if(e.predicateId===`always_true`)return!0;if(e.predicateId===`always_false`)return!1;if(e.predicateId===`any_step_failed`)return[...t.stepResults.values()].some(e=>c(e).failure>0);let n=e.predicateId.match(/success_rate_gte_(\d+)/i);if(n?.[1]){let e=Number(n[1]),r=[...t.stepResults.values()].reduce((e,t)=>{let n=c(t);return e.success+=n.success,e.failure+=n.failure,e},{success:0,failure:0}),i=r.success+r.failure;return i>0&&r.success/i>=e/100}let r=e.predicateId.match(/^variable_equals_(.+?)_(.+)$/);if(r?.[1]&&r[2])return p(f(t.stepResults,r[1]),r[2]);let i=e.predicateId.match(/^variable_contains_(.+?)_(.+)$/);if(i?.[1]&&i[2]){let e=f(t.stepResults,i[1]);return typeof e!=`string`&&!Array.isArray(e)?!1:String(e).includes(i[2])}let a=e.predicateId.match(/^variable_matches_(.+?)_(.+)$/);if(a?.[1]&&a[2]){let e=f(t.stepResults,a[1]);if(typeof e!=`string`)return!1;try{return new RegExp(a[2]).test(e)}catch{return!1}}throw Error(`Unknown workflow predicateId "${e.predicateId}"`)}function h(e){switch(e.kind){case`tool`:return[e];case`sequence`:case`parallel`:return e.steps.flatMap(e=>h(e));case`branch`:return[...h(e.whenTrue),...e.whenFalse?h(e.whenFalse):[]];case`fallback`:return[...h(e.primary),...h(e.fallback)];default:return[]}}function g(e){try{let t=e.getDomainInstance(`evidenceGraph`);return t?{hasGraph:!0,nodeCount:t.nodeCount,edgeCount:t.edgeCount}:{hasGraph:!1,nodeCount:0,edgeCount:0}}catch{return{hasGraph:!1,nodeCount:0,edgeCount:0}}}function _(e,t){let n=r(),i=[];for(let r of h(e)){let e=n[r.toolName]??[];for(let n of e)n.check(t)||i.push({nodeId:r.id,toolName:r.toolName,condition:n.condition,fix:n.fix})}return i}var v=class{runs=new Map;lastSuccess=new Map;recordSuccess(e){let n={workflowId:e.workflowId,runId:e.runId,startedAt:e.startedAt,finishedAt:e.finishedAt,durationMs:e.durationMs,status:`success`,stepResultKeys:Object.keys(e.stepResults)};this.runs.set(e.runId,n),this.lastSuccess.set(e.workflowId,e),t.debug(`workflow run recorded: ${e.runId} (${e.workflowId})`)}recordError(e,n,r,i){let a={workflowId:e,runId:n,startedAt:r,finishedAt:new Date().toISOString(),durationMs:Date.now()-new Date(r).getTime(),status:`error`,stepResultKeys:[]};this.runs.set(n,a),t.debug(`workflow run error: ${n} (${e}): ${i}`)}getRun(e){return this.runs.get(e)}getLastSuccess(e){return this.lastSuccess.get(e)}listRuns(e){let t=[...this.runs.values()];return e?t.filter(t=>t.workflowId===e):t}clear(){this.runs.clear(),this.lastSuccess.clear()}},y=class extends Error{warnings;constructor(e){super(`Workflow preflight failed with ${e.length} unsatisfied prerequisite(s)`),this.warnings=e,this.name=`PreflightError`}},b=e({executeExtensionWorkflow:()=>O});const x=new v;function S(e,t,n){let r=t.split(`.`).filter(Boolean),i=e;for(let e of r){if(!i||typeof i!=`object`)return n;i=i[e]}return i??n}function C(e){return new Promise(t=>setTimeout(t,e))}async function w(e,t,n){return!Number.isFinite(t)||t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}async function T(e,t,n,r){let i=t.inputFrom?l(t.inputFrom,r.dataBus):{},a={...t.input?u(t.input,r.dataBus):{},...i,...n?.[t.id]},o=async()=>{let n=await w(e.executeToolWithTracking(t.toolName,a),t.timeoutMs??0,`Workflow tool node "${t.id}"`),i=s(n);if(i)throw Error(i);return r.dataBus.set(t.id,n),n},c=t.retry;if(!c)return o();let d=0,f=c.backoffMs;for(;d<c.maxAttempts;)try{return await o()}catch(e){if(d+=1,d>=c.maxAttempts)throw e;await C(f),f=Math.max(0,Math.floor(f*(c.multiplier??1)))}throw Error(`Workflow tool node "${t.id}" exhausted retries`)}async function E(e,t,n,r){let i=Math.max(1,t.maxConcurrency??4),a={__order:[]},o=0,s=!1,c=async()=>{for(;;){if(s)return;let i=o;if(o+=1,i>=t.steps.length)return;let c=t.steps[i];if(!c)return;try{let t=await D(e,c,n,r);a[c.id]=t,a.__order.push(c.id)}catch(e){if(t.failFast)throw s=!0,e;a[c.id]={success:!1,error:e instanceof Error?e.message:String(e)},a.__order.push(c.id)}}};return await Promise.all(Array.from({length:Math.min(i,t.steps.length)},()=>c())),a}async function D(e,t,n,r){n.emitSpan(`workflow.node.start`,{nodeId:t.id,kind:t.kind});let i;switch(t.kind){case`tool`:i=await T(e,t,r.nodeInputOverrides,n);break;case`sequence`:{let a=t,o=[];for(let t of a.steps)o.push(await D(e,t,n,r));i=o;break}case`parallel`:i=await E(e,t,n,r);break;case`branch`:{let a=t,o=await m(a,n)?a.whenTrue:a.whenFalse;i=o?await D(e,o,n,r):void 0;break}case`fallback`:{let a=t;try{i=await D(e,a.primary,n,r)}catch(t){n.emitSpan(`workflow.node.fallback`,{nodeId:a.id,primaryNodeId:a.primary.id,fallbackNodeId:a.fallback.id,error:t instanceof Error?t.message:String(t)}),i=await D(e,a.fallback,n,r)}break}default:throw Error(`Unsupported workflow node kind: ${t.kind}`)}return n.stepResults.set(t.id,i),n.emitSpan(`workflow.node.finish`,{nodeId:t.id,kind:t.kind}),i}async function O(e,t,r={}){let o=i(),s=r.profile??String(e.baseTier??`workflow`),c=new Date().toISOString(),l=Date.now(),u=[],d=[],f=new Map,p=new a,m=r.config?{...e.config,...r.config}:e.config,h={workflowRunId:o,profile:s,stepResults:f,dataBus:p,invokeTool(t,n){return e.executeToolWithTracking(t,n)},emitSpan(e,t){d.push({name:e,attrs:t,at:new Date().toISOString()})},emitMetric(e,t,n,r){u.push({name:e,value:t,type:n,attrs:r,at:new Date().toISOString()})},getConfig(e,t){return S(m,e,t)}};try{await t.onStart?.(h);let i=t.build(h),a=r.preflightMode??`warn`,p=[];if(a===`skip`)h.emitSpan(`workflow.preflight`,{mode:a,skipped:!0,evidenceState:g(e),warningCount:0});else try{let t=await n(e),r=g(e);if(p=_(i,t),h.emitSpan(`workflow.preflight`,{mode:a,routingState:t,evidenceState:r,warningCount:p.length,warnings:p}),a===`strict`&&p.length>0)throw new y(p)}catch(t){if(t instanceof y)throw t;h.emitSpan(`workflow.preflight`,{mode:a,warningCount:0,skipped:!0,error:t instanceof Error?t.message:String(t),evidenceState:g(e)})}let m=await w(D(e,i,h,r),r.timeoutMs??t.timeoutMs??0,`Workflow "${t.id}"`);await t.onFinish?.(h,m);try{let t=typeof e.getDomainInstance==`function`?e.getDomainInstance(`evidenceGraph`):void 0;t&&t.nodeCount>0&&(f.set(`__evidenceSnapshot`,t.exportJson()),h.emitSpan(`workflow.evidence.auto-export`,{nodeCount:t.nodeCount,edgeCount:t.edgeCount}))}catch(e){h.emitSpan(`workflow.evidence.auto-export`,{skipped:!0,error:e instanceof Error?e.message:String(e)})}let v={workflowId:t.id,displayName:t.displayName,runId:o,profile:s,startedAt:c,finishedAt:new Date().toISOString(),durationMs:Date.now()-l,result:m,stepResults:Object.fromEntries(f.entries()),metrics:u,spans:d};return x.recordSuccess(v),v}catch(e){let n=e instanceof Error?e:Error(String(e));throw x.recordError(t.id,o,c,n),await t.onError?.(h,n),n}}export{O as n,b as t};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{Ft as t,Gr as n,Kr as r,Pt as i,Wr as a,c as o,o as s,s as c}from"./constants-BYj8Xek8.mjs";import{n as l,r as u}from"./response-C7rKQst4.mjs";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./parse-args-Bw413PlW.mjs";import{s as _}from"./PageController-Dfsm1_o7.mjs";import"./definitions-D5wl_8HN.mjs";import{n as v}from"./ResponseBuilder-BfWP-uaT.mjs";import{n as y,t as b}from"./webcrack-C1iYG_EX.mjs";import*as x from"@babel/parser";import S from"@babel/traverse";import*as C from"@babel/types";import w from"@babel/generator";const ee=new Set([`=`,`(`,`[`,`,`,`;`,`{`,`!`,`&`,`|`,`?`,`:`,`~`,`^`,`+`,`-`,`*`,`%`,`<`,`>`,`
|
|
2
|
+
`]);function T(e){return new RegExp(e.source,e.flags)}function E(e){if(e.length===0)return[];let t=[],n=e.toSorted((e,t)=>e.start-t.start||e.end-t.end);for(let e of n){let n=t[t.length-1];if(!n||e.start>n.end){t.push({...e});continue}n.end=Math.max(n.end,e.end)}return t}function D(e){try{let t=x.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),n=[],r=(e,t)=>{typeof e==`number`&&typeof t==`number`&&t>e&&n.push({start:e,end:t})},i=Array.isArray(t.comments)?t.comments:[];for(let e of i)r(e.start,e.end);return S(t,{StringLiteral(e){r(e.node.start,e.node.end),e.skip()},TemplateElement(e){r(e.node.start,e.node.end),e.skip()},RegExpLiteral(e){r(e.node.start,e.node.end),e.skip()}}),E(n)}catch{return null}}function te(e){let t=e[e.length-2];if(typeof t==`number`)return t;let n=e[e.length-3];return typeof n==`number`?n:null}function ne(e,t){let n=t-1;for(;n>=0&&(e[n]===` `||e[n]===` `||e[n]===`\r`);)n--;if(n<0)return!0;let r=e[n];if(ee.has(r))return!0;if(r!==`)`)return!1;let i=1,a=n-1;for(;a>=0&&i>0;)e[a]===`)`&&i++,e[a]===`(`&&i--,a--;for(a--;a>=0&&(e[a]===` `||e[a]===` `);)a--;let o=``;for(;a>=0&&/[a-z]/.test(e[a]);)o=e[a]+o,a--;return[`if`,`while`,`for`,`switch`,`return`,`typeof`,`void`,`in`,`of`,`case`].includes(o)}function re(e,t){let n=null,r=!1,i=!1,a=!1;for(let o=0;o<t;o++){let s=e[o];if(r){s===`*`&&e[o+1]===`/`&&(r=!1,o++);continue}if(i){s===`
|
|
3
|
+
`&&(i=!1);continue}if(a){if(s===`\\`){o++;continue}if(s===`/`){for(a=!1,o++;o<t&&/[gimsuy]/.test(e[o]);)o++;continue}if(s===`[`){for(o++;o<t&&e[o]!==`]`;)e[o]===`\\`&&o++,o++;continue}continue}if(n){if(s===`\\`){o++;continue}s===n&&(n=null);continue}if(s===`/`&&e[o+1]===`/`){i=!0,o++;continue}if(s===`/`&&e[o+1]===`*`){r=!0,o++;continue}if(s===`/`&&ne(e,o)){a=!0;continue}(s===`'`||s===`"`||s==="`")&&(n=s)}return n!==null||r||i||a}function O(e,t,n){let r=e=>e.replace(T(t),n),i=D(e);if(i===null)return e.replace(T(t),(...t)=>{let r=typeof t[0]==`string`?t[0]:``,i=te(t);return i!==null&&re(e,i)?r:typeof n==`string`?n:n(r,...t.slice(1))});if(i.length===0)return r(e);let a=``,o=0;for(let t of i)o<t.start&&(a+=r(e.slice(o,t.start))),a+=e.slice(t.start,t.end),o=t.end;return o<e.length&&(a+=r(e.slice(o))),a}const ie=/\b(-?\d+(?:\.\d+)?)\s*([+\-%*/])\s*(-?\d+(?:\.\d+)?)\b/g,ae=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*/g,oe=/if\s*\(\s*false\s*\)\s*\{[^}]*\}\s*else\s*\{([^}]*)\}/g,k=/if\s*\(\s*true\s*\)\s*\{([^}]*)\}\s*(?:else\s*\{[^}]*\}\s*)?/g,A=/var\s+([A-Za-z_$]\w*)\s*=\s*['"]([^'"]+)['"]\.split\(['"]\|['"]\)\s*;\s*var\s+(\w+)\s*=\s*0\s*;\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\s*\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,j=/var\s+([A-Za-z_$]\w*)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\];\s*var\s+(\w+)\s*=\s*(\d+);\s*while\s*\(\s*!!\[\]\s*\)\s*\{\s*switch\s*\(\s*\1\[\s*\3\+\+\]\s*\)\s*\{([\s\S]*?)\}\s*break;\s*\}/g,M=/['"]([^'"]*)['"]\s*\+\s*['"]([^'"]*)['"]/g;function N(e,t,n){for(let r=t;r>=0&&r<e.length;r+=n){let t=e[r];if(t&&!/\s/.test(t))return t}return``}function P(e,t){let n=t.toSorted((e,t)=>t.start-e.start||t.end-e.end),r=e;for(let e of n)r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`;return r}function F(e,t){let n=t.get(e.node.name);if(!n)return null;let r=e.scope.getBinding(e.node.name);if(!r||!C.isVariableDeclarator(r.path.node)||!C.isIdentifier(r.path.node.id)||!t.has(r.path.node.id.name))return null;let i=r.identifier===e.node,a=e.isReferencedIdentifier(),o=e.key===`left`&&e.parentPath.isAssignmentExpression(),s=e.key===`left`&&(e.parentPath.isForInStatement()||e.parentPath.isForOfStatement()),c=e.key===`argument`&&e.parentPath.isUpdateExpression();return!i&&!a&&!o&&!s&&!c?null:n}function I(e,t){try{let n=x.parse(e,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),r=new Map;return S(n,{ObjectProperty(e){if(!e.node.shorthand||!C.isIdentifier(e.node.key)||!C.isIdentifier(e.node.value))return;let n=e.get(`value`);if(!n.isIdentifier())return;let i=F(n,t),{start:a,end:o}=e.node;!i||a==null||o!=null&&(r.set(`${a}:${o}`,{start:a,end:o,text:`${e.node.key.name}: ${i}`}),e.skip())},Identifier(e){let n=F(e,t),{start:i,end:a}=e.node;!n||i==null||a!=null&&r.set(`${i}:${a}`,{start:i,end:a,text:n})}}),r.size===0?e:P(e,[...r.values()])}catch{return null}}function L(e){let t=e;return t=O(t,ie,(e,t,n,r)=>{let i=Number(t),a=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a))return e;let o=null;return n===`+`?o=i+a:n===`-`?o=i-a:n===`*`?o=i*a:n===`/`&&a!==0?o=i/a:n===`%`&&a!==0&&(o=i%a),o===null||!Number.isFinite(o)?e:String(Number.isInteger(o)?o:Number(o.toFixed(12)))}),t=O(t,M,(e,t,n)=>JSON.stringify(`${t}${n}`)),t=O(t,/--(\d)/g,(e,t)=>t),t=O(t,/\+\s*(\d+(?:\.\d+)?)/g,(e,t)=>t),t=O(t,/\b0x([0-9a-fA-F]{2,8})\b/g,(e,t)=>{let n=Number.parseInt(t,16);return Number.isFinite(n)?String(n):e}),t}function R(e){let t=e;return t=O(t,oe,(e,t)=>t),t=O(t,ae,``),t=O(t,k,(e,t)=>t),t=O(t,/\btrue\s*\?\s*([^:]+)\s*:\s*([^,;)\]}]+)/g,(e,t)=>t),t=O(t,/\bfalse\s*\?\s*[^:]+\s*:\s*([^,;)}\]]+)/g,(e,t)=>t),t=O(t,/if\s*\([^)]*\)\s*\{\s*\}\s*/g,``),t}function z(e){let t=e;return t=O(t,A,(e,t,n,r,i)=>{let a=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,o=new Map,s;for(;(s=a.exec(i))!==null;){let e=s[1],t=(s[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&o.set(e,t)}let c=n.split(`|`).map(e=>e.trim()).map(e=>o.get(e)).filter(e=>!!e).join(`
|
|
4
|
+
`);return c.length>0?c:e}),t=O(t,j,(e,t,n,r,i,a)=>{let o=/case\s*['"]([^'"]+)['"]\s*:\s*([\s\S]*?)(?=case\s*['"]|default\s*:|$)/g,s=new Map,c;for(;(c=o.exec(a))!==null;){let e=c[1],t=(c[2]??``).replace(/\bcontinue\s*;?/g,``).replace(/\bbreak\s*;?/g,``).trim();e&&t.length>0&&s.set(e,t)}let l=n.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``).trim()).map(e=>s.get(e)).filter(e=>!!e).join(`
|
|
5
|
+
`);return l.length>0?l:e}),t}function B(e){let t=new Set,n=/\b(?:var|let|const)\s+([A-Za-z_$]\w{0,3})\b/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];e&&(e.length<=2||e.startsWith(`_0x`)||e.startsWith(`_`))&&t.add(e)}if(t.size===0)return{code:e,count:0};let i=new Map,a=1;for(let e of t)i.set(e,`var_${a}`),a++;let o=I(e,i);if(o!==null)return{code:o,count:o===e?0:i.size};let s=e.replace(RegExp(`\\b(${[...t].map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b`,`g`),(e,t,n,r)=>{let a=i.get(t);if(!a)return e;let o=n>0?r[n-1]:``,s=N(r,n-1,-1),c=N(r,n+e.length,1);return o===`.`||o===`'`||o===`"`||o==="`"||o===`$`||(s===`{`||s===`,`)&&(c===`:`||c===`(`)?e:a});return{code:s,count:s===e?0:i.size}}const V={"<":(e,t)=>e<t,">":(e,t)=>e>t,"<=":(e,t)=>e<=t,"<==":(e,t)=>e<=t,">=":(e,t)=>e>=t,">==":(e,t)=>e>=t,"==":(e,t)=>e===t,"===":(e,t)=>e===t,"!=":(e,t)=>e!==t,"!==":(e,t)=>e!==t},H=[{pattern:`jsfuck`,regex:/\[!\[\]\]\[\(['"]\)constructor['"]\)\]\(!!\[\]\+\[\]\)\(\)/g,replacement:`"function Boolean() { [native code] }"`},{pattern:`jsfuck`,regex:/!!\[\]\+\[\]/g,replacement:`"true"`},{pattern:`jsfuck`,regex:/!\[\]\+\[\]/g,replacement:`"false"`},{pattern:`jsfuck`,regex:/\+!!\[\]/g,replacement:`1`},{pattern:`jsfuck`,regex:/\[\]\+\[\]/g,replacement:`""`},{pattern:`jsfuck`,regex:/\+\[\]/g,replacement:`0`}],U=[{pattern:`boolean-literal`,regex:/!!\[\]/g,replacement:`true`},{pattern:`boolean-literal`,regex:/!\[\]/g,replacement:`false`},{pattern:`undefined-literal`,regex:/void\s+0/g,replacement:`undefined`}],W={pattern:`opaque-truthy`,regex:/!0x0\b|!\b0(?![.\d])/g,replacement:`true`},G=[{pattern:`type-coercion`,regex:/typeof\s+undefined\s*===?\s*["']undefined["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+null\s*===?\s*["']object["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/typeof\s+NaN\s*===?\s*["']number["']/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*==\s*undefined/g,replacement:`true`},{pattern:`type-coercion`,regex:/null\s*===\s*undefined/g,replacement:`false`},{pattern:`type-coercion`,regex:/NaN\s*===?\s*NaN/g,replacement:`false`}],K=/if\s*\(\s*(-?\d+(?:\.\d+)?)\s*([<>!=]+)\s*(-?\d+(?:\.\d+)?)\s*\)/g,q=/!\s*(-?\d+(?:\.\d+)?)(?![.\d\s\w])/g,se=/(?:var|let|const)\s+(\w+)\s*=\s*\[(['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*)\]/g;function J(e,t,n,r){return e.solved.push({pattern:t,original:n,result:r}),r}function Y(e,t){for(let n of t)e.output=O(e.output,n.regex,t=>J(e,n.pattern,t,n.replacement))}function ce(e){e.output=O(e.output,K,(t,n,r,i)=>{if(e.iterations>=e.maxIterations)return t;let a=V[r];if(!a)return t;e.iterations+=1;let o=a(Number(n),Number(i));return J(e,`constant-comparison`,t,String(o)),e.replaceInPlace?`/* ${t} => ${o} */ if (${o})`:`if (${o})`})}function le(e){e.output=O(e.output,q,(t,n)=>{let r=Number(n);return r===0||!Number.isFinite(r)?t:J(e,`opaque-falsy`,t,`false`)})}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function de(e){let t=new Map;return O(e,se,(e,n,r)=>{let i=r.split(/,\s*/).map(e=>e.replace(/^['"]|['"]$/g,``));return t.set(n,i),e}),t}function fe(e){let t=de(e.output);if(t.size!==0)for(let[n,r]of t){let t=RegExp(`${ue(n)}\\(['"]?(0x[0-9a-fA-F]+|\\d+)['"]?\\)`,`g`);e.output=O(e.output,t,(t,n)=>{if(e.iterations>=e.maxIterations)return t;let i=n.startsWith(`0x`)?Number.parseInt(n,16):Number(n);return i<0||i>=r.length?t:(e.iterations+=1,J(e,`string-array-access`,t,JSON.stringify(r[i])))})}}function pe(e){let t={output:e.code,solved:[],replaceInPlace:e.replaceInPlace,maxIterations:e.maxIterations,iterations:0};return ce(t),Y(t,H),Y(t,U),Y(t,[W]),le(t),fe(t),Y(t,G),{success:!0,solvedCount:t.solved.length,solved:t.solved,transformedCode:e.replaceInPlace?t.output:void 0}}const me=[{type:`for-switch`,test:/for.*switch/s},{type:`while-switch`,test:/while.*switch/s},{type:`if-else-chain`,test:/if\s*\(\s*\w+\s*===?\s*\w+/}];function he(e){for(let t of me)if(t.test.test(e))return t.type;return`switch`}function ge(e){let t=new Map;for(let n of e){let e=n.type||`unknown`;t.set(e,(t.get(e)||0)+1)}return Object.fromEntries(t)}function _e(e){let{code:t,extractBytecode:n,mapOpcodes:r,vmResult:i}=e;if(!i.isJSVMP)return{success:!0,isVM:!1,message:`No VM/JSVMP patterns detected.`};let a={isVM:!0,vmType:i.vmType,dispatchType:he(t),complexity:i.vmFeatures?.complexity,instructionCount:i.vmFeatures?.instructionCount,interpreterLocation:i.vmFeatures?.interpreterLocation};return n&&i.instructions&&(a.bytecode=i.instructions),r&&i.instructions&&(a.opcodeDistribution=ge(i.instructions),a.suggestedStrategy=i.vmFeatures?.complexity===`high`?`Use js_symbolic_execute_jsvmp with these instructions for high-complexity VMs`:`Use standard deobfuscation pipeline (js_deobfuscate_pipeline)`),{success:!0,analysis:a}}async function ve(t,n){let r=d(n,`searchKeyword`,``),i=g(n,`forceRequireAll`,!!r),a=Math.min(m(n,`maxResults`,20),100);return v(async()=>{let n=await _(await t.getActivePage(),async e=>{let t=window,n=null;typeof t.__webpack_require__==`function`&&(n=t.__webpack_require__);let r=Object.keys(t).filter(e=>e.startsWith(`webpackChunk`)||e.startsWith(`webpackJsonp`)),i=new Set;for(let e of r){let n=t[e];if(!Array.isArray(n))continue;let r=n;if(r.m&&typeof r.m==`object`)for(let e of Object.keys(r.m))i.add(e);for(let e of n)if(Array.isArray(e)&&e[1]&&typeof e[1]==`object`)for(let t of Object.keys(e[1]))i.add(t)}if(typeof t.__webpack_modules__==`object`&&t.__webpack_modules__)for(let e of Object.keys(t.__webpack_modules__))i.add(e);if(!n)for(let e of r){let r=t[e];if(r?.m&&typeof r.m==`object`){let e=r.m;n=t=>{try{let n=e[t];return typeof n==`function`?n():n}catch{return}};break}}let a=Array.from(i);if(!e.forceRequireAll||!n)return{total:a.length,requireFound:!!n,chunkKeys:r,moduleIds:a.slice(0,200),matches:[]};let o=n,s=[];for(let t of a){if(s.length>=e.maxResults)break;try{let n=o(t);if(n==null)continue;let r;try{r=JSON.stringify(n)}catch{r=String(n)}(!e.searchKeyword||r.toLowerCase().includes(e.searchKeyword.toLowerCase()))&&s.push({id:t,preview:r.slice(0,600)})}catch{}}return{total:a.length,requireFound:!0,chunkKeys:r,moduleIds:a.slice(0,200),matches:s}},{searchKeyword:r,forceRequireAll:i,maxResults:a});return e.info(`webpack_enumerate: found ${n.total} modules, ${n.matches.length} matches`),n})}var X=class{symbolCounter=0;pathCounter=0;async execute(t){let i=Date.now(),{code:o,maxPaths:s=n,maxDepth:c=a,timeout:l=r,enableConstraintSolving:u=!1}=t;e.info(` ...`);let d=[],f=[],p=[],m=[];try{let t=x.parse(o,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),n=[{state:{pc:0,stack:[],registers:new Map,memory:new Map,pathConstraints:[]},depth:0}];for(;n.length>0&&d.length<s;){if(Date.now()-i>l){m.push(`Symbolic execution timed out`);break}let{state:e,depth:r}=n.pop();if(r>=c){m.push(`Max depth reached: ${c}`);continue}let a=this.executeStep(e,t);for(let e of a)if(this.isTerminalState(e)){let t=this.createPath(e);d.push(t),this.collectSymbolicValues(e,f),this.collectConstraints(e,p)}else n.push({state:e,depth:r+1})}u&&await this.solveConstraints(d,m);let r=this.calculateCoverage(d,t),a=Date.now()-i;return e.info(`Symbolic execution complete in ${a}ms`),e.info(` : ${d.length}`),e.info(` : ${(r*100).toFixed(1)}%`),{paths:d,coverage:r,symbolicValues:f,constraints:p,warnings:m,stats:{totalPaths:d.length,feasiblePaths:d.filter(e=>e.isFeasible).length,infeasiblePaths:d.filter(e=>!e.isFeasible).length,executionTime:a}}}catch(t){throw e.error(``,t),t}}executeStep(e,t){let n=[],r=null,i=0;if(S(t,{enter(t){i===e.pc&&(r=t.node,t.stop()),i++}}),!r)return[];if(C.isVariableDeclaration(r)){let t=this.cloneState(e);r.declarations.forEach(e=>{if(C.isIdentifier(e.id)){let n=e.id.name,r=this.createSymbolicValue(`unknown`,n,n);t.memory.set(n,r)}}),t.pc++,n.push(t)}else if(C.isIfStatement(r)){let t=this.cloneState(e),i=this.cloneState(e),a=r,o=this.nodeToString(a.test);t.pathConstraints.push({type:`custom`,expression:o,description:``}),i.pathConstraints.push({type:`custom`,expression:`!(${o})`,description:``}),t.pc++,i.pc++,n.push(t,i)}else if(C.isWhileStatement(r)||C.isForStatement(r)){let t=this.cloneState(e),r=this.cloneState(e);t.pc++,r.pc+=2,n.push(t,r)}else if(C.isAssignmentExpression(r)){let t=this.cloneState(e),i=r;if(C.isIdentifier(i.left)){let e=i.left.name,n=this.nodeToString(i.right),r=this.createSymbolicValue(`unknown`,n,n);t.memory.set(e,r)}t.pc++,n.push(t)}else{let t=this.cloneState(e);t.pc++,n.push(t)}return n}nodeToString(e){return C.isIdentifier(e)?e.name:C.isNumericLiteral(e)?String(e.value):C.isStringLiteral(e)?`"${e.value}"`:C.isBinaryExpression(e)?`${this.nodeToString(e.left)} ${e.operator} ${this.nodeToString(e.right)}`:C.isUnaryExpression(e)?`${e.operator}${this.nodeToString(e.argument)}`:`[Complex Expression]`}isTerminalState(e){return e.pc>1e3||e.pathConstraints.length>50||e.stack.length===0&&e.memory.size===0}createPath(e){let t=`path-${this.pathCounter++}`,n=this.calculatePathCoverage(e);return{id:t,states:[e],constraints:[...e.pathConstraints],isFeasible:this.checkPathFeasibility(e.pathConstraints),coverage:n}}calculatePathCoverage(e){return Math.min(e.pc/100,1)}checkPathFeasibility(e){let t=new Set;for(let n of e){let e=n.expression;if(t.has(`!(${e})`))return!1;t.add(e)}return!0}collectSymbolicValues(e,t){let n=new Set;for(let r of e.stack)n.has(r.id)||(t.push(r),n.add(r.id));for(let r of e.registers.values())n.has(r.id)||(t.push(r),n.add(r.id));for(let r of e.memory.values())n.has(r.id)||(t.push(r),n.add(r.id))}collectConstraints(e,t){let n=new Set;for(let r of e.pathConstraints){let e=`${r.type}:${r.expression}`;n.has(e)||(t.push(r),n.add(e))}let r=[...e.stack,...Array.from(e.registers.values()),...Array.from(e.memory.values())];for(let e of r)for(let r of e.constraints){let e=`${r.type}:${r.expression}`;n.has(e)||(t.push(r),n.add(e))}}async solveConstraints(t,n){e.info(` ...`);for(let e of t){let t=this.simpleSMTSolver(e.constraints);t.satisfiable?e.isFeasible=!0:(e.isFeasible=!1,n.push(` ${e.id} : ${t.reason}`))}e.info(`Path analysis complete, feasible paths: ${t.filter(e=>e.isFeasible).length}/${t.length}`)}simpleSMTSolver(e){let t=e.filter(e=>e.type===`range`||e.type===`inequality`);for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let r=t[e],i=t[n];if(!(!r||!i)&&this.areContradictory(r.expression,i.expression))return{satisfiable:!1,reason:`: ${r.expression} ${i.expression}`}}return{satisfiable:!0}}areContradictory(e,t){let n=/(\w+)\s*>\s*(\d+)/,r=/(\w+)\s*<\s*(\d+)/,i=e.match(n),a=t.match(r);return i&&a&&i[1]===a[1]&&i[2]&&a[2]?parseInt(i[2],10)>=parseInt(a[2],10):!1}calculateCoverage(e,t){let n=0;if(S(t,{Statement(){n++}}),n===0)return 0;let r=new Set;for(let t of e)for(let e of t.states)r.add(e.pc);return r.size/n}cloneState(e){return{pc:e.pc,stack:[...e.stack],registers:new Map(e.registers),memory:new Map(e.memory),pathConstraints:[...e.pathConstraints]}}createSymbolicValue(e,t,n){return{id:`sym-${this.symbolCounter++}`,type:e,name:t,constraints:[],source:n}}addConstraint(e,t,n,r){e.constraints.push({type:t,expression:n,description:r})}},ye=class extends X{async executeJSVMP(n){let r=Date.now(),{instructions:a,vmType:o=`custom`,maxSteps:s=i,timeout:c=t}=n;e.info(` JSVMP...`),e.info(` : ${a.length}`),e.info(`VM type detected: ${o}`);let l=[],u=[];try{let t={pc:0,stack:[],registers:new Map,memory:new Map,pathConstraints:[]},n=0;for(;t.pc<a.length&&n<s;){if(Date.now()-r>c){l.push(`JSVMP`);break}let e=a[t.pc];if(!e){l.push(`: PC=${t.pc}`);break}if(u.push(this.cloneStateInternal(t)),t=this.executeInstruction(t,e,a),e.opcode===255)break;n++}let i=this.inferLogic(u,a),o=this.collectAllConstraints(u),d=this.calculateConfidence(u,a),f=Date.now()-r;return e.info(`JSVMP symbolic execution complete in ${f}ms`),e.info(` : ${n}`),e.info(` : ${(d*100).toFixed(1)}%`),{finalState:t,executionTrace:u,inferredLogic:i,constraints:o,confidence:d,warnings:l}}catch(t){throw e.error(`JSVMP`,t),t}}executeInstruction(t,n,r){let i=this.cloneStateInternal(t);switch(n.opcode){case 1:this.executePush(i,n.operands[0]);break;case 2:this.executePop(i);break;case 16:this.executeAdd(i);break;case 17:this.executeSub(i);break;case 18:this.executeMul(i);break;case 19:this.executeDiv(i);break;case 20:this.executeMod(i);break;case 32:this.executeAnd(i);break;case 33:this.executeOr(i);break;case 34:this.executeNot(i);break;case 35:this.executeXor(i);break;case 48:this.executeEq(i);break;case 49:this.executeNe(i);break;case 50:this.executeLt(i);break;case 51:this.executeLe(i);break;case 52:this.executeGt(i);break;case 53:this.executeGe(i);break;case 66:return this.executeJnz(i,this.asNumberOperand(n.operands[0])),i;case 68:return i.pc=r.length,i;case 3:this.executeDup(i);break;case 82:return this.executePush(i,n.operands[0]),i.pc++,i;case 80:this.executeLoad(i,this.asStringOperand(n.operands[0]));break;case 81:this.executeStore(i,this.asStringOperand(n.operands[0]));break;case 64:return i.pc=this.asNumberOperand(n.operands[0]),i;case 65:return this.executeJZ(i,this.asNumberOperand(n.operands[0])),i;case 67:this.executeCall(i,this.asStringOperand(n.operands[0]));break;default:e.warn(`: 0x${n.opcode.toString(16)}`)}return i.pc++,i}executePush(e,t){let n=this.createSymbolicValue(`unknown`,`const_${t}`,String(t));n.possibleValues=[t],e.stack.push(n)}asNumberOperand(e){return e}asStringOperand(e){return e}executePop(e){return e.stack.pop()}executeAdd(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} + ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} + ${t.name}`,``),e.stack.push(r)}}executeSub(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} - ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} - ${t.name}`,``),e.stack.push(r)}}executeMul(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} * ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} * ${t.name}`,``),e.stack.push(r)}}executeDiv(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} / ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} / ${t.name}`,``),e.stack.push(r)}}executeMod(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`number`,`${n.name} % ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} % ${t.name}`,``),e.stack.push(r)}}executeAnd(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} && ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} && ${t.name}`,``),e.stack.push(r)}}executeOr(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} || ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} || ${t.name}`,``),e.stack.push(r)}}executeNot(e){let t=e.stack.pop();if(t){let n=this.createSymbolicValue(`boolean`,`!${t.name}`);this.addConstraint(n,`custom`,`${n.name} = !${t.name}`,``),e.stack.push(n)}}executeXor(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} ^ ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} ^ ${t.name}`,``),e.stack.push(r)}}executeEq(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} === ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} === ${t.name}`,``),e.stack.push(r)}}executeNe(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} !== ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} !== ${t.name}`,``),e.stack.push(r)}}executeLt(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} < ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} < ${t.name}`,``),e.stack.push(r)}}executeLe(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} <= ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} <= ${t.name}`,``),e.stack.push(r)}}executeGt(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} > ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} > ${t.name}`,``),e.stack.push(r)}}executeGe(e){let t=e.stack.pop(),n=e.stack.pop();if(n&&t){let r=this.createSymbolicValue(`boolean`,`${n.name} >= ${t.name}`);this.addConstraint(r,`custom`,`${r.name} = ${n.name} >= ${t.name}`,``),e.stack.push(r)}}executeJnz(e,t){let n=e.stack.pop();if(n){let r={type:`inequality`,expression:`${n.name} != 0`,description:``};e.pathConstraints.push(r),e.pc=t}}executeDup(e){let t=e.stack[e.stack.length-1];if(t){let n=this.createSymbolicValue(t.type,t.name,t.source);n.constraints=[...t.constraints],t.possibleValues&&(n.possibleValues=[...t.possibleValues]),e.stack.push(n)}}executeLoad(e,t){let n=e.memory.get(t);if(n)e.stack.push(n);else{let n=this.createSymbolicValue(`unknown`,t,t);e.stack.push(n)}}executeStore(e,t){let n=e.stack.pop();n&&e.memory.set(t,n)}executeJZ(e,t){let n=e.stack.pop();if(n){let r={type:`equality`,expression:`${n.name} == 0`,description:``};e.pathConstraints.push(r),e.pc=t}}executeCall(t,n){e.info(` : ${n}`)}inferLogic(e,t){let n=[];for(let r=0;r<Math.min(e.length,10);r++){let i=e[r];if(!i)continue;let a=t[i.pc];a&&n.push(`${a.opcode}(${a.operands.join(`, `)}) at ${a.location}`)}return n.join(`
|
|
6
|
+
`)||``}collectAllConstraints(e){let t=[];for(let n of e){t.push(...n.pathConstraints);for(let e of n.stack)t.push(...e.constraints)}return t}calculateConfidence(e,t){let n=e.length/t.length;return Math.min(n,1)}cloneStateInternal(e){return{pc:e.pc,stack:[...e.stack],registers:new Map(e.registers),memory:new Map(e.memory),pathConstraints:[...e.pathConstraints]}}};function be(t){e.info(`Derotating string array...`);try{let n=x.parse(t,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=0;return S(n,{CallExpression(t){if(!C.isFunctionExpression(t.node.callee)&&!C.isArrowFunctionExpression(t.node.callee))return;let n=t.node.callee;if(!C.isFunctionExpression(n)||!C.isBlockStatement(n.body))return;let i=n.body.body.some(e=>C.isWhileStatement(e)),a=JSON.stringify(n.body).includes(`push`)&&JSON.stringify(n.body).includes(`shift`);i&&a&&(e.debug(`Found string array rotation IIFE`),t.remove(),r++)}}),r>0?(e.info(`Removed ${r} string array rotation functions`),w(n,{comments:!0,compact:!1}).code):t}catch(n){return e.error(`Failed to derotate string array:`,n),t}}const Z=S.default??S,Q=w.default??w,$=new Set([`summary`,`priority`,`incremental`,`full`]),xe=new Set([`structure`,`business`,`security`,`all`]),Se=new Set([`function`,`xhr`,`fetch`,`websocket`,`localstorage`,`cookie`]),Ce=new Set([`log`,`block`,`modify`]),we=new Set([`call`,`apply`]);var Te=class{collector;scriptManager;deobfuscator;advancedDeobfuscator;obfuscationDetector;analyzer;cryptoDetector;hookManager;jsvmpDeobfuscator;constructor(e){this.collector=e.collector,this.scriptManager=e.scriptManager,this.deobfuscator=e.deobfuscator,this.advancedDeobfuscator=e.advancedDeobfuscator,this.obfuscationDetector=e.obfuscationDetector,this.analyzer=e.analyzer,this.cryptoDetector=e.cryptoDetector,this.hookManager=e.hookManager,this.jsvmpDeobfuscator=new y}requireCodeArg(t,n){let r=t.code;return typeof r!=`string`||r.trim().length===0?(e.warn(`${n} called without valid code argument`),null):r}extractWebcrackArgs(e){let t={},n=g(e,`unpack`),r=g(e,`unminify`),i=g(e,`jsx`),a=g(e,`mangle`),o=g(e,`forceOutput`),s=g(e,`includeModuleCode`),c=d(e,`outputDir`),l=m(e,`maxBundleModules`);return n!==void 0&&(t.unpack=n),r!==void 0&&(t.unminify=r),i!==void 0&&(t.jsx=i),a!==void 0&&(t.mangle=a),o!==void 0&&(t.forceOutput=o),s!==void 0&&(t.includeModuleCode=s),c?.trim()&&(t.outputDir=c),l!==void 0&&(t.maxBundleModules=l),Array.isArray(e.mappings)&&(t.mappings=e.mappings.filter(e=>typeof e==`object`&&!!e&&typeof e.path==`string`&&typeof e.pattern==`string`)),t}async handleCollectCode(t){let n=g(t,`returnSummaryOnly`,!1),r=p(t,`smartMode`,$),i=o,a=e=>e.slice(0,i).map(e=>({url:e.url,type:e.type,size:e.size,sizeKB:(e.size/1024).toFixed(2),truncated:e.metadata?.truncated||!1,preview:`${e.content.substring(0,200)}...`})),u=e=>{let t=(Array.isArray(e.summaries)&&e.summaries.length>0?e.summaries:a(e.files)).slice(0,i),n=Array.isArray(e.summaries)?e.summaries.length:e.files.length,r=e.totalSize>0?e.totalSize:Array.isArray(e.summaries)?e.summaries.reduce((e,t)=>e+(typeof t.size==`number`?t.size:0),0):e.files.reduce((e,t)=>e+t.size,0);return{totalSize:r,totalSizeKB:(r/1024).toFixed(2),filesCount:n,summarizedFiles:t.length,omittedFiles:Math.max(0,n-t.length),collectTime:e.collectTime,summary:t}};r||=`summary`;let d=await this.collector.collect({url:h(t,`url`),includeInline:g(t,`includeInline`),includeExternal:g(t,`includeExternal`),includeDynamic:g(t,`includeDynamic`),smartMode:r,compress:g(t,`compress`),maxTotalSize:m(t,`maxTotalSize`),maxFileSize:t.maxFileSize?m(t,`maxFileSize`,0)*1024:void 0,priorities:t.priorities});if(n)return l({mode:`summary`,...u(d),hint:`Use get_script_source for specific files.`});let f=s,_=c,v=Buffer.byteLength(JSON.stringify(d),`utf8`);return d.totalSize>f||v>_?(e.warn(`Collected code is too large (collected=${(d.totalSize/1024).toFixed(2)}KB, response=${(v/1024).toFixed(2)}KB), returning summary mode.`),l({warning:`Code size exceeds safe response threshold; summary returned.`,...u(d),estimatedResponseSize:v,estimatedResponseSizeKB:(v/1024).toFixed(2),recommendations:[`Use get_script_source for targeted files.`,`Use more specific priority filters.`,`Use smartMode=summary for initial reconnaissance.`]})):l(d)}async handleSearchInScripts(e){await this.scriptManager.init();let t=d(e,`keyword`);if(!t)return l({success:!1,error:`keyword is required`});let n=m(e,`maxMatches`,100),r=g(e,`returnSummary`,!1),i=m(e,`maxContextSize`,5e4),a=await this.scriptManager.searchInScripts(t,{isRegex:g(e,`isRegex`),caseSensitive:g(e,`caseSensitive`),contextLines:m(e,`contextLines`),maxMatches:n}),o=JSON.stringify(a).length;if(r||o>i){let t=a.matches??[];return l({success:!0,keyword:e.keyword,totalMatches:t.length,resultSize:o,resultSizeKB:(o/1024).toFixed(2),truncated:o>i,reason:o>i?`Result too large (${(o/1024).toFixed(2)}KB > ${(i/1024).toFixed(2)}KB)`:`Summary mode enabled`,matchesSummary:t.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url,line:e.line,preview:`${(e.context??``).substring(0,100)}...`})),recommendations:[`Use more specific keywords.`,`Reduce maxMatches (current: ${n}).`,`Use get_script_source for targeted file retrieval.`]})}return l(a)}async handleExtractFunctionTree(e){let t=d(e,`scriptId`),n=d(e,`functionName`);if(!t)return l({success:!1,error:`scriptId is required`,hint:`Use get_all_scripts() to list available scripts and their scriptIds`});if(!n)return l({success:!1,error:`functionName is required`,hint:`Specify the name of the function to extract`});await this.scriptManager.init();let r=await this.scriptManager.getAllScripts();if(!r.some(e=>String(e.scriptId)===String(t))){let e=r.slice(0,10).map(e=>({scriptId:e.scriptId,url:e.url?.substring(0,80)}));return l({success:!1,error:`Script not found: ${t}`,hint:`The specified scriptId does not exist. Use get_all_scripts() to list available scripts.`,availableScripts:e.length>0?e:`No scripts loaded. Navigate to a page first.`,totalScripts:r.length})}try{return l({success:!0,...await this.scriptManager.extractFunctionTree(t,n,{maxDepth:m(e,`maxDepth`),maxSize:m(e,`maxSize`),includeComments:g(e,`includeComments`)})})}catch(e){return l({success:!1,error:e instanceof Error?e.message:String(e),hint:`Make sure the function name exists in the specified script`})}}async handleDeobfuscate(e){let t=this.requireCodeArg(e,`deobfuscate`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});if(p(e,`engine`,new Set([`auto`,`webcrack`]),`auto`)===`webcrack`)return l(await this.advancedDeobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e),...typeof e.detectOnly==`boolean`?{detectOnly:e.detectOnly}:{}}));let n=await this.deobfuscator.deobfuscate({code:t,...this.extractWebcrackArgs(e)});return n&&typeof n==`object`&&`success`in n&&n.success===!1&&!(`error`in n)?l({...n,error:n.reason||`deobfuscation failed`}):l(n)}async handleUnderstandCode(e){let t=this.requireCodeArg(e,`understand_code`);return l(t?await this.analyzer.understand({code:t,context:f(e,`context`),focus:p(e,`focus`,xe,`all`)}):{success:!1,error:`code is required and must be a non-empty string`})}async handleDetectCrypto(e){let t=this.requireCodeArg(e,`detect_crypto`);return l(t?await this.cryptoDetector.detect({code:t}):{success:!1,error:`code is required and must be a non-empty string`})}async handleManageHooks(e){let t=h(e,`action`);switch(t){case`create`:return l(await this.hookManager.createHook({target:h(e,`target`),type:p(e,`type`,Se)??`function`,action:p(e,`hookAction`,Ce,`log`),customCode:d(e,`customCode`)}));case`list`:return l({hooks:this.hookManager.getAllHooks()});case`records`:return l({records:this.hookManager.getHookRecords(h(e,`hookId`))});case`clear`:return this.hookManager.clearHookRecords(d(e,`hookId`)),l({success:!0,message:`Hook records cleared`});default:return l({success:!1,message:`Unknown hook action: ${t}. Valid actions: create, list, records, clear`})}}async handleDetectObfuscation(e){let t=this.requireCodeArg(e,`detect_obfuscation`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=g(e,`generateReport`,!0),r=this.obfuscationDetector.detect(t);if(!n)return l(r);let i=this.obfuscationDetector.generateReport(r);return u(`${JSON.stringify(r,null,2)}\n\n${i}`)}async handleWebcrackUnpack(e){let t=this.requireCodeArg(e,`webcrack_unpack`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=await b(t,{unpack:g(e,`unpack`,!0),unminify:g(e,`unminify`,!0),jsx:g(e,`jsx`,!0),mangle:g(e,`mangle`,!1),...this.extractWebcrackArgs(e)});return n.applied?l({success:!0,code:n.code,bundle:n.bundle,savedTo:n.savedTo,savedArtifacts:n.savedArtifacts,optionsUsed:n.optionsUsed,engine:`webcrack`}):l({success:!1,error:n.reason||`webcrack execution failed`,optionsUsed:n.optionsUsed,engine:`webcrack`})}async handleWebpackEnumerate(e){return ve(this.collector,e)}async handleClearCollectedData(){return v(async()=>(await this.collector.clearAllData(),this.scriptManager.clear(),{message:`All collected data cleared.`,cleared:{fileCache:!0,compressionCache:!0,collectedUrls:!0,scriptManager:!0}}))}async handleGetCollectionStats(){return v(async()=>{let e=await this.collector.getAllStats();return{stats:e,summary:{totalCachedFiles:e.cache.memoryEntries+e.cache.diskEntries,totalCacheSize:`${(e.cache.totalSize/1024).toFixed(2)} KB`,compressionRatio:`${e.compression.averageRatio.toFixed(1)}%`,cacheHitRate:e.compression.cacheHits>0?`${(e.compression.cacheHits/(e.compression.cacheHits+e.compression.cacheMisses)*100).toFixed(1)}%`:`0%`,collectedUrls:e.collector.collectedUrls}}})}async handleJsDeobfuscateJsvmp(e){let t=this.requireCodeArg(e,`js_deobfuscate_jsvmp`);if(!t)return l({success:!1,error:`code is required and must be a non-empty string`});let n=g(e,`detectOnly`,!1),r=await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:g(e,`aggressive`,!1),extractInstructions:g(e,`extractInstructions`,!0),timeout:m(e,`timeout`,3e4)});return l(n?{success:!0,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,confidence:r.confidence,instructionCount:r.instructions?.length}:{success:r.isJSVMP,isJSVMP:r.isJSVMP,vmType:r.vmType,vmFeatures:r.vmFeatures,instructions:r.instructions,deobfuscatedCode:r.deobfuscatedCode,confidence:r.confidence,warnings:r.warnings,unresolvedParts:r.unresolvedParts,stats:r.stats})}async handleJsDeobfuscatePipeline(e){let t=this.requireCodeArg(e,`js_deobfuscate_pipeline`);if(!t)return l({success:!1,error:`code is required`});let n=g(e,`useWebcrack`,!0),r=g(e,`aggressive`,!1),i=g(e,`humanize`,!0),a=g(e,`returnStageDetails`,!1),o=Date.now(),s=t,c=[],u=L(s);u!==s&&(s=u,c.push(`constant_fold`));let d=R(s);d!==s&&(s=d,c.push(`dead_code_remove`));let f=s,p=!1,m,h;if(n)try{let e=await b(s,{unminify:!0,unpack:!0});e.applied?(f=e.code,p=!0):m=e.reason?`webcrack stage did not apply: ${e.reason}`:`webcrack stage did not apply any transformation.`}catch(e){h=e instanceof Error?e.message:String(e)}if(r){let e=z(f);e!==f&&(f=e)}let _=f,v=0;if(i){let e=B(_);e.code!==_&&(_=e.code,v=e.count)}let y=Date.now()-o,x=t.length>0?1-_.length/t.length:0,S={success:!m&&!h,deobfuscatedCode:_,...m?{warning:m}:{},...h?{error:`webcrack stage failed: ${h}`}:{},stats:{originalSize:t.length,finalSize:_.length,reductionRate:Math.round(x*1e3)/10,processingTimeMs:y,stages:{preprocessor:{transforms:c,sizeAfter:s.length},deobfuscator:{webcrackApplied:p,sizeAfter:f.length,...m?{warning:m}:{},...h?{error:h}:{}},humanizer:{renameCount:v,sizeAfter:_.length}}}};return a&&(S.stageDetails={preprocessed:s.substring(0,5e3),deobfuscated:f.substring(0,5e3)}),l(S)}async handleJsAnalyzeVm(e){let t=this.requireCodeArg(e,`js_analyze_vm`);if(!t)return l({success:!1,error:`code is required`});let n=g(e,`extractBytecode`,!0);return l(_e({code:t,extractBytecode:n,mapOpcodes:g(e,`mapOpcodes`,!0),vmResult:await this.jsvmpDeobfuscator.deobfuscate({code:t,aggressive:!1,extractInstructions:n,timeout:15e3})}))}async handleJsSolveConstraints(e){let t=this.requireCodeArg(e,`js_solve_constraints`);return l(t?pe({code:t,replaceInPlace:g(e,`replaceInPlace`,!0),maxIterations:m(e,`maxIterations`,100)}):{success:!1,error:`code is required`})}async handleAnalysisAstMatch(e){let t=d(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=d(e,`nodeType`);if(!n)return l({success:!1,error:`nodeType is required`});let r=m(e,`maxResults`,50),i=d(e,`filter`),a;if(i)try{a=JSON.parse(i)}catch{return l({success:!1,error:`filter must be valid JSON`})}let o;try{o=x.parse(t,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let s=[],c=n;function u(e){if(!a)return!0;for(let[t,n]of Object.entries(a)){let r=t.split(`.`),i=e;for(let e of r){if(typeof i!=`object`||!i)return!1;i=i[e]}if(String(i)!==String(n))return!1}return!0}function f(e){let t={};for(let n of Object.keys(e)){if(n===`type`||n===`start`||n===`end`||n===`loc`||n===`range`)continue;let r=e[n];r==null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t[n]=r:Array.isArray(r)&&r.length<=5?t[n]=r.map(e=>typeof e==`object`&&e&&`type`in e?{type:e.type}:e):typeof r==`object`&&r&&`type`in r&&(t[n]={type:r.type})}return t}return Z(o,{enter(e){let n=e.node;n.type===c&&u(n)&&(s.push({type:n.type,start:n.start??-1,end:n.end??-1,code:t.slice(n.start??0,n.end??0),properties:f(n)}),s.length>=r&&e.stop())}}),l({success:!0,matches:s,total:s.length,nodeType:n})}async handleAnalysisDeflatControlFlow(e){let t=d(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n;try{n=x.parse(t,{sourceType:`unambiguous`})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let r=g(e,`removeDispatcher`,!0),i=this.preprocessDeflatCode(t);if(i.code!==t)try{n=x.parse(i.code,{sourceType:`unambiguous`})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}let a=0,o=new Set,s=this.resolveDispatcherArray.bind(this);Z(n,{WhileStatement:e=>{let t=e.node.test;if(t.type!==`BooleanLiteral`||t.value!==!0)return;let n=e.node.body;if(n.type!==`BlockStatement`)return;let r=n.body.find(e=>e.type===`SwitchStatement`);if(!r)return;let i=r.discriminant;if(i.type!==`MemberExpression`||!i.computed)return;let c=i.object;if(c.type!==`Identifier`)return;let l=c.name,u,d=i.property;if(d.type===`Identifier`?u=d.name:d.type===`UpdateExpression`&&d.argument.type===`Identifier`&&(u=d.argument.name),!u)return;let f=r.cases;if(f.length===0)return;let p=new Map;for(let e of f)!e.test||e.test.type!==`StringLiteral`||p.set(e.test.value,e.consequent);let m=e.scope.getBinding(l),h=e.scope.getBinding(u);if(!m||!h)return;let g=s(e,l);if(!g)return;let _=[];if(g.type===`ArrayExpression`)for(let e of g.elements)e&&e.type===`StringLiteral`&&_.push(e.value);else if(g.type===`CallExpression`&&g.callee.type===`MemberExpression`&&g.callee.property.type===`Identifier`&&g.callee.property.name===`split`&&g.arguments[0]?.type===`StringLiteral`){let e=g.arguments[0].value,t=g.callee.object;t.type===`StringLiteral`&&_.push(...t.value.split(e))}if(_.length===0)return;let v=[];for(let e of _){let t=p.get(e);if(t)for(let e of t)e.type!==`BreakStatement`&&e.type!==`ContinueStatement`&&v.push(e)}e.replaceWith(C.blockStatement(v)),o.add(m.identifier),o.add(h.identifier),a++}}),r&&o.size>0&&Z(n,{VariableDeclarator(e){if(e.node.id.type===`Identifier`&&o.has(e.node.id)){let t=e.parent;t.type===`VariableDeclaration`&&t.declarations.length===1?e.parentPath.remove():e.remove()}}});let c=Q(n,{retainLines:!0}).code;return l({success:!0,code:c,flattenedCount:a,dispatchersRemoved:r?o.size:0,helperTransforms:i.transforms})}async handleAnalysisDecodeStringArray(e){let t=d(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=m(e,`maxReplacements`,200),r=g(e,`removeRotation`,!0),i=r?be(t):t,a=new Map,o;try{o=x.parse(i,{sourceType:`unambiguous`,plugins:[`jsx`,`typescript`]})}catch(e){return l({success:!1,error:`Parse error: ${e instanceof Error?e.message:String(e)}`})}Z(o,{VariableDeclarator(e){if(!C.isIdentifier(e.node.id)||!C.isArrayExpression(e.node.init))return;let t=[];for(let n of e.node.init.elements){if(!C.isStringLiteral(n))return;t.push(n.value)}a.set(e.node.id.name,t)}});let s=[],c=0;return Z(o,{CallExpression(e){if(c>=n){e.stop();return}if(!C.isIdentifier(e.node.callee))return;let t=e.node.callee.name,r=a.get(t);if(!r||e.node.arguments.length!==1)return;let i=e.node.arguments[0];if(!C.isNumericLiteral(i)&&!C.isStringLiteral(i))return;let o=C.isNumericLiteral(i)?i.value:i.value.startsWith(`0x`)?Number.parseInt(i.value,16):Number(i.value);if(!Number.isInteger(o)||o<0||o>=r.length)return;let l=r[o];typeof l==`string`&&(s.push({arrayName:t,index:o,value:l,original:Q(e.node,{compact:!0}).code}),e.replaceWith(C.stringLiteral(l)),c+=1)}}),l({success:!0,code:Q(o,{retainLines:!0}).code,replacedCount:c,arraysFound:a.size,rotationRemoved:r&&i!==t,replacements:s})}preprocessDeflatCode(e){let t=e,n=[];return t=t.replace(/(\b[a-zA-Z_$][\w$]*)\[['"]([a-zA-Z_$][\w$]*)['"]\]\(([^)]*)\)/g,(e,t,r,i)=>we.has(r)?(n.push(`helper-member-call`),`${t}.${r}(${i})`):e),{code:t,transforms:n}}resolveDispatcherArray(e,t){let n=e.scope.getBinding(t);if(!n?.path.isVariableDeclarator())return null;let r=n.path.node.init;if(r)return r;let i=n.path.parentPath;if(!i.isVariableDeclaration())return null;let a=i.getAllNextSiblings();for(let e of a){if(!e.isExpressionStatement())continue;let n=e.node.expression;if(!(!C.isAssignmentExpression(n)||n.operator!==`=`||!C.isIdentifier(n.left,{name:t})))return n.right}return null}async handleJsSymbolicExecute(e){let t=h(e,`code`);if(!t)return l({success:!1,error:`code is required`});let n=m(e,`maxPaths`),r=m(e,`maxDepth`),i=m(e,`timeout`),a=g(e,`enableConstraintSolving`,!1);return v(async()=>await new X().execute({code:t,...n===void 0?{}:{maxPaths:n},...r===void 0?{}:{maxDepth:r},...i===void 0?{}:{timeout:i},enableConstraintSolving:a}))}async handleJsSymbolicExecuteJsvmp(e){let t=f(e,`instructions`);if(!t||!Array.isArray(t))return l({success:!1,error:`instructions array is required (from js_analyze_vm output)`});let n=d(e,`vmType`),r=m(e,`maxSteps`),i=m(e,`timeout`);return v(async()=>await new ye().executeJSVMP({instructions:t,...n?{vmType:n}:{},...r===void 0?{}:{maxSteps:r},...i===void 0?{}:{timeout:i}}))}};export{Te as CoreAnalysisHandlers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as e,r as t,t as n}from"./parse-args-
|
|
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 () {
|
|
2
2
|
var globalObj = typeof window !== 'undefined' ? window : globalThis;
|
|
3
3
|
var installFlag = '__ANTI_DEBUGGER_STATEMENT_INSTALLED__';
|
|
4
4
|
if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
|
|
@@ -486,7 +486,7 @@ import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i
|
|
|
486
486
|
globalObj.Error = PatchedError;
|
|
487
487
|
} catch (_) {}
|
|
488
488
|
}
|
|
489
|
-
})();`},
|
|
489
|
+
})();`},s={bypassConsoleDetect:`(function () {
|
|
490
490
|
var globalObj = typeof window !== 'undefined' ? window : globalThis;
|
|
491
491
|
var installFlag = '__ANTI_DEBUG_CONSOLE_INSTALLED__';
|
|
492
492
|
if (Object.prototype.hasOwnProperty.call(globalObj, installFlag)) {
|
|
@@ -672,7 +672,7 @@ import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i
|
|
|
672
672
|
} catch (_) {}
|
|
673
673
|
}
|
|
674
674
|
}
|
|
675
|
-
})();`},
|
|
675
|
+
})();`},c={detectProtections:`(async function () {
|
|
676
676
|
function pushUnique(list, value) {
|
|
677
677
|
if (list.indexOf(value) === -1) {
|
|
678
678
|
list.push(value);
|
|
@@ -827,4 +827,4 @@ import{o as e,r as t,t as n}from"./parse-args-Cuk7-xUt.mjs";import{o as r,s as i
|
|
|
827
827
|
sourceBytesApprox: sourceBlob.length
|
|
828
828
|
}
|
|
829
829
|
};
|
|
830
|
-
})();`},
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-sBC6IdRT.mjs";import{Tr as t,b as n,y as r}from"./constants-Cp6hBrrx.mjs";import{i,l as a,n as o}from"./outputPaths-BonGThuc.mjs";import{n as s,r as c}from"./artifacts-B5xQuEa_.mjs";import{join as l,resolve as u}from"node:path";import{readdir as d,rm as f,stat as p}from"node:fs/promises";var m=class n{static instance;MAX_TOKENS=t;WARNING_THRESHOLDS=[.8,.9,.95];BYTES_PER_TOKEN=4;AUTO_CLEANUP_THRESHOLD=.9;HISTORY_RETENTION=300*1e3;currentUsage=0;toolCallHistory=[];warnings=new Set;sessionStartTime=Date.now();trackingEnabled=!0;MAX_ESTIMATION_DEPTH=4;MAX_ESTIMATION_ARRAY_ITEMS=50;MAX_ESTIMATION_OBJECT_KEYS=50;MAX_ESTIMATION_STRING_LENGTH=2e3;MAX_ESTIMATION_BYTES=256*1024;externalCleanupFn=null;constructor(){e.info(`TokenBudgetManager initialized`)}static getInstance(){return this.instance||=new n,this.instance}setExternalCleanup(e){this.externalCleanupFn=e}recordToolCall(t,n,r){if(this.trackingEnabled)try{let i=this.calculateSize(n),a=this.calculateSize(r),o=i+a,s=this.estimateTokens(o);this.currentUsage+=s;let c={toolName:t,timestamp:Date.now(),requestSize:i,responseSize:a,estimatedTokens:s,cumulativeTokens:this.currentUsage};this.toolCallHistory.push(c),e.debug(`Token usage: ${this.currentUsage}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%) | Tool: ${t} | Size: ${(o/1024).toFixed(1)}KB | Tokens: ${s}`),this.checkWarnings(),this.shouldAutoCleanup()&&this.autoCleanup()}catch(t){e.error(`Failed to record tool call:`,t)}}isRecord(e){return typeof e==`object`&&!!e}hasDetailedSummarySize(e){if(!this.isRecord(e)||!(`detailId`in e))return!1;let t=e.summary;if(!this.isRecord(t))return!1;let{size:n}=t;return typeof n==`number`&&Number.isFinite(n)&&n>0}tryEstimateMcpEnvelope(e){if(!this.isRecord(e))return null;let t=e.content;if(!Array.isArray(t)||t.length===0)return null;let n=t[0];if(!this.isRecord(n)||n.type!==`text`||typeof n.text!=`string`)return null;let r=n.text,i=r.length>this.MAX_ESTIMATION_STRING_LENGTH?`${r.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)}...[truncated:${r.length}]`:r,a=42+(e.isError===!0?14:0),o=Buffer.byteLength(i,`utf8`);return Math.min(a+o,this.MAX_ESTIMATION_BYTES)}calculateSize(t){try{if(this.hasDetailedSummarySize(t))return Math.min(t.summary.size,this.MAX_ESTIMATION_BYTES);let e=this.tryEstimateMcpEnvelope(t);if(e!==null)return e;let n=this.normalizeForSizeEstimate(t,0,new WeakSet),r=JSON.stringify(n);return r?Math.min(Buffer.byteLength(r,`utf8`),this.MAX_ESTIMATION_BYTES):0}catch(t){return e.warn(`Failed to calculate data size:`,t),0}}normalizeForSizeEstimate(e,t,n){if(e==null)return e;let r=typeof e;if(r===`boolean`||r===`number`)return e;if(r===`string`){let t=e;if(t.length<=this.MAX_ESTIMATION_STRING_LENGTH)return t;let n=`...[truncated:${t.length}]`,r=Math.max(this.MAX_ESTIMATION_STRING_LENGTH-n.length,0);return`${t.slice(0,r)}${n}`}if(r===`bigint`||r===`symbol`)return e.toString();if(r===`function`)return`[Function]`;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack?.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)};if(Buffer.isBuffer(e))return`[Buffer:${e.byteLength}]`;if(t>=this.MAX_ESTIMATION_DEPTH)return Array.isArray(e)?`[Array:${e.length}]`:`[Object]`;if(Array.isArray(e)){let r=e.slice(0,this.MAX_ESTIMATION_ARRAY_ITEMS).map(e=>this.normalizeForSizeEstimate(e,t+1,n));return e.length>this.MAX_ESTIMATION_ARRAY_ITEMS&&r.push(`[truncated:${e.length-this.MAX_ESTIMATION_ARRAY_ITEMS}]`),r}if(r===`object`){if(!this.isRecord(e))return`[Object]`;if(n.has(e))return`[Circular]`;n.add(e);let r=Object.entries(e),i=r.slice(0,this.MAX_ESTIMATION_OBJECT_KEYS),a={};for(let[e,r]of i)a[e]=this.normalizeForSizeEstimate(r,t+1,n);return r.length>this.MAX_ESTIMATION_OBJECT_KEYS&&(a.__truncatedKeys=r.length-this.MAX_ESTIMATION_OBJECT_KEYS),a}return String(e)}estimateTokens(e){return Math.ceil(e/this.BYTES_PER_TOKEN)}getUsagePercentage(){return Math.round(this.currentUsage/this.MAX_TOKENS*100)}checkWarnings(){let e=this.currentUsage/this.MAX_TOKENS;for(let t of this.WARNING_THRESHOLDS)e>=t&&!this.warnings.has(t)&&(this.emitWarning(t),this.warnings.add(t))}emitWarning(t){let n=Math.round(t*100),r=this.MAX_TOKENS-this.currentUsage;e.warn(`Token Budget Warning: ${n}% used! (${this.currentUsage}/${this.MAX_TOKENS}, ${r} tokens remaining)`),t>=.95?e.warn(`CRITICAL: Consider clearing caches or starting a new session.`):t>=.9?e.warn(`HIGH: Auto-cleanup will trigger soon. Consider using summary modes.`):t>=.8&&e.warn(`MODERATE: Monitor usage. Use get_token_budget_stats for details.`)}shouldAutoCleanup(){return this.currentUsage/this.MAX_TOKENS>=this.AUTO_CLEANUP_THRESHOLD}autoCleanup(){e.info(`Auto-cleanup triggered at 90% usage.`);let t=this.currentUsage;if(this.externalCleanupFn)try{this.externalCleanupFn(),e.info(`External cleanup callback invoked`)}catch(t){e.warn(`External cleanup callback failed:`,t)}let n=Date.now()-this.HISTORY_RETENTION,r=this.toolCallHistory.length;this.toolCallHistory=this.toolCallHistory.filter(e=>e.timestamp>n);let i=r-this.toolCallHistory.length;e.info(`Removed ${i} old tool call records`),this.recalculateUsage();let a=this.currentUsage,o=t-a,s=Math.round(o/this.MAX_TOKENS*100);e.info(`Cleanup complete. Freed ${o} tokens (${s}%). Usage: ${a}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%)`);let c=a/this.MAX_TOKENS;this.warnings=new Set(Array.from(this.warnings).filter(e=>c>=e))}recalculateUsage(){this.currentUsage=this.toolCallHistory.reduce((e,t)=>e+t.estimatedTokens,0)}getStats(){let e=new Map;for(let t of this.toolCallHistory){let n=e.get(t.toolName)||0;e.set(t.toolName,n+t.estimatedTokens)}let t=Array.from(e.entries()).map(([e,t])=>({tool:e,tokens:t,percentage:Math.round(t/this.currentUsage*100)})).toSorted((e,t)=>t.tokens-e.tokens).slice(0,10),n=this.generateSuggestions(t),r=this.toolCallHistory.slice(-20);return{currentUsage:this.currentUsage,maxTokens:this.MAX_TOKENS,usagePercentage:this.getUsagePercentage(),toolCallCount:this.toolCallHistory.length,topTools:t,warnings:Array.from(this.warnings).map(e=>Math.round(e*100)),recentCalls:r,suggestions:n,sessionStartTime:this.sessionStartTime}}generateSuggestions(e){let t=[],n=this.currentUsage/this.MAX_TOKENS;n>=.95?t.push(` CRITICAL: Clear all caches immediately or start a new session`):n>=.9?t.push(`HIGH: Auto-cleanup triggered. Consider manual cleanup for better control`):n>=.8&&t.push(`MODERATE: Monitor usage closely. Use summary modes for large data`);for(let{tool:n,percentage:r}of e)r>30&&(n.includes(`collect_code`)?t.push(` ${n} uses ${r}% tokens. Try smartMode="summary" or "priority"`):n.includes(`get_script_source`)?t.push(` ${n} uses ${r}% tokens. Try preview=true first`):n.includes(`network_get_requests`)?t.push(` ${n} uses ${r}% tokens. Reduce limit or use filters`):n.includes(`page_evaluate`)&&t.push(` ${n} uses ${r}% tokens. Query specific properties instead of full objects`));return t.length===0&&t.push(` Token usage is healthy. Continue monitoring.`),t}manualCleanup(){e.info(`Manual cleanup requested.`),this.autoCleanup()}setTrackingEnabled(t){this.trackingEnabled!==t&&(this.trackingEnabled=t,e.warn(`Token budget tracking ${t?`enabled`:`disabled`}`))}isTrackingEnabled(){return this.trackingEnabled}reset(){e.info(`Resetting token budget...`),this.currentUsage=0,this.toolCallHistory=[],this.warnings.clear(),this.sessionStartTime=Date.now(),e.info(`Token budget reset complete`)}},h=class t{static instance;GLOBAL_MAX_SIZE=r;LOW_HIT_RATE_THRESHOLD=n;caches=new Map;constructor(){e.info(`UnifiedCacheManager initialized`)}static getInstance(){return this.instance||=new t,this.instance}registerCache(t){this.caches.set(t.name,t),e.info(`Registered cache: ${t.name}`)}unregisterCache(t){this.caches.delete(t),e.info(`Unregistered cache: ${t}`)}async getGlobalStats(){let t=0,n=0,r=0,i=0,a=[];for(let[o,s]of this.caches)try{let e=await s.getStats();t+=e.entries,n+=e.size,r+=e.hits||0,i+=e.misses||0,a.push({name:o,entries:e.entries,size:e.size,sizeMB:(e.size/1024/1024).toFixed(2),hitRate:e.hitRate,ttl:e.ttl})}catch(t){e.error(`Failed to get stats for cache ${o}:`,t)}let o=r+i>0?r/(r+i):0,s=this.generateRecommendations(n,o,a);return{totalEntries:t,totalSize:n,totalSizeMB:(n/1024/1024).toFixed(2),hitRate:o,caches:a,recommendations:s}}async smartCleanup(t){let n=t||this.GLOBAL_MAX_SIZE*.7,r=await this.getGlobalStats(),i=r.totalSize;if(i<=n)return e.info(`No cleanup needed`),{before:i,after:i,freed:0,freedPercentage:0};e.info(`Smart cleanup: current ${r.totalSizeMB}MB, target ${(n/1024/1024).toFixed(2)}MB`),await this.cleanupExpired();let a=await this.getGlobalStats();if(a.totalSize<=n||(await this.cleanupLowHitRate(),a=await this.getGlobalStats(),a.totalSize<=n))return this.calculateCleanupResult(i,a.totalSize);await this.cleanupLargeItems();let o=await this.getGlobalStats();return this.calculateCleanupResult(i,o.totalSize)}async cleanupExpired(){e.info(`Cleaning up expired data...`);for(let[t,n]of this.caches)if(n.cleanup)try{await n.cleanup(),e.debug(`Cleaned up expired data in ${t}`)}catch(n){e.error(`Failed to cleanup ${t}:`,n)}}async cleanupLowHitRate(){e.info(`Cleaning up low hit rate caches...`);let t=await this.getGlobalStats(),n=t.hitRate;for(let r of t.caches)if(r.hitRate!==void 0&&r.hitRate<n*this.LOW_HIT_RATE_THRESHOLD){let t=this.caches.get(r.name);if(t?.clear)try{await t.clear(),e.info(`Cleared low hit rate cache: ${r.name} (${(r.hitRate*100).toFixed(1)}%)`)}catch(t){e.error(`Failed to clear ${r.name}:`,t)}}}async cleanupLargeItems(){e.info(`Cleaning up large caches...`);let t=(await this.getGlobalStats()).caches.toSorted((e,t)=>t.size-e.size);for(let n of t.slice(0,2)){let t=this.caches.get(n.name);if(t?.clear)try{await t.clear(),e.info(`Cleared large cache: ${n.name} (${n.sizeMB}MB)`)}catch(t){e.error(`Failed to clear ${n.name}:`,t)}}}calculateCleanupResult(t,n){let r=t-n,i=Math.round(r/this.GLOBAL_MAX_SIZE*100);return e.info(`Cleanup complete! Freed ${(r/1024/1024).toFixed(2)}MB (${i}%). Usage: ${(n/1024/1024).toFixed(2)}MB/${(this.GLOBAL_MAX_SIZE/1024/1024).toFixed(0)}MB`),{before:t,after:n,freed:r,freedPercentage:i}}async clearAll(){e.info(`Clearing all caches...`);for(let[t,n]of this.caches)if(n.clear)try{await n.clear(),e.info(`Cleared cache: ${t}`)}catch(n){e.error(`Failed to clear ${t}:`,n)}e.success(`All caches cleared`)}async preheat(t){e.info(`Preheating cache for ${t.length} URLs...`),e.info(`Cache preheat completed`)}generateRecommendations(e,t,n){let r=[],i=e/this.GLOBAL_MAX_SIZE;i>=.9?r.push(` CRITICAL: Cache size at 90%. Run smart_cache_cleanup immediately!`):i>=.7?r.push(`WARNING: Cache size at 70%. Consider cleanup soon.`):i>=.5&&r.push(`INFO: Cache size at 50%. Monitor usage.`),t<.3?r.push(` Low cache hit rate (<30%). Consider adjusting TTL or cache strategy.`):t>.7&&r.push(` Good cache hit rate (>70%). Cache is working well.`);for(let t of n){let n=t.size/e;n>.5&&r.push(` ${t.name} uses ${Math.round(n*100)}% of total cache. Consider cleanup.`),t.hitRate!==void 0&&t.hitRate<.2&&r.push(` ${t.name} has low hit rate (${(t.hitRate*100).toFixed(1)}%). Consider disabling or adjusting.`)}return r.length===0&&r.push(` Cache health is good. No action needed.`),r}};function g(e=process.env){let t=Math.max(0,parseInt(e.MCP_ARTIFACT_RETENTION_DAYS??`0`,10)||0),n=Math.max(0,parseInt(e.MCP_ARTIFACT_MAX_TOTAL_MB??`0`,10)||0),r=Math.max(0,parseInt(e.MCP_ARTIFACT_CLEANUP_INTERVAL_MINUTES??`0`,10)||0),i=[`1`,`true`].includes((e.MCP_ARTIFACT_CLEANUP_ON_START??``).toLowerCase());return{enabled:t>0||n>0,retentionDays:t,maxTotalBytes:n*1024*1024,cleanupOnStart:i,cleanupIntervalMinutes:r}}async function _(e){let t=g(),n={...t,retentionDays:e?.retentionDays??t.retentionDays,maxTotalBytes:e?.maxTotalBytes??t.maxTotalBytes},r=e?.now??Date.now(),a=e?.dryRun??!1,o=e?.directories??y(),s=n.retentionDays>0?r-n.retentionDays*864e5:0,c=0,l=0,u=0,d=0,p=0,m=[],h=[],_=i(),v=[];function S(e){v.push(f(e,{force:!0}).then(()=>void 0).catch(()=>void 0))}for(let e of o)await b(e,_,s,a,e=>{c++,s>0&&e.mtimeMs<s?(l++,u+=e.size,d+=e.size,h.length<20&&h.push(e.relativePath),a||S(e.path)):m.push(e)});if(n.maxTotalBytes>0){let e=m.reduce((e,t)=>e+t.size,0);if(e>n.maxTotalBytes){m.sort((e,t)=>e.mtimeMs-t.mtimeMs);let t=0;for(;t<m.length&&e>n.maxTotalBytes;){let n=m[t];e-=n.size,l++,u+=n.size,p+=n.size,h.length<20&&h.push(n.relativePath),a||S(n.path),t++}m.splice(0,t)}}return a||(await Promise.all(v),await Promise.all(o.map(e=>x(e)))),{success:!0,scannedFiles:c,removedFiles:l,removedBytes:u,removedByAge:d,removedBySize:p,remainingFiles:m.length,remainingBytes:m.reduce((e,t)=>e+t.size,0),dryRun:a,directories:o,removedSample:h,config:n}}function v(){let t=g();if(!t.enabled||t.cleanupIntervalMinutes<=0)return null;let n=setInterval(()=>{_().then(t=>{t.removedFiles>0&&e.info(`[artifacts] retention cleanup removed ${t.removedFiles} files (${t.removedBytes} bytes)`)}).catch(t=>{e.warn(`[artifacts] retention cleanup failed`,t)})},t.cleanupIntervalMinutes*60*1e3);return n.unref(),()=>clearInterval(n)}function y(){let e=i(),t=u(process.cwd(),`debugger-sessions`),n=u(e,`debugger-sessions`),r=new Set([c(),a().paths.screenshotDir,o(),t,n]);for(let e of[`wasm`,`traces`,`profiles`,`dumps`,`reports`,`har`,`sessions`,`tmp`])r.add(s(e));return[...r]}async function b(e,t,n,r,i){let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=l(e,o.name);if(o.isDirectory())await b(a,t,n,r,i);else if(o.isFile()){let e;try{e=await p(a)}catch{continue}i({path:a,relativePath:S(t,a),size:e.size,mtimeMs:e.mtimeMs})}}}async function x(e){let t;try{t=await d(e,{withFileTypes:!0})}catch{return}await Promise.all(t.filter(e=>e.isDirectory()).map(t=>x(l(e,t.name))));try{(await d(e)).length===0&&await f(e,{recursive:!0,force:!0})}catch{}}function S(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^[\\/]/,``).replace(/\\/g,`/`):t.replace(/\\/g,`/`)}export{m as a,h as i,g as n,v as r,_ as t};
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{Xr as t,g as n,h as r}from"./constants-BYj8Xek8.mjs";import{i,l as a,n as o}from"./outputPaths-B4Ic4RZh.mjs";import{n as s,r as c}from"./artifacts-CkodUM4j.mjs";import{join as l,resolve as u}from"node:path";import{readdir as d,rm as f,stat as p}from"node:fs/promises";var m=class n{static instance;MAX_TOKENS=t;WARNING_THRESHOLDS=[.8,.9,.95];BYTES_PER_TOKEN=4;AUTO_CLEANUP_THRESHOLD=.9;HISTORY_RETENTION=300*1e3;currentUsage=0;toolCallHistory=[];warnings=new Set;sessionStartTime=Date.now();trackingEnabled=!0;MAX_ESTIMATION_DEPTH=4;MAX_ESTIMATION_ARRAY_ITEMS=50;MAX_ESTIMATION_OBJECT_KEYS=50;MAX_ESTIMATION_STRING_LENGTH=2e3;MAX_ESTIMATION_BYTES=256*1024;externalCleanupFn=null;constructor(){e.info(`TokenBudgetManager initialized`)}static getInstance(){return this.instance||=new n,this.instance}setExternalCleanup(e){this.externalCleanupFn=e}recordToolCall(t,n,r){if(this.trackingEnabled)try{let i=this.calculateSize(n),a=this.calculateSize(r),o=i+a,s=this.estimateTokens(o);this.currentUsage+=s;let c={toolName:t,timestamp:Date.now(),requestSize:i,responseSize:a,estimatedTokens:s,cumulativeTokens:this.currentUsage};this.toolCallHistory.push(c),e.debug(`Token usage: ${this.currentUsage}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%) | Tool: ${t} | Size: ${(o/1024).toFixed(1)}KB | Tokens: ${s}`),this.checkWarnings(),this.shouldAutoCleanup()&&this.autoCleanup()}catch(t){e.error(`Failed to record tool call:`,t)}}isRecord(e){return typeof e==`object`&&!!e}hasDetailedSummarySize(e){if(!this.isRecord(e)||!(`detailId`in e))return!1;let t=e.summary;if(!this.isRecord(t))return!1;let{size:n}=t;return typeof n==`number`&&Number.isFinite(n)&&n>0}tryEstimateMcpEnvelope(e){if(!this.isRecord(e))return null;let t=e.content;if(!Array.isArray(t)||t.length===0)return null;let n=t[0];if(!this.isRecord(n)||n.type!==`text`||typeof n.text!=`string`)return null;let r=n.text,i=r.length>this.MAX_ESTIMATION_STRING_LENGTH?`${r.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)}...[truncated:${r.length}]`:r,a=42+(e.isError===!0?14:0),o=Buffer.byteLength(i,`utf8`);return Math.min(a+o,this.MAX_ESTIMATION_BYTES)}calculateSize(t){try{if(this.hasDetailedSummarySize(t))return Math.min(t.summary.size,this.MAX_ESTIMATION_BYTES);let e=this.tryEstimateMcpEnvelope(t);if(e!==null)return e;let n=this.normalizeForSizeEstimate(t,0,new WeakSet),r=JSON.stringify(n);return r?Math.min(Buffer.byteLength(r,`utf8`),this.MAX_ESTIMATION_BYTES):0}catch(t){return e.warn(`Failed to calculate data size:`,t),0}}normalizeForSizeEstimate(e,t,n){if(e==null)return e;let r=typeof e;if(r===`boolean`||r===`number`)return e;if(r===`string`){let t=e;if(t.length<=this.MAX_ESTIMATION_STRING_LENGTH)return t;let n=`...[truncated:${t.length}]`,r=Math.max(this.MAX_ESTIMATION_STRING_LENGTH-n.length,0);return`${t.slice(0,r)}${n}`}if(r===`bigint`||r===`symbol`)return e.toString();if(r===`function`)return`[Function]`;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack?.slice(0,this.MAX_ESTIMATION_STRING_LENGTH)};if(Buffer.isBuffer(e))return`[Buffer:${e.byteLength}]`;if(t>=this.MAX_ESTIMATION_DEPTH)return Array.isArray(e)?`[Array:${e.length}]`:`[Object]`;if(Array.isArray(e)){let r=e.slice(0,this.MAX_ESTIMATION_ARRAY_ITEMS).map(e=>this.normalizeForSizeEstimate(e,t+1,n));return e.length>this.MAX_ESTIMATION_ARRAY_ITEMS&&r.push(`[truncated:${e.length-this.MAX_ESTIMATION_ARRAY_ITEMS}]`),r}if(r===`object`){if(!this.isRecord(e))return`[Object]`;if(n.has(e))return`[Circular]`;n.add(e);let r=Object.entries(e),i=r.slice(0,this.MAX_ESTIMATION_OBJECT_KEYS),a={};for(let[e,r]of i)a[e]=this.normalizeForSizeEstimate(r,t+1,n);return r.length>this.MAX_ESTIMATION_OBJECT_KEYS&&(a.__truncatedKeys=r.length-this.MAX_ESTIMATION_OBJECT_KEYS),a}return String(e)}estimateTokens(e){return Math.ceil(e/this.BYTES_PER_TOKEN)}getUsagePercentage(){return Math.round(this.currentUsage/this.MAX_TOKENS*100)}checkWarnings(){let e=this.currentUsage/this.MAX_TOKENS;for(let t of this.WARNING_THRESHOLDS)e>=t&&!this.warnings.has(t)&&(this.emitWarning(t),this.warnings.add(t))}emitWarning(t){let n=Math.round(t*100),r=this.MAX_TOKENS-this.currentUsage;e.warn(`Token Budget Warning: ${n}% used! (${this.currentUsage}/${this.MAX_TOKENS}, ${r} tokens remaining)`),t>=.95?e.warn(`CRITICAL: Consider clearing caches or starting a new session.`):t>=.9?e.warn(`HIGH: Auto-cleanup will trigger soon. Consider using summary modes.`):t>=.8&&e.warn(`MODERATE: Monitor usage. Use get_token_budget_stats for details.`)}shouldAutoCleanup(){return this.currentUsage/this.MAX_TOKENS>=this.AUTO_CLEANUP_THRESHOLD}autoCleanup(){e.info(`Auto-cleanup triggered at 90% usage.`);let t=this.currentUsage;if(this.externalCleanupFn)try{this.externalCleanupFn(),e.info(`External cleanup callback invoked`)}catch(t){e.warn(`External cleanup callback failed:`,t)}let n=Date.now()-this.HISTORY_RETENTION,r=this.toolCallHistory.length;this.toolCallHistory=this.toolCallHistory.filter(e=>e.timestamp>n);let i=r-this.toolCallHistory.length;e.info(`Removed ${i} old tool call records`),this.recalculateUsage();let a=this.currentUsage,o=t-a,s=Math.round(o/this.MAX_TOKENS*100);e.info(`Cleanup complete. Freed ${o} tokens (${s}%). Usage: ${a}/${this.MAX_TOKENS} (${this.getUsagePercentage()}%)`);let c=a/this.MAX_TOKENS;this.warnings=new Set(Array.from(this.warnings).filter(e=>c>=e))}recalculateUsage(){this.currentUsage=this.toolCallHistory.reduce((e,t)=>e+t.estimatedTokens,0)}getStats(){let e=new Map;for(let t of this.toolCallHistory){let n=e.get(t.toolName)||0;e.set(t.toolName,n+t.estimatedTokens)}let t=Array.from(e.entries()).map(([e,t])=>({tool:e,tokens:t,percentage:Math.round(t/this.currentUsage*100)})).toSorted((e,t)=>t.tokens-e.tokens).slice(0,10),n=this.generateSuggestions(t),r=this.toolCallHistory.slice(-20);return{currentUsage:this.currentUsage,maxTokens:this.MAX_TOKENS,usagePercentage:this.getUsagePercentage(),toolCallCount:this.toolCallHistory.length,topTools:t,warnings:Array.from(this.warnings).map(e=>Math.round(e*100)),recentCalls:r,suggestions:n,sessionStartTime:this.sessionStartTime}}generateSuggestions(e){let t=[],n=this.currentUsage/this.MAX_TOKENS;n>=.95?t.push(` CRITICAL: Clear all caches immediately or start a new session`):n>=.9?t.push(`HIGH: Auto-cleanup triggered. Consider manual cleanup for better control`):n>=.8&&t.push(`MODERATE: Monitor usage closely. Use summary modes for large data`);for(let{tool:n,percentage:r}of e)r>30&&(n.includes(`collect_code`)?t.push(` ${n} uses ${r}% tokens. Try smartMode="summary" or "priority"`):n.includes(`get_script_source`)?t.push(` ${n} uses ${r}% tokens. Try preview=true first`):n.includes(`network_get_requests`)?t.push(` ${n} uses ${r}% tokens. Reduce limit or use filters`):n.includes(`page_evaluate`)&&t.push(` ${n} uses ${r}% tokens. Query specific properties instead of full objects`));return t.length===0&&t.push(` Token usage is healthy. Continue monitoring.`),t}manualCleanup(){e.info(`Manual cleanup requested.`),this.autoCleanup()}setTrackingEnabled(t){this.trackingEnabled!==t&&(this.trackingEnabled=t,e.warn(`Token budget tracking ${t?`enabled`:`disabled`}`))}isTrackingEnabled(){return this.trackingEnabled}reset(){e.info(`Resetting token budget...`),this.currentUsage=0,this.toolCallHistory=[],this.warnings.clear(),this.sessionStartTime=Date.now(),e.info(`Token budget reset complete`)}},h=class t{static instance;GLOBAL_MAX_SIZE=r;LOW_HIT_RATE_THRESHOLD=n;caches=new Map;constructor(){e.info(`UnifiedCacheManager initialized`)}static getInstance(){return this.instance||=new t,this.instance}registerCache(t){this.caches.set(t.name,t),e.info(`Registered cache: ${t.name}`)}unregisterCache(t){this.caches.delete(t),e.info(`Unregistered cache: ${t}`)}async getGlobalStats(){let t=0,n=0,r=0,i=0,a=[];for(let[o,s]of this.caches)try{let e=await s.getStats();t+=e.entries,n+=e.size,r+=e.hits||0,i+=e.misses||0,a.push({name:o,entries:e.entries,size:e.size,sizeMB:(e.size/1024/1024).toFixed(2),hitRate:e.hitRate,ttl:e.ttl})}catch(t){e.error(`Failed to get stats for cache ${o}:`,t)}let o=r+i>0?r/(r+i):0,s=this.generateRecommendations(n,o,a);return{totalEntries:t,totalSize:n,totalSizeMB:(n/1024/1024).toFixed(2),hitRate:o,caches:a,recommendations:s}}async smartCleanup(t){let n=t||this.GLOBAL_MAX_SIZE*.7,r=await this.getGlobalStats(),i=r.totalSize;if(i<=n)return e.info(`No cleanup needed`),{before:i,after:i,freed:0,freedPercentage:0};e.info(`Smart cleanup: current ${r.totalSizeMB}MB, target ${(n/1024/1024).toFixed(2)}MB`),await this.cleanupExpired();let a=await this.getGlobalStats();if(a.totalSize<=n||(await this.cleanupLowHitRate(),a=await this.getGlobalStats(),a.totalSize<=n))return this.calculateCleanupResult(i,a.totalSize);await this.cleanupLargeItems();let o=await this.getGlobalStats();return this.calculateCleanupResult(i,o.totalSize)}async cleanupExpired(){e.info(`Cleaning up expired data...`);for(let[t,n]of this.caches)if(n.cleanup)try{await n.cleanup(),e.debug(`Cleaned up expired data in ${t}`)}catch(n){e.error(`Failed to cleanup ${t}:`,n)}}async cleanupLowHitRate(){e.info(`Cleaning up low hit rate caches...`);let t=await this.getGlobalStats(),n=t.hitRate;for(let r of t.caches)if(r.hitRate!==void 0&&r.hitRate<n*this.LOW_HIT_RATE_THRESHOLD){let t=this.caches.get(r.name);if(t?.clear)try{await t.clear(),e.info(`Cleared low hit rate cache: ${r.name} (${(r.hitRate*100).toFixed(1)}%)`)}catch(t){e.error(`Failed to clear ${r.name}:`,t)}}}async cleanupLargeItems(){e.info(`Cleaning up large caches...`);let t=(await this.getGlobalStats()).caches.toSorted((e,t)=>t.size-e.size);for(let n of t.slice(0,2)){let t=this.caches.get(n.name);if(t?.clear)try{await t.clear(),e.info(`Cleared large cache: ${n.name} (${n.sizeMB}MB)`)}catch(t){e.error(`Failed to clear ${n.name}:`,t)}}}calculateCleanupResult(t,n){let r=t-n,i=Math.round(r/this.GLOBAL_MAX_SIZE*100);return e.info(`Cleanup complete! Freed ${(r/1024/1024).toFixed(2)}MB (${i}%). Usage: ${(n/1024/1024).toFixed(2)}MB/${(this.GLOBAL_MAX_SIZE/1024/1024).toFixed(0)}MB`),{before:t,after:n,freed:r,freedPercentage:i}}async clearAll(){e.info(`Clearing all caches...`);for(let[t,n]of this.caches)if(n.clear)try{await n.clear(),e.info(`Cleared cache: ${t}`)}catch(n){e.error(`Failed to clear ${t}:`,n)}e.success(`All caches cleared`)}async preheat(t){e.info(`Preheating cache for ${t.length} URLs...`),e.info(`Cache preheat completed`)}generateRecommendations(e,t,n){let r=[],i=e/this.GLOBAL_MAX_SIZE;i>=.9?r.push(` CRITICAL: Cache size at 90%. Run smart_cache_cleanup immediately!`):i>=.7?r.push(`WARNING: Cache size at 70%. Consider cleanup soon.`):i>=.5&&r.push(`INFO: Cache size at 50%. Monitor usage.`),t<.3?r.push(` Low cache hit rate (<30%). Consider adjusting TTL or cache strategy.`):t>.7&&r.push(` Good cache hit rate (>70%). Cache is working well.`);for(let t of n){let n=t.size/e;n>.5&&r.push(` ${t.name} uses ${Math.round(n*100)}% of total cache. Consider cleanup.`),t.hitRate!==void 0&&t.hitRate<.2&&r.push(` ${t.name} has low hit rate (${(t.hitRate*100).toFixed(1)}%). Consider disabling or adjusting.`)}return r.length===0&&r.push(` Cache health is good. No action needed.`),r}};function g(e=process.env){let t=Math.max(0,parseInt(e.MCP_ARTIFACT_RETENTION_DAYS??`0`,10)||0),n=Math.max(0,parseInt(e.MCP_ARTIFACT_MAX_TOTAL_MB??`0`,10)||0),r=Math.max(0,parseInt(e.MCP_ARTIFACT_CLEANUP_INTERVAL_MINUTES??`0`,10)||0),i=[`1`,`true`].includes((e.MCP_ARTIFACT_CLEANUP_ON_START??``).toLowerCase());return{enabled:t>0||n>0,retentionDays:t,maxTotalBytes:n*1024*1024,cleanupOnStart:i,cleanupIntervalMinutes:r}}async function _(e){let t=g(),n={...t,retentionDays:e?.retentionDays??t.retentionDays,maxTotalBytes:e?.maxTotalBytes??t.maxTotalBytes},r=e?.now??Date.now(),a=e?.dryRun??!1,o=e?.directories??y(),s=n.retentionDays>0?r-n.retentionDays*864e5:0,c=0,l=0,u=0,d=0,p=0,m=[],h=[],_=i(),v=[];function S(e){v.push(f(e,{force:!0}).then(()=>void 0).catch(()=>void 0))}for(let e of o)await b(e,_,s,a,e=>{c++,s>0&&e.mtimeMs<s?(l++,u+=e.size,d+=e.size,h.length<20&&h.push(e.relativePath),a||S(e.path)):m.push(e)});if(n.maxTotalBytes>0){let e=m.reduce((e,t)=>e+t.size,0);if(e>n.maxTotalBytes){m.sort((e,t)=>e.mtimeMs-t.mtimeMs);let t=0;for(;t<m.length&&e>n.maxTotalBytes;){let n=m[t];e-=n.size,l++,u+=n.size,p+=n.size,h.length<20&&h.push(n.relativePath),a||S(n.path),t++}m.splice(0,t)}}return a||(await Promise.all(v),await Promise.all(o.map(e=>x(e)))),{success:!0,scannedFiles:c,removedFiles:l,removedBytes:u,removedByAge:d,removedBySize:p,remainingFiles:m.length,remainingBytes:m.reduce((e,t)=>e+t.size,0),dryRun:a,directories:o,removedSample:h,config:n}}function v(){let t=g();if(!t.enabled||t.cleanupIntervalMinutes<=0)return null;let n=setInterval(()=>{_().then(t=>{t.removedFiles>0&&e.info(`[artifacts] retention cleanup removed ${t.removedFiles} files (${t.removedBytes} bytes)`)}).catch(t=>{e.warn(`[artifacts] retention cleanup failed`,t)})},t.cleanupIntervalMinutes*60*1e3);return n.unref(),()=>clearInterval(n)}function y(){let e=i(),t=u(process.cwd(),`debugger-sessions`),n=u(e,`debugger-sessions`),r=new Set([c(),a().paths.screenshotDir,o(),t,n]);for(let e of[`wasm`,`traces`,`profiles`,`dumps`,`reports`,`har`,`sessions`,`tmp`])r.add(s(e));return[...r]}async function b(e,t,n,r,i){let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=l(e,o.name);if(o.isDirectory())await b(a,t,n,r,i);else if(o.isFile()){let e;try{e=await p(a)}catch{continue}i({path:a,relativePath:S(t,a),size:e.size,mtimeMs:e.mtimeMs})}}}async function x(e){let t;try{t=await d(e,{withFileTypes:!0})}catch{return}await Promise.all(t.filter(e=>e.isDirectory()).map(t=>x(l(e,t.name))));try{(await d(e)).length===0&&await f(e,{recursive:!0,force:!0})}catch{}}function S(e,t){return t.startsWith(e)?t.slice(e.length).replace(/^[\\/]/,``).replace(/\\/g,`/`):t.replace(/\\/g,`/`)}export{m as a,h as i,g as n,v as r,_ as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-C_pMuVsO.mjs";import{i as t}from"./outputPaths-
|
|
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
|
+
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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-C_pMuVsO.mjs";import{t}from"./logger-sBC6IdRT.mjs";import{
|
|
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
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
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
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(`
|
|
@@ -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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./chunk-C_pMuVsO.mjs";import{a as t}from"./outputPaths-
|
|
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
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};
|