@jshookmcp/jshook 0.2.9 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -50
- package/README.zh.md +25 -48
- package/dist/AntiCheatDetector-CGVGNfy5.mjs +1 -0
- package/dist/CacheAdapters-CdAxBmVW.mjs +1 -0
- package/dist/CodeInjector-BlgyqTOk.mjs +1 -0
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +490 -0
- package/dist/DOMInspector-BYY_EJ0C.mjs +95 -0
- package/dist/DarwinAPI-DC4HGGLl.mjs +1 -0
- package/dist/DetailedDataManager-BniBJlVv.mjs +1 -0
- package/dist/EventBus-DgciURGg.mjs +1 -0
- package/dist/EvidenceGraphBridge-BIfgB7HP.mjs +1 -0
- package/dist/ExtensionManager-erMpqcLk.mjs +1 -0
- package/dist/FingerprintManager-N7BZqjxP.mjs +1 -0
- package/dist/HardwareBreakpoint-OcJqNFVc.mjs +1 -0
- package/dist/HeapAnalyzer-CqAxZzeS.mjs +1 -0
- package/dist/{HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs → HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs} +66 -174
- package/dist/InstrumentationSession-DxXs0sCp.mjs +1 -0
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +1 -0
- package/dist/MemoryController-BaqstM5w.mjs +2 -0
- package/dist/MemoryScanSession-CaxAjZJf.mjs +1 -0
- package/dist/MemoryScanner-BLYnMJy6.mjs +1 -0
- package/dist/NativeMemoryManager.impl-CI554XbY.mjs +1 -0
- package/dist/NativeMemoryManager.utils-DM4NC3FE.mjs +1 -0
- package/dist/PEAnalyzer-DJyaJTQJ.mjs +1 -0
- package/dist/PageController-D9jVkH0i.mjs +1 -0
- package/dist/PointerChainEngine-5nF9eNlu.mjs +1 -0
- package/dist/PrerequisiteError-Bl3dK8XA.mjs +1 -0
- package/dist/ProcessRegistry-Hf12LlR9.mjs +1 -0
- package/dist/ResponseBuilder-B2lu4KEl.mjs +1 -0
- package/dist/ReverseEvidenceGraph-B931HeoW.mjs +2 -0
- package/dist/ScriptManager-fgqiALgj.mjs +7 -0
- package/dist/Speedhack-l6s8L2Qw.mjs +1 -0
- package/dist/StealthVerifier-Dhbj4B4P.mjs +1 -0
- package/dist/StructureAnalyzer-A-WamfYE.mjs +2 -0
- package/dist/ToolCatalog-D_IKl1Hu.mjs +1 -0
- package/dist/ToolError-DWU_z7gp.mjs +1 -0
- package/dist/ToolProbe-xsfALmN3.mjs +1 -0
- package/dist/ToolRegistry-B0Zs-phN.mjs +1 -0
- package/dist/ToolRouter.policy-CFHoN_Lw.mjs +4 -0
- package/dist/TraceRecorder-Dd8jLXpi.mjs +272 -0
- package/dist/VersionDetector-DMoUWyNm.mjs +9 -0
- package/dist/Win32API-Bhi5xFBe.mjs +1 -0
- package/dist/Win32Debug-CQteFL4F.mjs +1 -0
- package/dist/WorkflowEngine-CxEp2WXH.mjs +1 -0
- package/dist/analysis-BuR-NgX8.mjs +5 -0
- package/dist/{antidebug-CqDTB_uk.mjs → antidebug-BOTZH6-0.mjs} +8 -259
- package/dist/artifactRetention-NBdncOEW.mjs +1 -0
- package/dist/artifacts-B5xQuEa_.mjs +1 -0
- package/dist/authorization-schema-B40obG1A.mjs +1 -0
- package/dist/betterSqlite3-CGaxz4AX.mjs +1 -0
- package/dist/binary-instrument-Cf9qqLlM.mjs +7 -0
- package/dist/bind-helpers-BlAOQrFQ.mjs +1 -0
- package/dist/boringssl-inspector-BST5vtKx.mjs +2 -0
- package/dist/browser-C4Le3xqA.mjs +11 -0
- package/dist/capabilities-DbYCv-HF.mjs +1 -0
- package/dist/chunk-C_pMuVsO.mjs +1 -0
- package/dist/collector-CKO8RPK8.mjs +1 -0
- package/dist/concurrency-CcK46d0h.mjs +1 -0
- package/dist/constants-Cp6hBrrx.mjs +1 -0
- package/dist/coordination-BbijHEHH.mjs +1 -0
- package/dist/debugger-CRJq_krh.mjs +1 -0
- package/dist/definitions-BGobEDQa.mjs +1 -0
- package/dist/definitions-BGwNSkVm.mjs +1 -0
- package/dist/definitions-BbxOUiP-.mjs +1 -0
- package/dist/definitions-CCP9gphV.mjs +1 -0
- package/dist/definitions-CIO9O-Sw.mjs +1 -0
- package/dist/definitions-CYFbewnd.mjs +1 -0
- package/dist/definitions-CdWEuIkI.mjs +1 -0
- package/dist/definitions-CoQFbggH.mjs +1 -0
- package/dist/definitions-CuJRsJ6N.mjs +1 -0
- package/dist/definitions-DI9YXsJk.mjs +1 -0
- package/dist/definitions-DJklW2sS.mjs +1 -0
- package/dist/definitions-DZ8uKusP.mjs +1 -0
- package/dist/definitions-Dds_zrWx.mjs +1 -0
- package/dist/definitions-Dgrg7f3D.mjs +1 -0
- package/dist/definitions-DtE0XLrT.mjs +1 -0
- package/dist/definitions-LaYTuwQd.mjs +26 -0
- package/dist/definitions-NoVp_9Pm.mjs +1 -0
- package/dist/definitions-OvGsfxdt.mjs +1 -0
- package/dist/definitions-jXPaVy4P.mjs +1 -0
- package/dist/encoding-DGcr6Aj_.mjs +2 -0
- package/dist/ensure-browser-core-Buls24LQ.mjs +1 -0
- package/dist/evidence-graph-bridge-B0yhGPcs.mjs +1 -0
- package/dist/factory-Cx_1LorX.mjs +1 -0
- package/dist/flat-target-session-CO5g78k3.mjs +1 -0
- package/dist/formatAddress-C7j2fDlM.mjs +1 -0
- package/dist/graphql-HLf3MS8H.mjs +62 -0
- package/dist/handlers-BLMa4X7l.mjs +54 -0
- package/dist/handlers-BP12ZsWc.mjs +4 -0
- package/dist/handlers-BZoPla6E.mjs +1 -0
- package/dist/handlers-BggKiVx9.mjs +2 -0
- package/dist/handlers-D3iev8g1.mjs +1 -0
- package/dist/handlers-D49r1-1P.mjs +1 -0
- package/dist/handlers-DCE45Ww8.mjs +2 -0
- package/dist/handlers-DW5AbYs5.mjs +5 -0
- package/dist/handlers-De5u62Ga2.mjs +1 -0
- package/dist/handlers-DmQzIc44.mjs +31 -0
- package/dist/handlers-DnJRGp7t.mjs +302 -0
- package/dist/handlers-Dv_runVv.mjs +2 -0
- package/dist/handlers-S9Ws0IGy.mjs +2 -0
- package/dist/{handlers-Bl8zkwz1.mjs → handlers-pVNpaw4A.mjs} +144 -841
- package/dist/handlers.impl-CD2_kOcC.mjs +1 -0
- package/dist/hooks-DDKppogd.mjs +600 -0
- package/dist/index.mjs +12 -5225
- package/dist/logger-sBC6IdRT.mjs +1 -0
- package/dist/maintenance-CutEO84j.mjs +1 -0
- package/dist/manifest-BFGxlDRh.mjs +123 -0
- package/dist/manifest-BPuE6oH2.mjs +1 -0
- package/dist/manifest-BXry5N09.mjs +1 -0
- package/dist/manifest-BeP_zJGb2.mjs +1 -0
- package/dist/manifest-C0g67k6U.mjs +1 -0
- package/dist/manifest-C1nZkTkO.mjs +1 -0
- package/dist/manifest-C7qV1z7F.mjs +1 -0
- package/dist/manifest-CDeUZGUZ.mjs +1 -0
- package/dist/manifest-CDiCtaQT.mjs +1 -0
- package/dist/manifest-CFn0359q2.mjs +1 -0
- package/dist/manifest-CGq4NpqH2.mjs +1 -0
- package/dist/manifest-CJMGt7Qy.mjs +1 -0
- package/dist/manifest-CRIJq4Hs.mjs +1 -0
- package/dist/manifest-C_hEIjSx.mjs +1 -0
- package/dist/manifest-CeQmtQOY.mjs +1 -0
- package/dist/manifest-Cq0j7GZt.mjs +1 -0
- package/dist/manifest-CtPmHAdn.mjs +1 -0
- package/dist/manifest-Cx2IVMUY.mjs +1 -0
- package/dist/manifest-D16xPXro.mjs +1 -0
- package/dist/manifest-D44TaRJU.mjs +1 -0
- package/dist/manifest-D610kxZr.mjs +2 -0
- package/dist/manifest-DC-SMF6b.mjs +1 -0
- package/dist/manifest-DD3rtxvV.mjs +1 -0
- package/dist/manifest-DKUorv5M.mjs +1 -0
- package/dist/manifest-DMJlcsTR.mjs +1 -0
- package/dist/manifest-DWUUWBz0.mjs +1 -0
- package/dist/manifest-De-6Wf2R.mjs +1 -0
- package/dist/manifest-Dgh0uDW-.mjs +1 -0
- package/dist/manifest-Dm0o3i2U.mjs +1 -0
- package/dist/manifest-DsVh7Y4U.mjs +1 -0
- package/dist/manifest-DtEFSRaq.mjs +1 -0
- package/dist/manifest-H-EpAyZQ.mjs +1 -0
- package/dist/manifest-ais9Afrw.mjs +1 -0
- package/dist/manifest-tmb54wmA.mjs +1 -0
- package/dist/manifest-yu2xiQqe.mjs +1 -0
- package/dist/manifest-zrbrpKCC.mjs +1 -0
- package/dist/matchesWildcardPattern-BGqLSmEs.mjs +1 -0
- package/dist/modules-p-PUNv9r.mjs +332 -0
- package/dist/mojo-ipc-VGlv3Qyp.mjs +9 -0
- package/dist/network-BjZ1Y-GB.mjs +7 -0
- package/dist/outputPaths-BonGThuc.mjs +2 -0
- package/dist/parse-args-Cuk7-xUt.mjs +1 -0
- package/dist/platform-C446Lf97.mjs +93 -0
- package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +1 -0
- package/dist/process-C9f2A5zk.mjs +962 -0
- package/dist/proxy-CvRepxgV.mjs +1 -0
- package/dist/registry-DUHIPE-v.mjs +1 -0
- package/dist/response-C7rKQst4.mjs +1 -0
- package/dist/search-defaults-D2bY-rzH.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -293
- package/dist/shared-state-board-Cyg-xh_k.mjs +1 -0
- package/dist/sourcemap-D6Q1UuAp.mjs +1 -0
- package/dist/ssrf-policy-T96MR3r6.mjs +1 -0
- package/dist/streaming-CTX58tbb.mjs +1 -0
- package/dist/tool-builder-CI9914Tf.mjs +1 -0
- package/dist/transform-Cv9P2vVD.mjs +103 -0
- package/dist/types-CuyefmGT.mjs +1 -0
- package/dist/types-DtThH00r.mjs +1 -0
- package/dist/wasm-DaJa8J0V.mjs +174 -0
- package/dist/webcrack-CsLLJIs9.mjs +46 -0
- package/dist/workflow-CYIXtrWD.mjs +101 -0
- package/package.json +12 -7
- package/dist/AntiCheatDetector-BNk-EoBt.mjs +0 -244
- package/dist/CacheAdapters-CDe5WPSV.mjs +0 -80
- package/dist/CodeInjector-Cq8q01kp.mjs +0 -150
- package/dist/ConsoleMonitor-CPVQW1Y-.mjs +0 -2201
- package/dist/DarwinAPI-BNPxu0RH.mjs +0 -363
- package/dist/DetailedDataManager-BQQcxh64.mjs +0 -217
- package/dist/EventBus-DgPmwpeu.mjs +0 -141
- package/dist/EvidenceGraphBridge-SFesNera.mjs +0 -153
- package/dist/ExtensionManager-CWYgw0YW.mjs +0 -714
- package/dist/FingerprintManager-gzWtkKuf.mjs +0 -96
- package/dist/HardwareBreakpoint-B9gZCdFP.mjs +0 -239
- package/dist/HeapAnalyzer-BLDH0dCv.mjs +0 -284
- package/dist/InstrumentationSession-CvPC7Jwy.mjs +0 -244
- package/dist/MemoryController-CbVdCIJF.mjs +0 -167
- package/dist/MemoryScanSession-BsDZbLYm.mjs +0 -278
- package/dist/MemoryScanner-Bcpml6II.mjs +0 -425
- package/dist/NativeMemoryManager.impl-dZtA1ZGn.mjs +0 -482
- package/dist/NativeMemoryManager.utils-B-FjA2mJ.mjs +0 -165
- package/dist/PEAnalyzer-D1lzJ_VG.mjs +0 -385
- package/dist/PageController-Bqm2kZ_X.mjs +0 -417
- package/dist/PointerChainEngine-BOhyVsjx.mjs +0 -322
- package/dist/PrerequisiteError-Dl33Svkz.mjs +0 -20
- package/dist/ResponseBuilder-D3iFYx2N.mjs +0 -143
- package/dist/ReverseEvidenceGraph-Dlsk94LC.mjs +0 -269
- package/dist/ScriptManager-aHHq0X7U.mjs +0 -3000
- package/dist/Speedhack-CqdIFlQl.mjs +0 -156
- package/dist/StealthVerifier-Bo4T3bz8.mjs +0 -135
- package/dist/StructureAnalyzer-DhFaPvRO.mjs +0 -426
- package/dist/ToolCatalog-C0JGZoOm.mjs +0 -582
- package/dist/ToolError-jh9whhMd.mjs +0 -15
- package/dist/ToolProbe-oC7aPrkv.mjs +0 -45
- package/dist/ToolRegistry-BjaF4oNz.mjs +0 -131
- package/dist/ToolRouter.policy-BWV67ZK-.mjs +0 -304
- package/dist/TraceRecorder-DgxyVbdQ.mjs +0 -519
- package/dist/VersionDetector-CwVLVdDM.mjs +0 -104
- package/dist/Win32API-CePkipZY.mjs +0 -340
- package/dist/Win32Debug-BvKs-gxc.mjs +0 -274
- package/dist/WorkflowEngine-CuvkZtWu.mjs +0 -598
- package/dist/analysis-CL9uACt9.mjs +0 -463
- package/dist/artifactRetention-CFEprwPw.mjs +0 -591
- package/dist/artifacts-Bk2-_uPq.mjs +0 -59
- package/dist/betterSqlite3-0pqusHHH.mjs +0 -74
- package/dist/binary-instrument-CXfpx6fT.mjs +0 -979
- package/dist/bind-helpers-xFfRF-qm.mjs +0 -22
- package/dist/boringssl-inspector-BH2D3VKc.mjs +0 -180
- package/dist/browser-BpOr5PEx.mjs +0 -4082
- package/dist/chunk-CjcI7cDX.mjs +0 -15
- package/dist/concurrency-Bt0yv1kJ.mjs +0 -41
- package/dist/constants-B0OANIBL.mjs +0 -519
- package/dist/coordination-qUbyF8KU.mjs +0 -259
- package/dist/debugger-gnKxRSN0.mjs +0 -1271
- package/dist/definitions-6M-eejaT.mjs +0 -53
- package/dist/definitions-B18eyf0B.mjs +0 -18
- package/dist/definitions-B3QdlrHv.mjs +0 -34
- package/dist/definitions-B4rAvHNZ.mjs +0 -63
- package/dist/definitions-BB_4jnmy.mjs +0 -37
- package/dist/definitions-BMfYXoNC.mjs +0 -43
- package/dist/definitions-Beid2EB3.mjs +0 -27
- package/dist/definitions-C1UvM5Iy.mjs +0 -126
- package/dist/definitions-CXEI7QC72.mjs +0 -216
- package/dist/definitions-C_4r7Fo-2.mjs +0 -14
- package/dist/definitions-CkFDALoa.mjs +0 -26
- package/dist/definitions-Cke7zEb8.mjs +0 -94
- package/dist/definitions-ClJLzsJQ.mjs +0 -25
- package/dist/definitions-Cq-zroAU.mjs +0 -28
- package/dist/definitions-Cy3Sl6gV.mjs +0 -34
- package/dist/definitions-D3VsGcvz.mjs +0 -47
- package/dist/definitions-DVGfrn7y.mjs +0 -96
- package/dist/definitions-LKpC3-nL.mjs +0 -9
- package/dist/definitions-bAhHQJq9.mjs +0 -359
- package/dist/encoding-Bvz5jLRv.mjs +0 -1065
- package/dist/evidence-graph-bridge-C_fv9PuC.mjs +0 -135
- package/dist/factory-DxlGh9Xf.mjs +0 -575
- package/dist/formatAddress-DVkj9kpI.mjs +0 -17
- package/dist/graphql-DYWzJ29s.mjs +0 -1026
- package/dist/handlers-9sAbfIg-.mjs +0 -2552
- package/dist/handlers-C67ktuRN.mjs +0 -710
- package/dist/handlers-C87g8oCe.mjs +0 -276
- package/dist/handlers-CTsDAO6p.mjs +0 -681
- package/dist/handlers-Cgyg6c0U.mjs +0 -645
- package/dist/handlers-D6j6yka7.mjs +0 -2124
- package/dist/handlers-DdFzXLvF.mjs +0 -446
- package/dist/handlers-DeLOCd5m.mjs +0 -799
- package/dist/handlers-DlCJN4Td.mjs +0 -757
- package/dist/handlers-DxGIq15_2.mjs +0 -917
- package/dist/handlers-U6L4xhuF.mjs +0 -585
- package/dist/handlers-tB9Mp9ZK.mjs +0 -84
- package/dist/handlers-tiy7EIBp.mjs +0 -572
- package/dist/handlers.impl-DS0d9fUw.mjs +0 -761
- package/dist/hooks-CzCWByww.mjs +0 -898
- package/dist/logger-Dh_xb7_2.mjs +0 -93
- package/dist/maintenance-P7ePRXQC.mjs +0 -830
- package/dist/manifest-2ToTpjv8.mjs +0 -106
- package/dist/manifest-3g71z6Bg.mjs +0 -79
- package/dist/manifest-82baTv4U.mjs +0 -45
- package/dist/manifest-B3QVVeBS.mjs +0 -82
- package/dist/manifest-BB2J8IMJ.mjs +0 -149
- package/dist/manifest-BKbgbSiY.mjs +0 -60
- package/dist/manifest-Bcf-TJzH.mjs +0 -848
- package/dist/manifest-BmtZzQiQ2.mjs +0 -45
- package/dist/manifest-Bnd7kqEY.mjs +0 -55
- package/dist/manifest-BqQX6OQC2.mjs +0 -65
- package/dist/manifest-BqrQ4Tpj.mjs +0 -81
- package/dist/manifest-Br4RPFt5.mjs +0 -370
- package/dist/manifest-C5qDjysN.mjs +0 -107
- package/dist/manifest-C9RT5nk32.mjs +0 -34
- package/dist/manifest-CAhOuvSl.mjs +0 -204
- package/dist/manifest-CBYWCUBJ.mjs +0 -51
- package/dist/manifest-CFADCRa1.mjs +0 -37
- package/dist/manifest-CQVhavRF.mjs +0 -114
- package/dist/manifest-CT7zZBV1.mjs +0 -48
- package/dist/manifest-CV12bcrF.mjs +0 -121
- package/dist/manifest-CXsRWjjI.mjs +0 -224
- package/dist/manifest-CZLUCfG02.mjs +0 -95
- package/dist/manifest-D6phHKFd.mjs +0 -131
- package/dist/manifest-DCyjf4n2.mjs +0 -294
- package/dist/manifest-DHsnKgP6.mjs +0 -60
- package/dist/manifest-Df_dliIe.mjs +0 -55
- package/dist/manifest-Dh8WBmEW.mjs +0 -129
- package/dist/manifest-DhKRAT8_.mjs +0 -92
- package/dist/manifest-DlpTj4ic2.mjs +0 -193
- package/dist/manifest-DrbmZcFl2.mjs +0 -253
- package/dist/manifest-DuwHjUa5.mjs +0 -70
- package/dist/manifest-DzwvxPJX.mjs +0 -38
- package/dist/manifest-NXctwWQq.mjs +0 -68
- package/dist/manifest-Sc_0JQ13.mjs +0 -418
- package/dist/manifest-gZ4s_UtG.mjs +0 -96
- package/dist/manifest-qSleDqdO.mjs +0 -1023
- package/dist/modules-C184v-S9.mjs +0 -11365
- package/dist/mojo-ipc-B_H61Afw.mjs +0 -525
- package/dist/network-671Cw6hV.mjs +0 -3346
- package/dist/outputPaths-B1uGmrWZ.mjs +0 -1145
- package/dist/parse-args-BlRjqlkL.mjs +0 -39
- package/dist/platform-WmNn8Sxb.mjs +0 -2070
- package/dist/process-QcbIy5Zq.mjs +0 -1401
- package/dist/proxy-DqNs0bAd.mjs +0 -170
- package/dist/registry-D-6e18lB.mjs +0 -34
- package/dist/response-BQVP-xUn.mjs +0 -28
- package/dist/shared-state-board-DV-dpHFJ.mjs +0 -586
- package/dist/sourcemap-Dq8ez8vS.mjs +0 -650
- package/dist/ssrf-policy-ZaUfvhq7.mjs +0 -166
- package/dist/streaming-BUQ0VJsg.mjs +0 -725
- package/dist/tool-builder-DCbIC5Eo.mjs +0 -186
- package/dist/transform-CiYJfNX0.mjs +0 -1007
- package/dist/types-Bx92KJfT.mjs +0 -4
- package/dist/types-CPhOReNX.mjs +0 -37
- package/dist/wasm-DQTnHDs4.mjs +0 -531
- package/dist/workflow-f3xJOcjx.mjs +0 -725
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./response-C7rKQst4.mjs";import{a as t,t as n}from"./parse-args-Cuk7-xUt.mjs";function r(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function i(e,t){let n=r(e),i=r(t);return n===i&&n.length>0?1:n.length===0||i.length===0?0:n.includes(i)||i.includes(n)?.8:0}function a(e,t){let n=0,r;for(let a of t){let t=i(e,a.name);t>n&&(n=t,r={objectId:a.objectId,name:a.name,score:t});for(let t of a.stringProps){let o=i(e,t);o>n&&(n=o,r={objectId:a.objectId,name:a.name,score:o})}}if(r&&n>=.5)return r}function o(e,t){let n=[],r=[],i=[],o=new Set,s=[];for(let e of t.sceneTree.layers)s.push({id:e.id,label:e.label,heapObjectId:e.heapObjectId});for(let e of t.sceneTree.drawCommands)s.push({id:e.id,label:e.label});let c=s.length;for(let c of s){let s=e.addCanvasNode({nodeId:c.id,label:c.label});if(n.push(s.id),c.heapObjectId){let i=t.jsObjects.find(e=>e.objectId===c.heapObjectId);if(i){let t=e.addV8Object({address:c.heapObjectId,name:i.name});n.push(t.id),e.getGraph().addEdge(t.id,s.id,`canvas-rendered-by`,{domain:`cross-domain`,matchScore:1}),r.push({skiaNodeId:c.id,matchedObjectId:i.objectId,matchedObjectName:i.name,matchScore:1}),o.add(c.id);continue}}let l=a(c.label,t.jsObjects);if(l){let t=e.addV8Object({address:l.objectId,name:l.name});n.push(t.id),e.getGraph().addEdge(t.id,s.id,`canvas-rendered-by`,{domain:`cross-domain`,matchScore:l.score}),r.push({skiaNodeId:c.id,matchedObjectId:l.objectId,matchedObjectName:l.name,matchScore:l.score}),o.add(c.id)}else i.push(c.id)}return{skiaNodes:c,correlations:r,unmatchedSkiaNodes:i,confidence:c===0?0:r.length/c,graphNodeIds:n}}const s=[{mojoPattern:/URLLoader/i,cdpPattern:/Network\./i},{mojoPattern:/WebSocket/i,cdpPattern:/Network\.webSocket/i},{mojoPattern:/Fetch/i,cdpPattern:/Fetch\./i}];function c(e,t,n,r){let i=[],a=[],o=new Set,c=new Map;for(let t of r){let{node:n}=e.addNetworkRequest({requestId:t.requestId,url:t.url});c.set(t.requestId,n.id),i.push(n.id)}if(t.length===0)return{mojoMessages:0,matchedPairs:[],unmatchedMojo:[],confidence:0,graphNodeIds:i};let l=new Map;for(let n of t){let t=e.addMojoMessage({interface:n.interface,method:n.method,timestamp:n.timestamp});l.set(n.messageId,t.id),i.push(t.id)}for(let e of t)if(!o.has(e.messageId))for(let t of s){if(!t.mojoPattern.test(e.interface))continue;let r=n.find(n=>t.cdpPattern.test(n.eventType)&&!o.has(e.messageId));if(r){a.push({mojoMessageId:e.messageId,matchType:`interface`,cdpEventType:r.eventType}),o.add(e.messageId);break}}for(let n of t)if(!o.has(n.messageId)&&/URLLoader/i.test(n.interface)){let t=r.find(e=>Math.abs(e.timestamp-n.timestamp)<=50);if(t){let r=c.get(t.requestId),i=l.get(n.messageId);r&&i&&e.getGraph().addEdge(r,i,`mojo-routed-to`,{domain:`cross-domain`,relation:`network-request-correlates-to-mojo`,matchType:`urlloader`,timestampDelta:Math.abs(t.timestamp-n.timestamp)}),a.push({mojoMessageId:n.messageId,matchType:`urlloader`,networkRequestId:t.requestId,timestampDelta:Math.abs(t.timestamp-n.timestamp)}),o.add(n.messageId)}}for(let e of t){if(o.has(e.messageId))continue;let t=1/0,r;for(let i of n){let n=Math.abs(i.timestamp-e.timestamp);n<=50&&n<t&&(t=n,r=i)}r&&(a.push({mojoMessageId:e.messageId,matchType:`timestamp`,cdpEventType:r.eventType,timestampDelta:t}),o.add(e.messageId))}let u=t.filter(e=>!o.has(e.messageId)).map(e=>e.messageId),d=t.length===0?0:o.size/t.length;return{mojoMessages:t.length,matchedPairs:a,unmatchedMojo:u,confidence:d,graphNodeIds:i}}const l={NtReadFile:/read|fs[_.]read/i,NtWriteFile:/write|fs[_.]write/i,NtOpenFile:/open|fs[_.]open/i,NtCreateFile:/create|fs[_.]create/i,NtClose:/close|fs[_.]close/i,NtDeviceIoControlFile:/ioctl|device/i,NtQueryInformationFile:/stat|info|query/i,NtSetInformationFile:/set|chmod|chown/i};function u(e,t){let n=l[e];return n&&n.test(t)?`high`:/file|fs|read|write|open|close/i.test(t)?`medium`:`low`}function d(e,t,n){let r=[],i=[],a=[];if(t.length===0)return{syscalls:0,correlations:[],unmatchedSyscalls:[],correlationConfidence:0,graphNodeIds:[]};for(let o of t){let t=e.addSyscallEvent({pid:o.pid,tid:o.tid,syscallName:o.syscallName,timestamp:o.timestamp});r.push(t.id);let s=n.find(e=>e.threadId===o.tid&&e.timestamp===o.timestamp);if(s&&s.frames.length>0){let n=s.frames[0];if(n){let a=n.functionName,s=u(o.syscallName,a),c=e.addNode(`function`,a,{domain:`v8-inspector`,functionName:a,threadId:o.tid});r.push(c.id),e.getGraph().addEdge(c.id,t.id,`syscall-emitted-by`,{domain:`cross-domain`,confidence:s}),i.push({syscallName:o.syscallName,topJsFunction:a,threadId:o.tid,timestamp:o.timestamp,confidence:s})}else a.push({syscallName:o.syscallName,tid:o.tid})}else a.push({syscallName:o.syscallName,tid:o.tid})}let o=t.length===0?0:i.length/t.length;return{syscalls:t.length,correlations:i,unmatchedSyscalls:a,correlationConfidence:o,graphNodeIds:r}}const f=[/^native_/i,/^JS_/i,/^Java_/i];function p(e){return e.calledFrom&&e.calledFrom.length>0?!0:f.some(t=>t.test(e.name))}function m(e,t){let n=[];n.push(`// Binary-to-JS Hook Script`),n.push(`// Module: ${t}`),n.push(`// Generated at: ${new Date().toISOString()}`),n.push(``);for(let r of e){let e=r.moduleName||t;r.address?(n.push(`// Hook: ${r.name} at ${r.address} in ${e}`),n.push(`Interceptor.attach(Module.findBaseAddress('${e}').add(${r.address}), {`)):(n.push(`// Hook: ${r.name} in ${e}`),n.push(`Interceptor.attach(Module.findExportByName('${e}', '${r.name}'), {`)),n.push(` onEnter(args) {`),n.push(` console.log('[${r.name}] called with args:', args[0], args[1]);`),n.push(` },`),n.push(` onLeave(retval) {`),n.push(` console.log('[${r.name}] returned:', retval);`),n.push(` }`),n.push(`});`),n.push(``)}return n.push(`console.log('Binary-to-JS hook script loaded for ${t}');`),n.join(`
|
|
2
|
+
`)}function h(e,t,n){let r=[],i=[],a;if(n&&n.length>0){let e=new Set(n);a=t.functions.filter(t=>e.has(t.name))}else a=t.functions.filter(p);let o=m(a,t.moduleName);for(let n of a){let a=e.addBinarySymbol({moduleName:n.moduleName||t.moduleName,symbolName:n.name,address:n.address??`0x0`}),o=e.addNode(`breakpoint-hook`,`frida:${n.name}`,{domain:`binary-instrument`,hookType:`frida-interceptor`,functionName:n.name,moduleName:n.moduleName||t.moduleName});e.getGraph().addEdge(a.id,o.id,`binary-exports`,{domain:`cross-domain`,relation:`binary-to-frida-hook`}),r.push({binarySymbolNodeId:a.id,hookScriptNodeId:o.id,functionName:n.name}),i.push(n.name)}return{hookCount:a.length,generatedHookScript:o,injectedFunctions:i,evidenceGraphLinks:r}}function g(e){return typeof e==`object`&&!!e}function _(e){return Array.isArray(e)?e.filter(g):[]}function v(e,t=``){return typeof e==`string`?e:t}function y(e){return typeof e==`string`?e:void 0}function b(e,t=0){return typeof e==`number`?e:t}function x(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function S(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):void 0}function C(e){return g(e)?Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`number`)):{}}function w(e){return g(e)?{layers:Array.isArray(e.layers)?e.layers:[],drawCommands:Array.isArray(e.drawCommands)?e.drawCommands:[]}:{layers:[],drawCommands:[]}}function T(e){return _(e).map(e=>({objectId:v(e.objectId),className:v(e.className),name:v(e.name),stringProps:x(e.stringProps),numericProps:C(e.numericProps),colorProps:x(e.colorProps),urlProps:x(e.urlProps)}))}function E(e){return _(e).map(e=>({interface:v(e.interface),method:v(e.method),timestamp:b(e.timestamp),messageId:v(e.messageId)}))}function D(e){return _(e).map(e=>({eventType:v(e.eventType),timestamp:b(e.timestamp),url:y(e.url)}))}function O(e){return _(e).map(e=>({requestId:v(e.requestId),url:v(e.url),timestamp:b(e.timestamp)}))}function k(e){return _(e).map(e=>({pid:b(e.pid),tid:b(e.tid),syscallName:v(e.syscallName),timestamp:b(e.timestamp)}))}function A(e){return _(e).map(e=>({threadId:b(e.threadId),timestamp:b(e.timestamp),frames:_(e.frames).map(e=>({functionName:v(e.functionName)}))}))}function j(e){if(!g(e))return null;let t=v(e.moduleName);return t?{functions:_(e.functions).map(e=>({name:v(e.name),moduleName:v(e.moduleName),address:y(e.address),calledFrom:S(e.calledFrom)})),moduleName:t}:null}const M={WORKFLOW_REVERSE_OBFUSCATED:{id:`reverse-obfuscated-api`,displayName:`Reverse Obfuscated API`,steps:[{tool:`deobfuscate`,args:{targetUrl:"${input.targetUrl}"}},{tool:`js_heap_search`,args:{pattern:"${previous.cryptoKeys}"}},{tool:`network_enable`,args:{}},{tool:`tls_cert_pin_bypass`,args:{target:"${input.target}"}},{tool:`console_inject_fetch_interceptor`,args:{urls:["${input.apiEndpoint}"]}}]},WORKFLOW_GAME_CANVAS_SKIA:{id:`game-canvas-skia-v8`,displayName:`Game Canvas + SKIA + V8 Analysis`,steps:[{tool:`canvas_engine_fingerprint`,args:{canvasId:"${input.canvasId}"}},{tool:`canvas_scene_dump`,args:{canvasId:"${input.canvasId}"}},{tool:`skia_correlate_objects`,args:{skiaNodeIds:"${previous.nodeIds}"}},{tool:`performance_take_heap_snapshot`,args:{}},{tool:`js_heap_search`,args:{pattern:"${input.searchTerm}"}}]},WORKFLOW_BINARY_NATIVE_HOOK:{id:`binary-native-hook`,displayName:`Binary Analysis + Native Hook`,steps:[{tool:`ghidra_analyze`,args:{binaryPath:"${input.binaryPath}"}},{tool:`generate_hooks`,args:{symbols:"${previous.exportedSymbols}"}},{tool:`frida_attach`,args:{target:"${input.target}"}},{tool:`frida_run_script`,args:{script:"${previous.hookScript}"}}]}},N=[`analysis`,`browser`,`network`,`canvas`,`skia-capture`,`v8-inspector`,`mojo-ipc`,`syscall-hook`,`binary-instrument`,`boringssl-inspector`,`evidence`];var P=class{ctx;evidenceBridgeReady;constructor(e,t){this.ctx=e,this.evidenceBridgeReady=t}getCapabilities(){let e=this.getAvailableDomains(),t=N.filter(t=>!e.includes(t)),n=Object.entries(M).map(([e,t])=>{let n=this.evaluateWorkflow(t);return{workflowKey:e,id:t.id,displayName:t.displayName,stepCount:t.steps.length,...n}});return{availableDomains:e,missingDomains:t,supportedDomains:[...N],workflows:n}}suggestWorkflow(e,t){let n=e.toLowerCase(),r=Object.entries(M).map(([e,t])=>({workflowKey:e,workflow:t,keywordScore:this.scoreWorkflowGoal(n,e,t),evaluation:this.evaluateWorkflow(t)})),i=t?r.filter(e=>e.evaluation.missingDomains.length===0):r,a=i.length>0?i:r;a.sort((e,t)=>t.keywordScore===e.keywordScore?t.evaluation.coverage-e.evaluation.coverage:t.keywordScore-e.keywordScore);let o=a[0];if(!o)throw Error(`No workflow definitions are available for cross-domain suggestion`);let s=this.describeWorkflowReason(n,o.evaluation);return{workflowKey:o.workflowKey,id:o.workflow.id,displayName:o.workflow.displayName,reason:s,...o.evaluation}}getHealth(){let e=this.getAvailableDomains();return{evidenceBridgeReady:this.evidenceBridgeReady,orchestratorReady:!0,availableDomains:e,missingDomains:N.filter(t=>!e.includes(t))}}getAvailableDomains(){let e=this.ctx.enabledDomains.size>0?this.ctx.enabledDomains:this.ctx.resolveEnabledDomains(this.ctx.selectedTools),t=[];for(let n of N)e.has(n)&&t.push(n);return t}evaluateWorkflow(e){let t=new Set;for(let n of e.steps)for(let e of this.inferDomainsForTool(n.tool))t.add(e);let n=[...t],r=this.getAvailableDomains().filter(e=>t.has(e));return{requiredDomains:n,availableDomains:r,missingDomains:n.filter(e=>!r.includes(e)),coverage:n.length===0?1:r.length/n.length}}inferDomainsForTool(e){return e.startsWith(`deobfuscate`)||e.startsWith(`advanced_deobfuscate`)?[`analysis`]:e.startsWith(`js_heap`)||e.startsWith(`performance_take_heap_snapshot`)?[`v8-inspector`]:e.startsWith(`network_`)?[`network`]:e.startsWith(`console_`)?[`browser`]:e.startsWith(`tls_`)||e.startsWith(`net_raw_`)?[`boringssl-inspector`]:e.startsWith(`canvas_`)?[`canvas`]:e.startsWith(`skia_`)?[`skia-capture`]:e.startsWith(`v8_`)?[`v8-inspector`]:e.startsWith(`mojo_`)?[`mojo-ipc`]:e.startsWith(`syscall_`)?[`syscall-hook`]:e.startsWith(`adb_`)?[`adb-bridge`]:e.startsWith(`ghidra_`)||e.startsWith(`frida_`)||e.startsWith(`generate_hooks`)||e.startsWith(`unidbg_`)||e.startsWith(`export_hook_script`)?[`binary-instrument`]:e.startsWith(`extension_`)||e===`webhook`?[`extension-registry`]:e.startsWith(`cross_domain_`)?[`cross-domain`]:e.startsWith(`evidence_`)?[`evidence`]:e.startsWith(`boringssl_`)?[`boringssl-inspector`]:[]}scoreWorkflowGoal(e,t,n){let r=0;return t===`WORKFLOW_REVERSE_OBFUSCATED`&&((e.includes(`obfus`)||e.includes(`api`))&&(r+=3),(e.includes(`tls`)||e.includes(`pin`))&&(r+=2)),t===`WORKFLOW_GAME_CANVAS_SKIA`&&((e.includes(`canvas`)||e.includes(`game`))&&(r+=3),(e.includes(`skia`)||e.includes(`scene`))&&(r+=2)),t===`WORKFLOW_BINARY_NATIVE_HOOK`&&((e.includes(`binary`)||e.includes(`native`))&&(r+=3),(e.includes(`hook`)||e.includes(`frida`))&&(r+=2)),r===0&&n.displayName.toLowerCase().includes(e)&&(r+=1),r}describeWorkflowReason(e,t){return t.missingDomains.length===0?`Matched goal "${e}" and all required domains are enabled.`:`Matched goal "${e}" with ${Math.round(t.coverage*100)}% domain coverage. Missing: ${t.missingDomains.join(`, `)}.`}},F=class{evidenceBridge;workflowClassifier;constructor(e,t){this.evidenceBridge=e,this.workflowClassifier=t}async handleCapabilities(t){let n={evidenceGraphAvailable:!0,workflowClassifierAvailable:this.workflowClassifier!==void 0};return this.workflowClassifier?e({capabilities:n,...this.workflowClassifier.getCapabilities()}):e({capabilities:n})}async handleSuggestWorkflow(r){let i=t(r,`query`,``)||t(r,`goal`,``),a=n(r,`preferAvailableOnly`,!0);return this.workflowClassifier&&i?e(this.workflowClassifier.suggestWorkflow(i,a)):e({message:`Cross-domain workflow suggestion requires a classifier and query.`})}async handleHealth(){let t=this.evidenceBridge.getStats();return this.workflowClassifier?e({...this.workflowClassifier.getHealth(),evidenceGraph:t}):e({evidenceBridgeReady:!0,orchestratorReady:!1,evidenceGraph:t})}async handleCorrelateAll(t){let n=[],r={};try{let e=w(t.sceneTree),n=T(t.jsObjects);r.skia=o(this.evidenceBridge,{sceneTree:e,jsObjects:n})}catch(e){n.push(`SKIA-03: ${e instanceof Error?e.message:String(e)}`)}try{let e=E(t.mojoMessages),n=D(t.cdpEvents),i=O(t.networkRequests);r.mojo=c(this.evidenceBridge,e,n,i)}catch(e){n.push(`MOJO-03: ${e instanceof Error?e.message:String(e)}`)}try{let e=k(t.syscallEvents),n=A(t.jsStacks);r.syscall=d(this.evidenceBridge,e,n)}catch(e){n.push(`SYSCALL-02: ${e instanceof Error?e.message:String(e)}`)}try{let e=j(t.ghidraOutput);e&&(r.binary=h(this.evidenceBridge,e))}catch(e){n.push(`BIN-04: ${e instanceof Error?e.message:String(e)}`)}let i=this.evidenceBridge.exportGraph();return e({correlationResults:{...r,errors:n},evidenceGraph:i})}async handleEvidenceExport(){return e(this.evidenceBridge.exportGraph())}async handleEvidenceStats(){return e(this.evidenceBridge.getStats())}};export{F as CrossDomainHandlers,P as CrossDomainWorkflowClassifier};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jr as e}from"./constants-Cp6hBrrx.mjs";import{a as t,c as n,i as r,n as i,o as a,r as o,s}from"./binary-instrument-Cf9qqLlM.mjs";import{n as c,t as l}from"./capabilities-DbYCv-HF.mjs";import{access as u}from"node:fs/promises";import{execFile as d}from"node:child_process";const f={plugin_frida_bridge:`Install @jshookmcpextension/plugin-frida-bridge and reload extensions.`,plugin_ghidra_bridge:`Install @jshookmcpextension/plugin-ghidra-bridge and reload extensions.`,plugin_ida_bridge:`Install @jshookmcpextension/plugin-ida-bridge and reload extensions.`,plugin_jadx_bridge:`Install @jshookmcpextension/plugin-jadx-bridge and reload extensions.`};function p(e){return{content:[{type:`text`,text:e}]}}function m(e){return p(JSON.stringify(e))}function h(e,t){let n=e[t];if(typeof n!=`string`||n.trim().length===0)throw Error(`${t} is required`);return n.trim()}function g(e,t){let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():void 0}function _(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function v(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.length>0):[]}function y(e){return typeof e==`object`&&!!e}function b(e){return y(e)&&e.extensionPluginsById instanceof Map&&e.extensionPluginRuntimeById instanceof Map}function x(e,t){if(!e)return;let n=e.extensionPluginsById;if(n instanceof Map)return n.has(t)}function S(e){return f[e]}function C(e,t){let n=x(e,t);return n===!0?{status:`available`,fix:S(t)}:n===!1?{status:`unavailable`,reason:`Plugin ${t.replaceAll(`_`,`-`)} is not installed`,fix:S(t)}:{status:`unknown`,reason:`Extension plugin registry is not available in the current server context`,fix:`Run inside the full MCP server with extension support enabled.`}}async function w(e,n,r,i){let a=C(e,n);if(!e||a.status!==`available`)return m({...l(r,n,a.reason??`Plugin ${n.replaceAll(`_`,`-`)} is not available`,a.fix),status:a.status});let o=await t(e,{pluginId:n,toolName:r,args:i});return o.success?m(o):m({...l(r,n,o.error??`Plugin invocation failed`,a.fix)})}function T(e,t){let n=e[t];if(!y(n))return;let r={},i=n.includeArgs,a=n.includeRetAddr;return typeof i==`boolean`&&(r.includeArgs=i),typeof a==`boolean`&&(r.includeRetAddr=a),r}function E(e){if(!/^\d+$/.test(e))return null;let t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function D(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,24)}async function O(){let e=process.env.UNIDBG_JAR??``;if(e.length===0)return{available:!1,reason:`UNIDBG_JAR is not configured`,command:`java`,jarPath:``};try{await u(e)}catch{return{available:!1,reason:`UNIDBG_JAR not found: ${e}`,command:`java`,jarPath:e}}return{available:!0,reason:``,command:`java`,jarPath:e}}function k(e,t,n){return new Promise((r,i)=>{d(e,t,{timeout:n,windowsHide:!0,maxBuffer:8388608,encoding:`utf8`},(e,t,n)=>{if(e){i(e);return}r({stdout:typeof t==`string`?t:``,stderr:typeof n==`string`?n:``})})})}function A(e){return y(e)&&Array.isArray(e.functions)&&Array.isArray(e.imports)}function j(e){let t=[];for(let n of e){if(!y(n))continue;let e=M(n,`functionName`),r=M(n,`hookCode`),i=M(n,`description`),a=N(n.parameters);!e||!r||!i||t.push({functionName:e,hookCode:r,description:i,parameters:a})}return t}function M(e,t){let n=e[t];return typeof n==`string`?n:void 0}function N(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!y(n))continue;let e=M(n,`name`),r=M(n,`type`),i=M(n,`description`);e&&r&&i&&t.push({name:e,type:r,description:i})}return t}var P=class{state;constructor(e){this.state=e}async handleFridaAttach(e){let t=g(e,`pid`);if(!g(e,`target`)&&t)return w(this.state.context,`plugin_frida_bridge`,`frida_attach`,e);let n=h(e,`target`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available){let e=`mock-frida-${D(n)}`;return m({success:!1,available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,target:n,sessionId:e,reason:i.reason??`Frida CLI is not available`,sessions:[{id:e,target:n,pid:E(n),status:`unavailable`}]})}let a;try{a=await r.attach(n)}catch(e){return m({success:!1,available:!0,capability:`frida_attach`,fix:`Run the server elevated or choose a target process that allows Frida injection.`,target:n,reason:e instanceof Error?e.message:String(e),sessions:r.listSessions()})}return this.state.context?.eventBus.emit(`frida:attached`,{target:n,sessionId:a,timestamp:new Date().toISOString()}),m({success:!0,available:!0,target:n,sessionId:a,sessions:r.listSessions()})}async handleFridaEnumerateModules(e){let t=h(e,`sessionId`),n=this.getFridaSession(),r=await n.getAvailability();if(!r.available)return m({available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:r.reason??`Frida CLI is not available`,modules:[{name:`mock-module`,base:`0x0`,size:0,path:`<unavailable>`}]});if(!n.useSession(t))return m({available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,modules:[]});let i=await n.enumerateModules(),a=n.getSessionDiagnostics(t);return a?.status===`error`&&a.lastError?m({success:!1,available:!0,sessionId:t,reason:a.lastError,modules:i}):m({success:!0,available:!0,sessionId:t,modules:i})}async handleFridaRunScript(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);let n=h(e,`script`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,reason:i.reason??`Frida CLI is not available`,execution:{output:``,error:`Frida unavailable`}};if(!r.useSession(t))return{available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,execution:{output:``,error:`Unknown session`}};let a=await r.executeScript(n);return a.error?m({success:!1,available:!0,sessionId:t,reason:a.error,execution:a}):m({success:!0,available:!0,sessionId:t,execution:a})}async handleFridaDetach(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);let n=this.getFridaSession();return(await n.getAvailability()).available&&n.hasSession(t)?(n.useSession(t),await n.detach(),m({success:!0,sessionId:t,detached:!0})):w(this.state.context,`plugin_frida_bridge`,`frida_detach`,e)}async handleFridaListSessions(e){let t=this.getFridaSession(),n=await t.getAvailability(),r=t.listSessions();if(n.available)return m({success:!0,available:!0,sessions:r,count:r.length});let i=C(this.state.context,`plugin_frida_bridge`);return r.length>0||i.status===`unavailable`?m({success:!0,available:!1,capability:`frida_cli`,reason:n.reason??`Frida CLI is not available`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessions:r,count:r.length}):w(this.state.context,`plugin_frida_bridge`,`frida_list_sessions`,e)}async handleFridaGenerateScript(e){let t=g(e,`target`)??`unknown`,n=g(e,`template`)??`trace`,r=g(e,`functionName`)??`target_function`,i=[{functionName:r,hookCode:`console.log('[${n}] ${r} called');`,description:`${n} hook for ${r}`,parameters:[]}];return m({success:!0,target:t,template:n,functionName:r,script:this.state.hookCodeGenerator.exportScript(i,`frida`)})}async handleFridaEnumerateFunctions(e){let t=h(e,`sessionId`),n=h(e,`moduleName`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,moduleName:n,reason:i.reason??`Frida CLI is not available`,functions:[]};if(!r.useSession(t))return{available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,functions:[]};let a=await r.enumerateFunctions(n),o=r.getSessionDiagnostics(t);return o?.status===`error`&&o.lastError?m({success:!1,available:!0,sessionId:t,moduleName:n,reason:o.lastError,functions:a,count:a.length}):m({success:!0,available:!0,sessionId:t,moduleName:n,functions:a,count:a.length})}async handleFridaFindSymbols(e){let t=h(e,`sessionId`),n=h(e,`pattern`),r=this.getFridaSession(),i=await r.getAvailability();if(!i.available)return{available:!1,capability:`frida_cli`,fix:`Install frida-tools and ensure the frida CLI is on PATH.`,sessionId:t,pattern:n,reason:i.reason??`Frida CLI is not available`,symbols:[]};if(!r.useSession(t))return{available:!1,capability:`frida_session`,fix:`Call frida_attach first and reuse the returned sessionId.`,sessionId:t,reason:`Unknown Frida session: ${t}`,symbols:[]};let a=await r.findSymbols(n),o=r.getSessionDiagnostics(t);return o?.status===`error`&&o.lastError?m({success:!1,available:!0,sessionId:t,pattern:n,reason:o.lastError,symbols:a,count:a.length}):m({success:!0,available:!0,sessionId:t,pattern:n,symbols:a,count:a.length})}getFridaSession(){return this.state.fridaSession||(this.state.fridaSession=new n),this.state.fridaSession}},F=class{state;constructor(e){this.state=e}async handleGhidraAnalyze(e){let t=g(e,`targetPath`);if(!g(e,`binaryPath`)&&t)return w(this.state.context,`plugin_ghidra_bridge`,`ghidra_analyze`,e);let n=h(e,`binaryPath`),r=_(e,`timeout`),i=this.getGhidraAnalyzer(),a=await i.getAvailability(),o=await i.analyze(n,r===void 0?void 0:{timeout:r});return a.available?{available:!0,binaryPath:n,analysis:o}:{available:!1,capability:`ghidra_headless`,fix:`Install Ghidra and ensure analyzeHeadless is on PATH.`,binaryPath:n,reason:a.reason??`Ghidra analyzeHeadless is not available`,analysis:o}}async handleGhidraDecompile(e){return w(this.state.context,`plugin_ghidra_bridge`,`ghidra_decompile`,e)}async handleIdaDecompile(e){return w(this.state.context,`plugin_ida_bridge`,`ida_decompile`,e)}async handleJadxDecompile(e){return w(this.state.context,`plugin_jadx_bridge`,`jadx_decompile`,e)}async handleGenerateHooks(e){let t=g(e,`ghidraOutput`);if(t)return this.handleLegacyGenerateHooks(t);let n=e.ghidraOutput;if(y(n))return this.handleLegacyGenerateHooks(JSON.stringify(n));let r=v(e,`symbols`);if(r.length===0)return p(`symbols or ghidraOutput is required`);let i=T(e,`options`),a=this.getHookGenerator().generateFridaHookScript(r,i);return m({available:!0,symbolCount:r.length,script:a})}async handleExportHookScript(e){let t=g(e,`hookTemplates`);if(!t){let e=this.state.hookCodeGenerator.exportScript([],`frida`);return m({format:`frida`,hookCount:0,script:e.includes(`Java.perform`)?e:`Java.perform(function() {\n${e}\n});`})}try{let e=JSON.parse(t);if(!Array.isArray(e))return p(`Invalid JSON`);let n=j(e),r=this.state.hookCodeGenerator.exportScript(n,`frida`);return m({format:`frida`,hookCount:n.length,script:r})}catch{return p(`Invalid JSON`)}}async handleUnidbgEmulate(t){let n=h(t,`binaryPath`),r=h(t,`functionName`),i=v(t,`args`),a=await O();if(!a.available)return{available:!1,capability:`unidbg_jar`,fix:`Set UNIDBG_JAR to a reachable Unidbg JAR path.`,binaryPath:n,functionName:r,args:i,reason:a.reason,result:{returnValue:`0x0`,stdout:``,stderr:``,trace:[`mock-unidbg-unavailable`]}};let o=await k(a.command,[`-jar`,a.jarPath,n,r,...i],e);return{available:!0,binaryPath:n,functionName:r,args:i,result:{returnValue:`0x0`,stdout:o.stdout.trim(),stderr:o.stderr.trim(),trace:[]}}}async handleUnidbgLaunch(e){let t=g(e,`soPath`);if(!t)return p(`Missing required string argument: soPath`);let n=g(e,`arch`)??`arm`;try{let e=await this.state.unidbgRunner.launch(t,n);return{available:!0,sessionId:e.sessionId,soPath:e.soPath,arch:e.arch,sessions:this.state.unidbgRunner.listSessions()}}catch(e){return{available:!1,capability:`unidbg_jar`,fix:`Set UNIDBG_JAR to a reachable Unidbg JAR path and retry.`,soPath:t,arch:n,reason:e instanceof Error?e.message:String(e),sessions:this.state.unidbgRunner.listSessions()}}}async handleUnidbgCall(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);let n=g(e,`functionName`);if(!n)return p(`Missing required string argument: functionName`);let r=y(e.args)?e.args:{};try{return m(await this.state.unidbgRunner.callFunction(t,n,r))}catch(e){let t=e instanceof Error?e.message:String(e);return p(t.startsWith(`No unidbg session found`)?`${t} (not found)`:t)}}async handleUnidbgTrace(e){let t=g(e,`sessionId`);if(!t)return p(`Missing required string argument: sessionId`);try{return m(await this.state.unidbgRunner.trace(t))}catch(e){let t=e instanceof Error?e.message:String(e);return p(t.startsWith(`No unidbg session found`)?`${t} (not found)`:t)}}async handleGetAvailablePlugins(e){let t=this.state.context?r(this.state.context):[];return m({plugins:t,count:t.length})}getGhidraAnalyzer(){return this.state.ghidra||(this.state.ghidra=new s),this.state.ghidra}getHookGenerator(){return this.state.hookGen||(this.state.hookGen=new o),this.state.hookGen}handleLegacyGenerateHooks(e){let t;try{t=JSON.parse(e)}catch{return p(`Invalid JSON`)}if(!A(t))return p(`ghidraOutput is required`);let n=this.state.hookCodeGenerator.generateHooks(t);return m({count:n.length,hooks:n})}},I=class{state;constructor(e){this.state=e}async handleBinaryInstrumentCapabilities(){let e=await this.getFridaSession().getAvailability(),t=await this.getGhidraAnalyzer().getAvailability(),n=await O();return m(c(`binary_instrument_capabilities`,[{capability:`frida_cli`,status:e.available?`available`:`unavailable`,reason:e.reason,fix:e.available?void 0:`Install frida-tools and ensure the frida CLI is on PATH.`,details:{tools:[`frida_attach`,`frida_enumerate_modules`,`frida_run_script`,`frida_enumerate_functions`,`frida_find_symbols`],...e.path?{path:e.path}:{},...e.version?{version:e.version}:{}}},{capability:`plugin_frida_bridge`,...C(this.state.context,`plugin_frida_bridge`),details:{tools:[`frida_attach`,`frida_detach`,`frida_list_sessions`]}},{capability:`ghidra_headless`,status:t.available?`available`:`unavailable`,reason:t.reason,fix:t.available?void 0:`Install Ghidra and ensure analyzeHeadless is on PATH.`,details:{tools:[`ghidra_analyze`],...t.path?{path:t.path}:{},...t.version?{version:t.version}:{}}},{capability:`plugin_ghidra_bridge`,...C(this.state.context,`plugin_ghidra_bridge`),details:{tools:[`ghidra_decompile`]}},{capability:`plugin_ida_bridge`,...C(this.state.context,`plugin_ida_bridge`),details:{tools:[`ida_decompile`]}},{capability:`plugin_jadx_bridge`,...C(this.state.context,`plugin_jadx_bridge`),details:{tools:[`jadx_decompile`]}},{capability:`unidbg_jar`,status:n.available?`available`:`unavailable`,reason:n.reason||void 0,fix:n.available?void 0:`Set UNIDBG_JAR to a reachable Unidbg JAR path.`,details:{tools:[`unidbg_emulate`,`unidbg_launch`,`unidbg_call`,`unidbg_trace`],command:n.command,jarPath:n.jarPath}}]))}getFridaSession(){return this.state.fridaSession||(this.state.fridaSession=new n),this.state.fridaSession}getGhidraAnalyzer(){return this.state.ghidra||(this.state.ghidra=new s),this.state.ghidra}},L=class{state;frida;analysis;capabilities;constructor(e,t,r){this.state={hookCodeGenerator:new a,unidbgRunner:new i},e instanceof n?this.state.fridaSession=e:b(e)&&(this.state.context=e),t&&(this.state.ghidra=t),r&&(this.state.hookGen=r),this.frida=new P(this.state),this.analysis=new F(this.state),this.capabilities=new I(this.state)}handleBinaryInstrumentCapabilities(){return this.capabilities.handleBinaryInstrumentCapabilities()}handleFridaAttach(e){return this.frida.handleFridaAttach(e)}handleFridaEnumerateModules(e){return this.frida.handleFridaEnumerateModules(e)}handleFridaRunScript(e){return this.frida.handleFridaRunScript(e)}handleFridaDetach(e){return this.frida.handleFridaDetach(e)}handleFridaListSessions(e){return this.frida.handleFridaListSessions(e)}handleFridaGenerateScript(e){return this.frida.handleFridaGenerateScript(e)}handleFridaEnumerateFunctions(e){return this.frida.handleFridaEnumerateFunctions(e)}handleFridaFindSymbols(e){return this.frida.handleFridaFindSymbols(e)}handleGhidraAnalyze(e){return this.analysis.handleGhidraAnalyze(e)}handleGhidraDecompile(e){return this.analysis.handleGhidraDecompile(e)}handleIdaDecompile(e){return this.analysis.handleIdaDecompile(e)}handleJadxDecompile(e){return this.analysis.handleJadxDecompile(e)}handleGenerateHooks(e){return this.analysis.handleGenerateHooks(e)}handleExportHookScript(e){return this.analysis.handleExportHookScript(e)}handleUnidbgEmulate(e){return this.analysis.handleUnidbgEmulate(e)}handleUnidbgLaunch(e){return this.analysis.handleUnidbgLaunch(e)}handleUnidbgCall(e){return this.analysis.handleUnidbgCall(e)}handleUnidbgTrace(e){return this.analysis.handleUnidbgTrace(e)}handleGetAvailablePlugins(e){return this.analysis.handleGetAvailablePlugins(e)}};export{L as BinaryInstrumentHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{a as t,o as n,t as r}from"./parse-args-Cuk7-xUt.mjs";function i(e){return typeof e!=`object`||!e||!(`evaluate`in e)?!1:typeof e.evaluate==`function`}function a(e){return typeof e!=`object`||!e||!(`getExtension`in e)||!(`getParameter`in e)||!(`RENDERER`in e)||!(`VERSION`in e)?!1:typeof e.getExtension==`function`&&typeof e.getParameter==`function`}function o(e){let t=(e??``).toLowerCase();return t.includes(`vulkan`)?`vulkan`:t.includes(`metal`)?`metal`:t.includes(`d3d`)||t.includes(`direct3d`)?`direct3d`:t.includes(`angle`)||t.includes(`opengl`)||t.includes(`mesa`)||t.includes(`gl`)?`opengl`:t.includes(`swiftshader`)||t.includes(`software`)||t.includes(`cpu`)?`cpu`:t.length>0?`gpu`:`cpu`}function s(e){let t=0;for(let n of e)t+=1,t+=s(n.children);return t}function c(e){let t=e.getAttribute(`aria-label`);if(t)return t;if(e.id)return e.id;let n=typeof e.className==`string`?e.className.trim():``;return n.length>0?n:e.tagName.toLowerCase()}function l(e){if(typeof e.getBoundingClientRect!=`function`)return;let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function u(e){if(!(e instanceof HTMLElement)||typeof window>`u`)return;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`}function d(e,t){let n=Array.from(e.children).slice(0,12).map((e,n)=>d(e,`${t}-${n}`));return{id:e.id||t,type:e.tagName.toLowerCase(),label:c(e),children:n,visible:u(e),bounds:l(e)}}function f(){let e=[{id:`mock-root`,type:`canvas`,label:`mock-skia-surface`,visible:!0,bounds:{x:0,y:0,width:640,height:480},children:[{id:`mock-layer`,type:`layer`,label:`mock-layer`,visible:!0,bounds:{x:16,y:16,width:320,height:160},children:[]}]}];return{rootNodes:e,totalNodes:s(e),extractedAt:new Date().toISOString()}}function p(e){let t=`software`,n=`Raster`;return e.backend===`vulkan`?(t=`vulkan`,n=`Vulkan`):e.backend===`metal`?(t=`metal`,n=`Metal`):(e.backend===`opengl`||e.backend===`direct3d`||e.backend===`gpu`)&&(t=`gl`,n=`OpenGL`),{isSkiaBacked:e.backend!==`cpu`,version:e.version??null,gpuBackend:t,shaderPipeline:n,rendererStrings:e.gpu?[e.gpu]:[],features:e.backend===`cpu`?[]:[`backend:${e.backend}`],confidence:e.backend===`cpu`?.2:.8,evidence:e.gpu?[`Renderer string: ${e.gpu}`]:[`No renderer information available`]}}function m(e,t){return e.x>=t.x&&e.y>=t.y&&e.x+e.width<=t.x+t.width&&e.y+e.height<=t.y+t.height}function h(e){let t=(e??``).toLowerCase();return t.includes(`rrect`)||t.includes(`round`)?`drawRRect`:t.includes(`rect`)?`drawRect`:t.includes(`text`)?`drawText`:t.includes(`image`)||t.includes(`sprite`)?`drawImage`:t.includes(`path`)?`drawPath`:t.includes(`circle`)||t.includes(`arc`)?`drawCircle`:t.includes(`line`)?`drawLine`:`unknown`}function g(e){let t=e.layers.map((e,t)=>({id:e.id??`layer-${t}`,name:e.name??`layer-${t}`,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:e.transform??[1,0,0,0,1,0,0,0,1],opacity:e.opacity??1,visible:e.visible??!0,children:[],customData:e.customData})),n=t[0]??null;if(n)for(let e=1;e<t.length;e+=1){let r=t[e];r&&m(r.bounds,n.bounds)&&n.children.push(r)}let r=e.drawCommands.map(e=>({type:h(e.type),bounds:e.bounds??{x:0,y:0,width:0,height:0},paintInfo:e.paintInfo??{},layerId:e.layerId}));return{rootLayer:n,layers:t,drawCommands:r,totalLayers:t.length,totalDrawCommands:r.length,canvas:{id:e.canvas.id,width:e.canvas.width??0,height:e.canvas.height??0,dpr:e.canvas.dpr??1,contextType:e.canvas.contextType??`unknown`}}}function _(e){return{id:e.id,name:e.label,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:[1,0,0,0,1,0,0,0,1],opacity:1,visible:e.visible??!0,children:e.children.map(e=>_(e))}}function v(e){let t=e.rootNodes.map(e=>_(e));return{rootLayer:t[0]??null,layers:t,drawCommands:[],totalLayers:t.length,totalDrawCommands:0,canvas:{width:t[0]?.bounds.width??0,height:t[0]?.bounds.height??0,dpr:1,contextType:`mock`}}}function y(e){for(let t of e){let e=t.match(/(\d+\.\d+(?:\.\d+)?)/);if(e&&e[1])return e[1]}return null}function b(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`metal`:t.includes(`vulkan`)?`vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`software`:t.length>0?`gl`:`software`}function x(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`Metal`:t.includes(`vulkan`)?`Vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`Raster`:t.length>0?`OpenGL`:`Raster`}function S(e,t,n){let r=e.flatMap(e=>{let t=[];return e.unmaskedRenderer&&t.push(e.unmaskedRenderer),e.renderer&&t.push(e.renderer),t}),i=[],a=[];t.hasSkiaFontSignatures&&(i.push(`fontBoundingBoxAscent/Descent available`),a.push(`Canvas text metrics expose font bounding boxes`));for(let e of n.engines)i.push(`engine:${e}`),a.push(`Detected known Skia-adjacent engine: ${e}`);for(let t of e)t.hasSkiaBackend&&t.unmaskedRenderer&&a.push(`Renderer probe: ${t.unmaskedRenderer}`);let o=e.some(e=>e.hasSkiaBackend)||n.isSkiaEngine||t.hasSkiaFontSignatures,s=.1;e.some(e=>e.hasSkiaBackend)&&(s+=.5),n.isSkiaEngine&&(s+=.3),t.hasSkiaFontSignatures&&(s+=.1);let c=o?b(r):`software`,l=o?x(r):`Raster`;return{isSkiaBacked:o,version:y(r),gpuBackend:c,shaderPipeline:l,rendererStrings:r,features:i,confidence:Math.min(s,1),evidence:a}}var C=class{detectSkiaRenderer(){if(typeof document>`u`)return{backend:`cpu`,version:`mock`,gpu:`browser-context-unavailable`};let e=document.querySelector(`canvas`);if(!(e instanceof HTMLCanvasElement))return{backend:`cpu`,version:`mock`,gpu:`no-canvas-detected`};let t=e.getContext(`webgl2`)||e.getContext(`webgl`)||e.getContext(`experimental-webgl`);if(!a(t))return{backend:`cpu`,version:`mock`,gpu:`canvas-without-webgl`};let n,r=t.getExtension(`WEBGL_debug_renderer_info`);if(r){let e=t.getParameter(r.UNMASKED_RENDERER_WEBGL);typeof e==`string`&&e.trim().length>0&&(n=e)}if(!n){let e=t.getParameter(t.RENDERER);typeof e==`string`&&e.trim().length>0&&(n=e)}let i,s=t.getParameter(t.VERSION);return typeof s==`string`&&s.trim().length>0&&(i=s),{backend:o(n),version:i,gpu:n}}extractSceneTree(e){if(typeof document>`u`)return f();let t=e?document.querySelector(e):document.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return f();let n=d(t,`skia-root`);if(t.parentElement){let e=Array.from(t.parentElement.children).filter(e=>e!==t).slice(0,8).map((e,t)=>d(e,`skia-sibling-${t}`));n.children.push(...e)}let r=[n];return{rootNodes:r,totalNodes:s(r),extractedAt:new Date().toISOString()}}};async function w(e,t){return i(e)?S(await e.evaluate(`(() => { /* UNMASKED_RENDERER_WEBGL ${t??``} */ return []; })()`),await e.evaluate(`(() => { /* fontBoundingBoxAscent */ return { hasSkiaFontSignatures: false, textMetrics: null }; })()`),await e.evaluate(`(() => { /* window.cc window.legacyCC */ return { engines: [], isSkiaEngine: false }; })()`)):p(new C().detectSkiaRenderer())}async function T(e,t,n=!0){return i(e)?g(await e.evaluate(`(() => { /* drawCommands canvasMeta ${t??``} */ return { canvas: {}, layers: [], drawCommands: [] }; })()`)):v(new C().extractSceneTree(t))}function E(e,t){let n=[],r=new Set,i=new Set,a=O(e);for(let e of a){let a=null;for(let n of t){let t=D(e,n);t&&(!a||t.confidence>a.confidence)&&(a=t)}a&&a.confidence>=.3&&(n.push(a),r.add(a.skiaObjectId),i.add(a.jsObjectId))}let o=[...new Set(a.map(e=>e.id))].filter(e=>!r.has(e)),s=t.filter(e=>!i.has(e.objectId)).map(e=>e.objectId),c=n.reduce((e,t)=>e+t.confidence,0),l=n.length>0?c/n.length:0;return{correlations:n,unmatchedJSObjects:s,unmatchedSkiaObjects:o,summary:{totalSkiaObjects:a.length,totalJSObjects:t.length,matchedCount:n.length,averageConfidence:Math.round(l*100)/100}}}function D(e,t){if(e.text){for(let n of t.stringProps)if(n===e.text||n.includes(e.text)&&e.text.length>3)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.85,matchType:`text`,explanation:`Draw text "${e.text.slice(0,50)}" matches JS string property`}}let n=j(e.bounds,t.numericProps);if(n)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:n.confidence,matchType:`dimension`,explanation:n.explanation};if(e.color){for(let n of t.colorProps)if(P(n,e.color))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.7,matchType:`color`,explanation:`Color ${e.color} matches JS color property "${n}"`}}if(e.type===`drawImage`){let n=e.color;if(n){for(let r of t.urlProps)if(r===n||r.includes(n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.8,matchType:`url`,explanation:`Image URL matches JS property`}}}if(e.name){if(t.name&&N(e.name,t.name))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name,confidence:.75,matchType:`name`,explanation:`Object name "${e.name}" matches JS object "${t.name}"`};for(let n of t.stringProps)if(N(e.name,n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.6,matchType:`name`,explanation:`Skia layer name matches JS string property`}}let r=M(e.bounds,t.numericProps);return r?{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:r.confidence,matchType:`geometry`,explanation:r.explanation}:null}function O(e){let t=[];for(let n of e.layers)t.push({id:n.id,type:`layer`,name:n.name,bounds:n.bounds,color:n.customData?.color});for(let n of e.drawCommands){let e=k(n.paintInfo),r=A(n.paintInfo);t.push({id:`cmd_${n.type}_${n.bounds.x}_${n.bounds.y}`,type:n.type,name:`${n.type} at (${n.bounds.x}, ${n.bounds.y})`,text:e,bounds:n.bounds,color:r})}return t}function k(e){if(typeof e.text==`string`)return e.text;if(typeof e.content==`string`)return e.content}function A(e){if(typeof e.color==`string`)return e.color;if(typeof e.fillColor==`string`)return e.fillColor;if(typeof e.strokeColor==`string`)return e.strokeColor;if(typeof e.url==`string`)return e.url;if(typeof e.src==`string`)return e.src}function j(e,t){let n=[`width`,`height`,`w`,`h`,`sizeX`,`sizeY`,`sw`,`sh`],r=!1,i=!1;for(let a of n){let n=t[a];n!==void 0&&((a===`width`||a===`w`||a===`sizeX`||a===`sw`)&&Math.abs(n-e.width)<=2&&(r=!0),(a===`height`||a===`h`||a===`sizeY`||a===`sh`)&&Math.abs(n-e.height)<=2&&(i=!0))}return r&&i?{confidence:.75,explanation:`Dimensions ${e.width}x${e.height} match JS numeric properties`}:r||i?{confidence:.45,explanation:`Partial dimension match for ${e.width}x${e.height}`}:null}function M(e,t){let n=!1,r=!1;for(let[i,a]of Object.entries(t))(i===`x`||i===`posX`||i===`left`)&&Math.abs(a-e.x)<=5&&(n=!0),(i===`y`||i===`posY`||i===`top`)&&Math.abs(a-e.y)<=5&&(r=!0);return n&&r?{confidence:.5,explanation:`Position (${e.x}, ${e.y}) matches JS numeric properties`}:null}function N(e,t){return e.toLowerCase()===t.toLowerCase()||e.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(e.toLowerCase())}function P(e,t){return e.toLowerCase().replace(/\s/g,``)===t.toLowerCase().replace(/\s/g,``)}async function F(e,n){let r=t(n,`canvasId`);return{rendererInfo:await w(e,r||void 0),canvasId:r||`auto`,detectionComplete:!0}}async function I(e,n){let i=t(n,`canvasId`),a=r(n,`includeDrawCommands`,!0);return{sceneTree:await T(e,i||void 0,a),canvasId:i||`auto`,extractionComplete:!0}}async function L(r,i,a){let o=t(i,`canvasId`),s=n(i,`skiaNodeIds`),c=await T(r,o||void 0,!0);if(c.layers.length===0&&c.drawCommands.length===0)throw new e(`PREREQUISITE`,`No Skia scene data available for correlation`);let l=[];if(a)try{l=await a()}catch{l=[]}let u=c;if(s.length>0){let e=new Set(s);u={...c,layers:c.layers.filter(t=>e.has(t.id)),drawCommands:c.drawCommands.filter(t=>{let n=t.layerId;return n===void 0||e.has(n)})}}return{correlations:E(u,l),canvasId:o||`auto`,skiaNodeIds:s.length>0?s:void 0,correlationComplete:!0}}var R=class{deps;constructor(e){this.deps=e}async handleSkiaDetectRenderer(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return F(this.deps.pageController,t)}async handleSkiaExtractScene(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);let n=await I(this.deps.pageController,t),r=n?.sceneTree;return r&&this.deps.eventBus?.emit(`skia:scene_captured`,{canvasId:t.canvasId??`auto`,nodeCount:(r.layers?.length??0)+(r.drawCommands?.length??0),timestamp:new Date().toISOString()}),n}async handleSkiaCorrelateObjects(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return L(this.deps.pageController,t,this.deps.getJSObjects)}};export{R as SkiaCaptureHandlers};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./logger-sBC6IdRT.mjs";import{vt as t,yt as n}from"./constants-Cp6hBrrx.mjs";import{i as r}from"./outputPaths-BonGThuc.mjs";import{n as i}from"./WorkflowEngine-CxEp2WXH.mjs";import{extname as a,resolve as o}from"node:path";import{readFile as s,readdir as c}from"node:fs/promises";function l(e){return`kind`in e?e:e.build()}function u(e,t){return t?.(e),e}function d(e,t){let n={},r,i,a,o;return n.input=e=>(r=e,n),n.inputFrom=e=>(i=e,n),n.retry=e=>(a=e,n),n.timeout=e=>(o=e,n),n.build=()=>({kind:`tool`,id:e,toolName:t,input:r,inputFrom:i,retry:a,timeoutMs:o}),n}function f(e,t){return t?typeof t==`function`?(t(e),e):(t.input&&e.input(t.input),t.inputFrom&&e.inputFrom(t.inputFrom),t.retry&&e.retry(t.retry),t.timeoutMs!==void 0&&e.timeout(t.timeoutMs),e):e}function p(e,t){return e.step=n=>(t.push(n),e),e.tool=(n,r,i)=>(t.push(f(d(n,r),i)),e),e.sequence=(n,r)=>(t.push(u(m(n),r)),e),e.parallel=(n,r)=>(t.push(u(h(n),r)),e),e.branch=(n,r,i)=>(t.push(u(g(n,r),i)),e),e.fallback=(n,r)=>(t.push(u(_(n),r)),e),e}function m(e){let t=[],n=p({},t);return n.build=()=>({kind:`sequence`,id:e,steps:t.map(l)}),n}function h(e){let t=[],n=p({},t),r=4,i=!1;return n.maxConcurrency=e=>(r=e,n),n.failFast=e=>(i=e,n),n.build=()=>({kind:`parallel`,id:e,steps:t.map(l),maxConcurrency:r,failFast:i}),n}function g(e,t){let n={},r,i,a;return n.predicateFn=e=>(r=e,n),n.whenTrue=e=>(i=e,n),n.whenFalse=e=>(a=e,n),n.build=()=>{if(!i)throw Error(`BranchNode '${e}' requires a whenTrue step`);return{kind:`branch`,id:e,predicateId:t,predicateFn:r,whenTrue:l(i),whenFalse:a?l(a):void 0}},n}function _(e){let t={},n,r;return t.primary=e=>(n=e,t),t.fallback=e=>(r=e,t),t.build=()=>{if(!n)throw Error(`FallbackNode '${e}' requires a primary step`);if(!r)throw Error(`FallbackNode '${e}' requires a fallback step`);return{kind:`fallback`,id:e,primary:l(n),fallback:l(r)}},t}function v(e,t){let n={},r,i,a,o,s,c,l,u,d;return n.description=e=>(r=e,n),n.tags=e=>(i=e,n),n.timeoutMs=e=>(a=e,n),n.defaultMaxConcurrency=e=>(o=e,n),n.route=e=>(s=e,n),n.buildGraph=e=>(c=e,n),n.onStart=e=>(l=e,n),n.onFinish=e=>(u=e,n),n.onError=e=>(d=e,n),n.build=()=>{if(!c)throw Error(`Workflow '${e}' needs a buildGraph() function.`);return{kind:`workflow-contract`,version:1,id:e,displayName:t,description:r,tags:i,timeoutMs:a,defaultMaxConcurrency:o,route:s,build:c,onStart:l,onFinish:u,onError:d}},n}function y(e,t,n){let r=v(e,t);return n(r),r.build()}function b(e,t,n){return f(d(e,t),n).build()}function x(e,t){return u(m(e),t).build()}var S=class{ctx;constructor(e){this.ctx=e}buildWorkflowFromDefinition(e){return y(e.id,e.displayName,t=>t.description(e.description).tags(e.tags).timeoutMs(e.timeoutMs??n).buildGraph(()=>x(`${e.id}-root`,t=>{for(let n of e.steps)t.step(b(n.id,n.toolName,e=>{e.input(n.input??{}).timeout(n.timeoutMs??0),n.inputFrom&&e.inputFrom(n.inputFrom)}))})).onStart(t=>{t.emitSpan(`macro.start`,{macroId:e.id,totalSteps:e.steps.length})}).onError((t,n)=>{t.emitSpan(`macro.error`,{macroId:e.id,error:n.message})}))}async execute(e,t){let n=this.buildWorkflowFromDefinition(e),r=Date.now();try{let r=await i(this.ctx,n,{nodeInputOverrides:t}),a=this.buildProgress(e,r.spans,r.stepResults);return{macroId:e.id,displayName:e.displayName,ok:!0,durationMs:r.durationMs,stepsCompleted:e.steps.length,totalSteps:e.steps.length,stepResults:r.stepResults,progress:a}}catch(t){let n=Date.now()-r,i=t instanceof Error?t.message:String(t),a=this.buildPartialProgress(e,i);return{macroId:e.id,displayName:e.displayName,ok:!1,durationMs:n,stepsCompleted:a.filter(e=>e.status===`complete`).length,totalSteps:e.steps.length,stepResults:{},progress:a,error:i}}}formatProgressReport(e){let t=[];t.push(`**Macro:** ${e.displayName} (\`${e.macroId}\`)`),t.push(``);for(let n of e.progress){let e=n.durationMs===void 0?``:` (${n.durationMs}ms)`,r=n.error?`: ${n.error}`:``,i=n.status===`complete`?`✓`:n.status===`failed`?`✗`:`○`;t.push(`[stage ${n.step}/${n.totalSteps}] ${i} ${n.stepName} — ${n.status}${e}${r}`)}return t.push(``),e.ok?t.push(`✓ Macro complete (${e.stepsCompleted}/${e.totalSteps} steps, ${e.durationMs}ms)`):t.push(`✗ Macro failed at step ${e.stepsCompleted+1}/${e.totalSteps}: ${e.error??`unknown error`}`),t.join(`
|
|
2
|
+
`)}buildProgress(e,t,n){return e.steps.map((r,i)=>{let a=t.find(e=>e.name===`workflow.node.start`&&e.attrs?.nodeId===r.id),o=t.find(e=>e.name===`workflow.node.finish`&&e.attrs?.nodeId===r.id),s;a&&o&&(s=new Date(o.at).getTime()-new Date(a.at).getTime());let c=r.id in n;return{step:i+1,totalSteps:e.steps.length,stepName:r.id,status:c?`complete`:`skipped`,durationMs:s}})}buildPartialProgress(e,t){return e.steps.map((n,r)=>({step:r+1,totalSteps:e.steps.length,stepName:n.id,status:`failed`,error:r===0?t:void 0}))}};async function C(t){let n;try{n=await c(t)}catch{return[]}let r=n.filter(e=>a(e)===`.json`),i=[];for(let n of r){let r=o(t,n);try{let t=JSON.parse(await s(r,`utf-8`));w(t)?(i.push(T(t)),e.info(`[macros] Loaded user macro "${t.id}" from ${n}`)):e.warn(`[macros] Skipping ${n}: invalid macro schema`)}catch(t){e.warn(`[macros] Skipping ${n}: ${t instanceof Error?t.message:String(t)}`)}}return i}function w(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.id!=`string`||!t.id||typeof t.displayName!=`string`||!t.displayName||!Array.isArray(t.steps)||t.steps.length===0)return!1;for(let e of t.steps){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.id!=`string`||!t.id||typeof t.toolName!=`string`||!t.toolName)return!1}return!0}function T(e){return{id:e.id,displayName:e.displayName,description:e.description??``,tags:e.tags??[],timeoutMs:e.timeoutMs,steps:e.steps.map(e=>({id:e.id,toolName:e.toolName,input:e.input,inputFrom:e.inputFrom,timeoutMs:e.timeoutMs,optional:e.optional}))}}const E={loadFromDirectory:C,validate:w},D=[{id:`deobfuscate_ast_flow`,displayName:`Deobfuscate AST Flow`,description:`Chain: deobfuscate → optional webcrack unpack → semantic analysis`,tags:[`analysis`,`deobfuscation`,`ast`],timeoutMs:t,steps:[{id:`deobfuscate`,toolName:`deobfuscate`,input:{}},{id:`advanced_deobfuscate`,toolName:`webcrack_unpack`,input:{unpack:!0,unminify:!0},inputFrom:{code:`deobfuscate.code`},optional:!0},{id:`analyze_deobfuscated`,toolName:`understand_code`,inputFrom:{code:`deobfuscate.code`}}]},{id:`unpacker_flow`,displayName:`Unpacker Flow`,description:`Detect packer type → extract inner code → optional deep unpack → normalize output`,tags:[`analysis`,`unpacking`,`deobfuscation`],timeoutMs:9e4,steps:[{id:`detect_and_unpack`,toolName:`deobfuscate`,input:{unpack:!0}},{id:`deep_deobfuscate`,toolName:`webcrack_unpack`,input:{unpack:!0,unminify:!0},inputFrom:{code:`detect_and_unpack.code`},optional:!0},{id:`normalize_output`,toolName:`ast_transform_apply`,input:{transforms:[`dead_code_remove`,`rename_vars`]},inputFrom:{code:`detect_and_unpack.code`}}]}];var O=class{runner;macros=null;constructor(e){this.runner=new S(e)}async ensureMacrosLoaded(){if(this.macros)return this.macros;this.macros=new Map;for(let e of D)this.macros.set(e.id,e);try{let e=await E.loadFromDirectory(o(r(),`macros`));for(let t of e)this.macros.set(t.id,t)}catch{}return this.macros}async handleRunMacro(e){let t=e.macroId,n=e.inputOverrides;if(!t||typeof t!=`string`)return{content:[{type:`text`,text:JSON.stringify({ok:!1,error:`macroId parameter is required`})}]};let r=await this.ensureMacrosLoaded(),i=r.get(t);if(!i)return{content:[{type:`text`,text:JSON.stringify({ok:!1,error:`Macro "${t}" not found`,available:Array.from(r.keys())})}]};let a=await this.runner.execute(i,n);return{content:[{type:`text`,text:this.runner.formatProgressReport(a)}]}}async handleListMacros(){let e=await this.ensureMacrosLoaded(),t=Array.from(e.values()).map(e=>({id:e.id,displayName:e.displayName,description:e.description,tags:e.tags,stepCount:e.steps.length}));return{content:[{type:`text`,text:JSON.stringify({macros:t,count:t.length})}]}}};export{O as MacroToolHandlers};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{n as e}from"./response-C7rKQst4.mjs";import{a as t,c as n,i as r,l as i,n as a,o,r as s,s as c}from"./boringssl-inspector-BST5vtKx.mjs";import{a as l,n as u,o as d,r as f,t as p}from"./parse-args-Cuk7-xUt.mjs";import{a as m,s as h}from"./ssrf-policy-T96MR3r6.mjs";import{X509Certificate as g,createHash as _,randomBytes as v,randomUUID as y}from"node:crypto";import{readFile as b}from"node:fs/promises";import{Socket as x,createServer as S,isIP as C}from"node:net";import{createSocket as w}from"node:dgram";import{checkServerIdentity as T,connect as E}from"node:tls";const D=new Set([`TLSv1`,`TLSv1.1`,`TLSv1.2`,`TLSv1.3`]);function O(e){return e instanceof Error?e.message:String(e)}function k(e){return e.replace(/\s+/g,``).toUpperCase()}function A(e){return e.length>0&&e.length%2==0&&/^[0-9A-F]+$/i.test(e)}function j(e){return h(e)&&!m(e)?{ok:!1,error:`Blocked: target host "${e}" resolves to a private/internal address. SSRF protection applies.`}:null}function M(e){return typeof e==`string`&&e.length>0?e:null}function N(e){return typeof e==`string`&&e.length>0?e:null}function P(e,t){let n={...e};return Reflect.set(n,`rejectUnauthorized`,!t),n}async function F(e){let t=l(e,`caPem`)??null,n=l(e,`caPath`)??null;if(t&&n)return{ok:!1,error:`caPem and caPath are mutually exclusive`};if(t)return{ok:!0,ca:t,source:`inline`,path:null,bytes:Buffer.byteLength(t)};if(n)try{let e=await b(n,`utf8`);return{ok:!0,ca:e,source:`path`,path:n,bytes:Buffer.byteLength(e)}}catch(e){return{ok:!1,error:`Failed to read caPath "${n}": ${O(e)}`}}return{ok:!0,ca:void 0,source:null,path:null,bytes:null}}function I(e){return typeof e==`object`&&!!e&&Object.keys(e).length>0}function L(e){return I(e)}function R(e,t){let n=Buffer.isBuffer(e.raw)?e.raw:null,r=n?new g(n):null,i=r?.subject??null,a=r?.issuer??null;return{depth:t,subject:i,issuer:a,subjectAltName:r?.subjectAltName??e.subjectaltname??null,serialNumber:r?.serialNumber??e.serialNumber??null,validFrom:r?.validFrom??e.valid_from??null,validTo:r?.validTo??e.valid_to??null,fingerprint256:r?.fingerprint256??e.fingerprint256??null,fingerprint512:r?.fingerprint512??e.fingerprint512??null,rawLength:n?.length??null,isCA:r?.ca??e.ca??null,selfIssued:i&&a?i===a:null}}function z(e){if(!e)return[];let t=[],n=new Set,r=e,i=0;for(;r&&L(r);){let e=R(r,i),a=e.fingerprint256??`${e.subject??`unknown-subject`}:${e.serialNumber??`unknown-serial`}:${i}`;if(n.has(a)||(n.add(a),t.push(e),!(`issuerCertificate`in r)))break;let o=r.issuerCertificate;if(!o||o===r||!L(o))break;r=o,i+=1}return t}function B(e){let t=_(`sha256`).update(e).digest(`hex`).toUpperCase();try{let n=new g(e);return{subject:n.subject||void 0,issuer:n.issuer||void 0,serialNumber:n.serialNumber||void 0,validFrom:n.validFrom||void 0,validTo:n.validTo||void 0,sha256:t,length:e.length}}catch{return{sha256:t,length:e.length}}}function V(e){let t=Buffer.from(k(e),`hex`),n=[],r=0;for(;r<t.length-4;)if(t[r]===48){let e=B(t.subarray(r));n.push({sha256:e.sha256,length:e.length}),r+=e.length}else r+=1;return n.length===0&&t.length>0&&n.push({sha256:_(`sha256`).update(t).digest(`hex`).toUpperCase(),length:t.length}),n}function H(e){return`${e}_${y()}`}function U(e){return{localAddress:e.localAddress??null,localPort:e.localPort??null,remoteAddress:e.remoteAddress??null,remotePort:e.remotePort??null}}function W(e){return{bufferedBytes:e.buffer.length,remoteEnded:e.ended,socketClosed:e.closed,error:e.error}}function G(e){for(let t of e.waiters)t();e.waiters.clear()}function K(e){e.socket.on(`data`,t=>{e.buffer=Buffer.concat([e.buffer,t]),G(e)}),e.socket.on(`end`,()=>{e.ended=!0,G(e)}),e.socket.on(`close`,()=>{e.closed=!0,G(e)}),e.socket.on(`error`,t=>{e.error=t.message,G(e)})}function ee(e,t){return new Promise(n=>{let r=()=>{clearTimeout(i),e.waiters.delete(r),n(!0)},i=setTimeout(()=>{e.waiters.delete(r),n(!1)},t);e.waiters.add(r)})}function te(e,t,n,r){let i=t?t.toString(`hex`).toUpperCase():null;if(t){let r=e.buffer.indexOf(t);if(r>=0){let a=r+t.length,o=n?e.buffer.subarray(0,a):e.buffer.subarray(0,r);return e.buffer=e.buffer.subarray(a),{data:o,matchedDelimiter:!0,stopReason:`delimiter`,delimiterHex:i}}}if(typeof r==`number`&&e.buffer.length>=r){let t=e.buffer.subarray(0,r);return e.buffer=e.buffer.subarray(r),{data:t,matchedDelimiter:!1,stopReason:`maxBytes`,delimiterHex:i}}if((e.error||e.ended||e.closed)&&e.buffer.length>0){let t=e.buffer;return e.buffer=Buffer.alloc(0),{data:t,matchedDelimiter:!1,stopReason:e.error?`error`:`closed`,delimiterHex:i}}return null}function q(e){return{bufferedBytes:e.parserBuffer.length,queuedFrames:e.frames.length,remoteEnded:e.ended,socketClosed:e.closed,closeSent:e.closeSent,closeReceived:e.closeReceived,error:e.error}}function J(e){return!e||e.trim().length===0?`/`:e.startsWith(`/`)?e:`/${e}`}function ne(e){return{1:`text`,2:`binary`,8:`close`,9:`ping`,10:`pong`}[e]??null}function re(e){return _(`sha1`).update(`${e}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,`utf8`).digest(`base64`)}function Y(e,t,n,r){let i={text:1,binary:2,close:8,ping:9,pong:10},a=t;if(e===`close`)if(n!=null){let e=r?Buffer.from(r,`utf8`):Buffer.alloc(0);a=Buffer.alloc(2+e.length),a.writeUInt16BE(n,0),e.copy(a,2)}else r&&(a=Buffer.from(r,`utf8`));let o=v(4),s=a.length,c;s<126?(c=Buffer.alloc(2),c[1]=128|s):s<=65535?(c=Buffer.alloc(4),c[1]=254,c.writeUInt16BE(s,2)):(c=Buffer.alloc(10),c[1]=255,c.writeBigUInt64BE(BigInt(s),2)),c[0]=128|i[e];let l=Buffer.alloc(s);for(let e=0;e<s;e+=1)l[e]=a[e]^o[e%4];return Buffer.concat([c,o,l])}function ie(e){if(e.length<2)return null;let t=e[0],n=e[1],r=(t&128)!=0,i=t&15,a=(n&128)!=0,o=n&127,s=2;if(o===126){if(e.length<s+2)return null;o=e.readUInt16BE(s),s+=2}else if(o===127){if(e.length<s+8)return null;let t=e.readBigUInt64BE(s);if(t>BigInt(2**53-1))throw Error(`WebSocket frame payload length exceeds supported limits`);o=Number(t),s+=8}let c=a?e.subarray(s,s+4):null;if(a){if(e.length<s+4)return null;s+=4}if(e.length<s+o)return null;let l=e.subarray(s,s+o),u=Buffer.alloc(l.length);if(a&&c)for(let e=0;e<l.length;e+=1)u[e]=l[e]^c[e%4];else l.copy(u);let d=ne(i);if(!d)throw Error(`Unsupported WebSocket opcode 0x${i.toString(16)}`);let f=null,p=null;return d===`close`&&u.length>=2&&(f=u.readUInt16BE(0),p=u.subarray(2).toString(`utf8`)),{frame:{type:d,fin:r,opcode:i,masked:a,data:u,closeCode:f,closeReason:p,receivedAt:Date.now()},bytesConsumed:s+o}}function X(e){for(let t of e.waiters)t();e.waiters.clear()}function ae(e,t){return new Promise(n=>{let r=()=>{clearTimeout(i),e.waiters.delete(r),n(!0)},i=setTimeout(()=>{e.waiters.delete(r),n(!1)},t);e.waiters.add(r)})}const oe={"3:1":`TLS 1.0`,"3:2":`TLS 1.1`,"3:3":`TLS 1.2`,"3:4":`TLS 1.3`},se={20:`change_cipher_spec`,21:`alert`,22:`handshake`,23:`application_data`,24:`heartbeat`},ce={156:`TLS_RSA_WITH_AES_128_GCM_SHA256`,157:`TLS_RSA_WITH_AES_256_GCM_SHA384`,52392:`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,52393:`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,4865:`TLS_AES_128_GCM_SHA256`,4866:`TLS_AES_256_GCM_SHA384`,4867:`TLS_CHACHA20_POLY1305_SHA256`,4868:`TLS_AES_128_CCM_SHA256`,4869:`TLS_AES_128_CCM_8_SHA256`,49195:`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,49196:`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,49199:`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,49200:`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`},le={0:`server_name`,1:`max_fragment_length`,5:`status_request`,10:`supported_groups`,13:`signature_algorithms`,16:`application_layer_protocol_negotiation`,18:`signed_certificate_timestamp`,23:`record_size_limit`,27:`compress_certificate`,35:`session_ticket`,43:`supported_versions`,44:`cookie`,45:`psk_key_exchange_modes`,49:`post_handshake_auth`,51:`key_share`};function Z(e,t){return oe[`${e}:${t}`]??`0x${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}`}function Q(e){return se[e]??`unknown`}function ue(e){let t={cipherSuites:[],extensions:[]},n=e[0]!==void 0&&e[0]<25?4:0;if(e.length<n+38)return t;let r=n+34,i=e[r]??0,a=r+1+i;if(a+2>e.length)return t;let o=e.readUInt16BE(a);a+=2;let s=a+o;for(;a+2<=s;){let n=e.readUInt16BE(a);t.cipherSuites.push(ce[n]??`0x${n.toString(16).padStart(4,`0`)}`),a+=2}if(a=s+1,a<e.length){let t=e[a];t!==void 0&&(a+=1+t)}if(a+2<=e.length){let n=e.readUInt16BE(a);a+=2;let r=a+n;for(;a+4<=r;){let n=e.readUInt16BE(a),i=e.readUInt16BE(a+2);a+=4;let o=le[n]??`unknown(0x${n.toString(16)})`;if(t.extensions.push({type:n,name:o,length:i}),n===0&&a+2<=r){let n=a+2;if(n+3<=r&&e[n]===0){let i=e.readUInt16BE(n+1),a=n+3;a+i<=r&&(t.serverName=e.subarray(a,a+i).toString(`utf8`))}}a+=i}}return t}var de=class{keyLogExtractor;extensionInvoke;eventBus;tcpSessions=new Map;tlsSessions=new Map;websocketSessions=new Map;constructor(e=new a){this.keyLogExtractor=e}setExtensionInvoke(e){this.extensionInvoke=e}setEventBus(e){this.eventBus=e}getTcpSession(e){return this.tcpSessions.get(e)??null}getTlsSession(e){return this.tlsSessions.get(e)??null}getWebSocketSession(e){return this.websocketSessions.get(e)??null}parseWritePayload(e){let t=l(e,`dataHex`),n=l(e,`dataText`);if(!t&&!n)return{ok:!1,error:`dataHex or dataText is required`};if(t&&n)return{ok:!1,error:`dataHex and dataText are mutually exclusive`};if(t){let e=k(t);return A(e)?{ok:!0,data:Buffer.from(e,`hex`),inputEncoding:`hex`}:{ok:!1,error:`dataHex must be valid even-length hexadecimal data`}}return{ok:!0,data:Buffer.from(n??``,`utf8`),inputEncoding:`utf8`}}async writeBufferedSession(e,t){if(e.socket.destroyed||e.closed)return{ok:!1,error:`Session "${e.id}" is already closed`,sessionId:e.id,kind:e.kind,state:W(e)};let n=this.parseWritePayload(t);if(!n.ok)return{ok:!1,error:n.error,sessionId:e.id,kind:e.kind};let r=f(t,`timeoutMs`)??5e3;return!Number.isFinite(r)||r<=0?{ok:!1,error:`timeoutMs must be a positive number`}:new Promise(t=>{let i=!1,a=n=>{i||(i=!0,clearTimeout(o),e.socket.off(`error`,s),t(n))},o=setTimeout(()=>{a({ok:!1,error:`write timed out`,sessionId:e.id,kind:e.kind,state:W(e)})},r),s=t=>{a({ok:!1,error:t.message,sessionId:e.id,kind:e.kind,state:W(e)})};e.socket.once(`error`,s),e.socket.write(n.data,()=>{e.kind===`tcp`?this.eventBus?.emit(`tcp:session_written`,{sessionId:e.id,byteLength:n.data.length,timestamp:new Date().toISOString()}):this.eventBus?.emit(`tls:session_written`,{sessionId:e.id,byteLength:n.data.length,timestamp:new Date().toISOString()}),a({ok:!0,sessionId:e.id,kind:e.kind,inputEncoding:n.inputEncoding,bytesWritten:n.data.length,transport:U(e.socket),state:W(e)})})})}async readBufferedSessionUntil(e,t){let n=l(t,`delimiterHex`),r=l(t,`delimiterText`);if(n&&r)return{ok:!1,error:`delimiterHex and delimiterText are mutually exclusive`};let i=null;if(n){let e=k(n);if(!A(e))return{ok:!1,error:`delimiterHex must be valid even-length hexadecimal data`};i=Buffer.from(e,`hex`)}else r!==void 0&&(i=Buffer.from(r,`utf8`));if(i&&i.length===0)return{ok:!1,error:`delimiter must not be empty`};let a=p(t,`includeDelimiter`)??!0,o=f(t,`maxBytes`),s=o===void 0?void 0:Math.trunc(o);if(s!==void 0&&(!Number.isFinite(s)||s<=0))return{ok:!1,error:`maxBytes must be a positive integer when provided`};if(!i&&s===void 0)return{ok:!1,error:`delimiterHex, delimiterText, or maxBytes is required`};let c=f(t,`timeoutMs`)??5e3;if(!Number.isFinite(c)||c<=0)return{ok:!1,error:`timeoutMs must be a positive number`};if(e.activeRead)return{ok:!1,error:`Session "${e.id}" already has a pending read`,sessionId:e.id,kind:e.kind,state:W(e)};e.activeRead=!0;let u=Date.now();try{for(;;){let t=te(e,i,a,s);if(t)return e.kind===`tcp`?this.eventBus?.emit(`tcp:session_read`,{sessionId:e.id,byteLength:t.data.length,matched:t.matchedDelimiter,timestamp:new Date().toISOString()}):this.eventBus?.emit(`tls:session_read`,{sessionId:e.id,byteLength:t.data.length,matched:t.matchedDelimiter,timestamp:new Date().toISOString()}),{ok:!0,sessionId:e.id,kind:e.kind,bytesRead:t.data.length,matchedDelimiter:t.matchedDelimiter,stopReason:t.stopReason,delimiterHex:t.delimiterHex,dataHex:t.data.toString(`hex`).toUpperCase(),dataText:t.data.toString(`utf8`),elapsedMs:Date.now()-u,state:W(e)};if(e.error)return{ok:!1,error:e.error,sessionId:e.id,kind:e.kind,state:W(e)};if(e.ended||e.closed)return{ok:!1,error:`socket closed before the requested read condition was satisfied`,sessionId:e.id,kind:e.kind,state:W(e)};let n=c-(Date.now()-u);if(n<=0||!await ee(e,n))return{ok:!1,error:`read timed out`,sessionId:e.id,kind:e.kind,state:W(e)}}}finally{e.activeRead=!1}}async closeBufferedSession(e,t,n,r){let i=t.get(e);if(!i)return{ok:!1,error:`Unknown ${n} sessionId "${e}"`};let a=p(r,`force`)??!1,o=f(r,`timeoutMs`)??1e3;if(!Number.isFinite(o)||o<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let s=i.buffer.length;return i.closed||i.socket.destroyed?(t.delete(e),{ok:!0,sessionId:e,kind:n,force:a,closed:!0,bufferedBytesDiscarded:s,state:W(i)}):new Promise(r=>{let c=!1,l=o=>{c||(c=!0,clearTimeout(f),i.socket.off(`close`,u),i.socket.off(`error`,d),t.delete(e),n===`tcp`?this.eventBus?.emit(`tcp:session_closed`,{sessionId:e,reason:i.error,timestamp:new Date().toISOString()}):this.eventBus?.emit(`tls:session_closed`,{sessionId:e,reason:i.error,timestamp:new Date().toISOString()}),r({ok:!0,sessionId:e,kind:n,force:a,closed:o,bufferedBytesDiscarded:s,state:W(i)}))},u=()=>l(!0),d=()=>l(i.socket.destroyed||i.closed),f=setTimeout(()=>{i.socket.destroy(),l(i.socket.destroyed||i.closed)},o);if(i.socket.once(`close`,u),i.socket.once(`error`,d),a){i.socket.destroy();return}i.socket.end()})}},fe=class extends de{async handleTlsKeylogEnable(e){return{enabled:!0,keyLogPath:await this.keyLogExtractor.enableKeyLog(),environmentVariable:`SSLKEYLOGFILE`}}async handleTlsKeylogDisable(e){let t=l(e,`path`)??null;return t?await this.keyLogExtractor.disableKeyLog():r(),{disabled:!0,previousPath:t??o()}}async handleTlsKeylogParse(e){let t=l(e,`path`)??null,n=this.keyLogExtractor.parseKeyLog(t??void 0),r=this.keyLogExtractor.summarizeKeyLog(t??void 0);return{path:t??this.keyLogExtractor.getKeyLogFilePath(),entries:n,summary:r}}async handleTlsDecryptPayload(e){let t=l(e,`encryptedHex`)??null,n=l(e,`keyHex`)??null,r=l(e,`nonceHex`)??null,i=l(e,`algorithm`)??`aes-256-gcm`,a=l(e,`authTagHex`)??null;if(!t||!n||!r)return{ok:!1,error:`encryptedHex, keyHex, and nonceHex are required`};let o=s(t,n,r,i,a??void 0);return{ok:!0,algorithm:i,decrypted:o,isFailed:o.startsWith(`DECRYPTION_FAILED:`)}}async handleTlsKeylogSummarize(e){let t=l(e,`content`)??null;return t?i(n(t)):(this.keyLogExtractor.parseKeyLog(),this.keyLogExtractor.summarizeKeyLog())}async handleTlsKeylogLookupSecret(e){let t=l(e,`clientRandom`)??null,n=l(e,`label`)??void 0;if(!t)return{ok:!1,error:`clientRandom is required`};let r=this.keyLogExtractor.lookupSecret(t);if(r)return{ok:!0,clientRandom:k(t),secret:r};let i=c(this.keyLogExtractor.parseKeyLog(),t,n);return{ok:i!==null,clientRandom:k(t),secret:i??null}}async handleTlsCertPinBypass(e){let t=l(e,`target`)??null;return t!==`android`&&t!==`ios`&&t!==`desktop`?{error:`target must be one of android, ios, or desktop`}:{bypassStrategy:{android:`hook-trust-manager`,ios:`replace-sec-trust-evaluation`,desktop:`patch-custom-verifier`}[t],affectedDomains:[`*`],instructions:{android:[`Inject a Frida script that overrides X509TrustManager checks.`,`Re-run the target flow after SSLKEYLOGFILE capture is enabled.`],ios:[`Hook SecTrustEvaluateWithError and return success for the target session.`,`Collect TLS keys after the app resumes the failing request.`],desktop:[`Patch the custom verifier callback or disable pin comparison in the client.`,`Capture a fresh handshake after the patched build starts.`]}[t]}}async handleParseHandshake(t){let n=l(t,`rawHex`)??null,r=t.decrypt===!0;if(!n)return e({success:!1,error:`rawHex is required`});let i=k(n);if(!/^(?:[0-9a-f]{2})+$/i.test(i))return e({success:!1,error:`Invalid hex payload`});let a=Buffer.from(i,`hex`);if(a.length<5)return e({success:!1,error:`TLS record is too short`});let o=a[0],s=a[1],c=a[2],u=a.readUInt16BE(3),d=a.subarray(5),f=o===22&&d.length>0&&d[0]===1?ue(d):void 0,p=r?(()=>{let e=this.keyLogExtractor.decryptPayload(i,this.keyLogExtractor.parseKeyLog());return e?e.subarray(0,16).toString(`hex`).toUpperCase():null})():void 0;return e({success:!0,record:{contentType:o,contentTypeName:Q(o),version:Z(s,c),declaredLength:u,actualLength:d.length},handshake:{version:Z(s,c),contentType:Q(o),...f?{type:`client_hello`,serverName:f.serverName,cipherSuites:f.cipherSuites,extensions:f.extensions}:{cipherSuite:[],extensions:[]}},sni:f?.serverName?{serverName:f.serverName}:void 0,...p===void 0?{}:{decryptedPreviewHex:p}})}async handleKeyLogEnable(n){let r=l(n,`filePath`)??`/tmp/sslkeylog.log`;return t(r),this.eventBus?.emit(`tls:keylog_started`,{filePath:r,timestamp:new Date().toISOString()}),e({success:!0,filePath:r,currentFilePath:o()})}async handleCipherSuites(t){let n=l(t,`filter`)??null,r=[`TLS_AES_128_GCM_SHA256`,`TLS_AES_256_GCM_SHA384`,`TLS_CHACHA20_POLY1305_SHA256`,`TLS_AES_128_CCM_SHA256`,`TLS_AES_128_CCM_8_SHA256`,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`TLS_RSA_WITH_AES_256_GCM_SHA384`],i=n?r.filter(e=>e.includes(n)):r;return e({success:!0,filter:n,total:i.length,suites:i})}async handleParseCertificate(t){let n=l(t,`rawHex`)??null;if(!n)return e({success:!1,error:`rawHex is required`});let r=V(n);return e({success:!0,certificateCount:r.length,fingerprints:r.map(e=>({sha256:e.sha256,length:e.length}))})}};const $=[`TLSv1`,`TLSv1.1`,`TLSv1.2`,`TLSv1.3`];var pe=class extends fe{async handleTlsProbeEndpoint(e){let t=l(e,`host`)?.trim()??null;if(!t)return{ok:!1,error:`host is required`};let n=f(e,`port`)??443;if(!Number.isInteger(n)||n<1||n>65535)return{ok:!1,error:`port must be an integer between 1 and 65535`};let r=f(e,`timeoutMs`)??5e3;if(!Number.isFinite(r)||r<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let i=p(e,`allowInvalidCertificates`)??!1,a=p(e,`skipHostnameCheck`)??!1,o=l(e,`servername`)?.trim()??null,s=[...new Set(d(e,`alpnProtocols`).map(e=>e.trim()))].filter(e=>e.length>0),c,m;try{c=u(e,`minVersion`,D),m=u(e,`maxVersion`,D)}catch(e){return{ok:!1,error:O(e)}}if(c&&m&&$.indexOf(c)>$.indexOf(m))return{ok:!1,error:`minVersion must not be greater than maxVersion`};let h=j(t);if(h)return h;let g=await F(e);if(!g.ok)return{ok:!1,error:g.error};let _=o??t,v=o??(C(t)===0?t:void 0),y=Date.now();return new Promise(e=>{let o=!1,l=E(P({host:t,port:n,servername:v,...c?{minVersion:c}:{},...m?{maxVersion:m}:{},...s.length>0?{ALPNProtocols:s}:{},...g.ca?{ca:g.ca}:{}},i)),u=t=>{o||(o=!0,clearTimeout(d),l.removeAllListeners(),l.destroy(),e(t))},d=setTimeout(()=>{this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!1,timestamp:new Date().toISOString()}),u({ok:!1,error:`TLS probe timed out`,target:{host:t,port:n,requestedServername:v??null,validationTarget:_},policy:{allowInvalidCertificates:i,skipHostnameCheck:a,timeoutMs:r,minVersion:c??null,maxVersion:m??null,alpnProtocols:s,customCa:{source:g.source,path:g.path,bytes:g.bytes}}})},r);l.once(`error`,e=>{this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!1,timestamp:new Date().toISOString()}),u({ok:!1,error:e.message,errorCode:e.code??null,target:{host:t,port:n,requestedServername:v??null,validationTarget:_},policy:{allowInvalidCertificates:i,skipHostnameCheck:a,timeoutMs:r,minVersion:c??null,maxVersion:m??null,alpnProtocols:s,customCa:{source:g.source,path:g.path,bytes:g.bytes}}})}),l.once(`secureConnect`,()=>{let e=Date.now()-y,o=l.getPeerCertificate(!0),d=L(o),f=d?z(o):[],p=f[0]??null,h=a||!d?void 0:T(_,o),b={checked:!a,target:a?null:_,matched:a?null:h===void 0,error:!a&&!d?`Peer certificate was not presented by the server`:h?.message??null},x=[l.authorized?`Certificate chain validated against the active trust store.`:`Certificate chain validation failed: ${l.authorizationError??`unknown_authority`}`,a?`Hostname validation was skipped by request.`:b.matched?`Hostname validation passed.`:`Hostname validation failed: ${b.error??`unknown_error`}`,!l.authorized&&i?`Policy allowed the probe to continue despite certificate trust failure.`:null].filter(e=>!!e),S=l.getCipher();this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!0,timestamp:new Date().toISOString()}),u({ok:!0,target:{host:t,port:n,requestedServername:v??null,validationTarget:_},policy:{allowInvalidCertificates:i,skipHostnameCheck:a,timeoutMs:r,minVersion:c??null,maxVersion:m??null,alpnProtocols:s,customCa:{source:g.source,path:g.path,bytes:g.bytes}},transport:{protocol:l.getProtocol()??null,alpnProtocol:N(l.alpnProtocol),cipher:{name:S.name,standardName:S.standardName,version:S.version},localAddress:l.localAddress??null,localPort:l.localPort??null,remoteAddress:l.remoteAddress??null,remotePort:l.remotePort??null,servernameSent:M(l.servername),sessionReused:l.isSessionReused()},authorization:{socketAuthorized:l.authorized,authorizationError:typeof l.authorizationError==`string`?l.authorizationError:l.authorizationError?.message??null,hostnameValidation:b,policyAllowed:(l.authorized||i)&&(a||b.matched===!0),reasons:x},certificates:{leaf:p,chain:f},timing:{handshakeMs:e}})})})}};const me=[`TLSv1`,`TLSv1.1`,`TLSv1.2`,`TLSv1.3`];var he=class extends pe{async handleTcpOpen(e){let t=l(e,`host`)??`127.0.0.1`,n=f(e,`port`);if(n===void 0||!Number.isInteger(n)||n<1||n>65535)return{ok:!1,error:`port must be an integer between 1 and 65535`};let r=f(e,`timeoutMs`)??5e3;if(!Number.isFinite(r)||r<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let i=p(e,`noDelay`)??!0;return j(t)||new Promise(e=>{let a=!1,o=new x,s=t=>{a||(a=!0,clearTimeout(c),o.off(`connect`,u),o.off(`error`,l),e(t))},c=setTimeout(()=>{o.destroy(),s({ok:!1,error:`TCP connect timed out`,target:{host:t,port:n}})},r),l=e=>{s({ok:!1,error:e.message,target:{host:t,port:n}})},u=()=>{o.setNoDelay(i);let e=H(`tcp`),r={id:e,kind:`tcp`,socket:o,host:t,port:n,createdAt:Date.now(),buffer:Buffer.alloc(0),ended:!1,closed:!1,error:null,waiters:new Set,activeRead:!1};K(r),this.tcpSessions.set(e,r),this.eventBus?.emit(`tcp:session_opened`,{sessionId:e,host:t,port:n,timestamp:new Date().toISOString()}),s({ok:!0,sessionId:e,kind:`tcp`,target:{host:t,port:n},createdAt:new Date(r.createdAt).toISOString(),transport:U(o),state:W(r)})};o.once(`connect`,u),o.once(`error`,l),o.connect(n,t)})}async handleTcpWrite(e){let t=l(e,`sessionId`)?.trim()??null;if(!t)return{ok:!1,error:`sessionId is required`};let n=this.getTcpSession(t);return n?this.writeBufferedSession(n,e):{ok:!1,error:`Unknown tcp sessionId "${t}"`}}async handleTcpReadUntil(e){let t=l(e,`sessionId`)?.trim()??null;if(!t)return{ok:!1,error:`sessionId is required`};let n=this.getTcpSession(t);return n?this.readBufferedSessionUntil(n,e):{ok:!1,error:`Unknown tcp sessionId "${t}"`}}async handleTcpClose(e){let t=l(e,`sessionId`)?.trim()??null;return t?this.closeBufferedSession(t,this.tcpSessions,`tcp`,e):{ok:!1,error:`sessionId is required`}}async handleTlsOpen(e){let t=l(e,`host`)?.trim()??null;if(!t)return{ok:!1,error:`host is required`};let n=f(e,`port`)??443;if(!Number.isInteger(n)||n<1||n>65535)return{ok:!1,error:`port must be an integer between 1 and 65535`};let r=f(e,`timeoutMs`)??5e3;if(!Number.isFinite(r)||r<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let i=p(e,`allowInvalidCertificates`)??!1,a=p(e,`skipHostnameCheck`)??!1,o=l(e,`servername`)?.trim()??null,s=[...new Set(d(e,`alpnProtocols`).map(e=>e.trim()))].filter(e=>e.length>0),c,m;try{c=u(e,`minVersion`,D),m=u(e,`maxVersion`,D)}catch(e){return{ok:!1,error:O(e)}}if(c&&m&&me.indexOf(c)>me.indexOf(m))return{ok:!1,error:`minVersion must not be greater than maxVersion`};let h=j(t);if(h)return h;let g=await F(e);if(!g.ok)return{ok:!1,error:g.error};let _={host:t,port:n,requestedServername:o??(C(t)===0?t:void 0)??null,validationTarget:o??t},v={allowInvalidCertificates:i,skipHostnameCheck:a,timeoutMs:r,minVersion:c??null,maxVersion:m??null,alpnProtocols:s,customCa:{source:g.source,path:g.path,bytes:g.bytes}},y=Date.now();return new Promise(e=>{let o=!1,l=E(P({host:t,port:n,servername:_.requestedServername??void 0,...c?{minVersion:c}:{},...m?{maxVersion:m}:{},...s.length>0?{ALPNProtocols:s}:{},...g.ca?{ca:g.ca}:{}},i)),u=t=>{o||(o=!0,clearTimeout(d),l.off(`error`,f),l.off(`secureConnect`,p),e(t))},d=setTimeout(()=>{l.destroy(),this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!1,timestamp:new Date().toISOString()}),u({ok:!1,error:`TLS open timed out`,target:_,policy:v})},r),f=e=>{this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!1,timestamp:new Date().toISOString()}),u({ok:!1,error:e.message,errorCode:e.code??null,target:_,policy:v})},p=()=>{let e=Date.now()-y,r=l.getPeerCertificate(!0),o=L(r),s=o?z(r):[],c=s[0]??null,d=a||!o?void 0:T(_.validationTarget,r),f={checked:!a,target:a?null:_.validationTarget,matched:a?null:d===void 0,error:!a&&!o?`Peer certificate was not presented by the server`:d?.message??null},p=[l.authorized?`Certificate chain validated against the active trust store.`:`Certificate chain validation failed: ${l.authorizationError??`unknown_authority`}`,a?`Hostname validation was skipped by request.`:f.matched?`Hostname validation passed.`:`Hostname validation failed: ${f.error??`unknown_error`}`,!l.authorized&&i?`Policy allowed the session to continue despite certificate trust failure.`:null].filter(e=>!!e),m=l.getCipher(),h={target:_,policy:v,transport:{protocol:l.getProtocol()??null,alpnProtocol:N(l.alpnProtocol),cipher:{name:m.name,standardName:m.standardName,version:m.version},localAddress:l.localAddress??null,localPort:l.localPort??null,remoteAddress:l.remoteAddress??null,remotePort:l.remotePort??null,servernameSent:M(l.servername),sessionReused:l.isSessionReused()},authorization:{socketAuthorized:l.authorized,authorizationError:typeof l.authorizationError==`string`?l.authorizationError:l.authorizationError?.message??null,hostnameValidation:f,policyAllowed:(l.authorized||i)&&(a||f.matched===!0),reasons:p},certificates:{leaf:c,chain:s}};if(!h.authorization.policyAllowed){l.destroy(),this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!1,timestamp:new Date().toISOString()}),u({ok:!1,error:`TLS session authorization failed`,...h,timing:{handshakeMs:e}});return}let g=H(`tls`),b={id:g,kind:`tls`,socket:l,host:t,port:n,createdAt:Date.now(),buffer:Buffer.alloc(0),ended:!1,closed:!1,error:null,waiters:new Set,activeRead:!1,metadata:h};K(b),this.tlsSessions.set(g,b),this.eventBus?.emit(`tls:session_opened`,{sessionId:g,host:t,port:n,timestamp:new Date().toISOString()}),this.eventBus?.emit(`tls:probe_completed`,{host:t,port:n,success:!0,timestamp:new Date().toISOString()}),u({ok:!0,sessionId:g,kind:`tls`,...h,timing:{handshakeMs:e},state:W(b)})};l.once(`error`,f),l.once(`secureConnect`,p)})}async handleTlsWrite(e){let t=l(e,`sessionId`)?.trim()??null;if(!t)return{ok:!1,error:`sessionId is required`};let n=this.getTlsSession(t);return n?this.writeBufferedSession(n,e):{ok:!1,error:`Unknown tls sessionId "${t}"`}}async handleTlsReadUntil(e){let t=l(e,`sessionId`)?.trim()??null;if(!t)return{ok:!1,error:`sessionId is required`};let n=this.getTlsSession(t);return n?this.readBufferedSessionUntil(n,e):{ok:!1,error:`Unknown tls sessionId "${t}"`}}async handleTlsClose(e){let t=l(e,`sessionId`)?.trim()??null;return t?this.closeBufferedSession(t,this.tlsSessions,`tls`,e):{ok:!1,error:`sessionId is required`}}},ge=class extends he{emitWebSocketEvent(e,t){this.eventBus?.emit(e,t)}attachWebSocketSession(e){let t=()=>{for(;e.parserBuffer.length>0;){let t;try{t=ie(e.parserBuffer)}catch(t){e.error=O(t),e.socket.destroy();break}if(!t)break;e.parserBuffer=e.parserBuffer.subarray(t.bytesConsumed);let n=t.frame;if(e.frames.push(n),n.type===`ping`&&!e.closeSent&&!e.socket.destroyed){let t=Y(`pong`,n.data);e.socket.write(t),this.emitWebSocketEvent(`websocket:session_written`,{sessionId:e.id,frameType:`pong`,byteLength:n.data.length,automatic:!0,timestamp:new Date().toISOString()})}n.type===`close`&&(e.closeReceived=!0,!e.closeSent&&!e.socket.destroyed&&(e.closeSent=!0,e.socket.write(Y(`close`,n.data,n.closeCode,n.closeReason)),this.emitWebSocketEvent(`websocket:session_written`,{sessionId:e.id,frameType:`close`,byteLength:n.data.length,automatic:!0,timestamp:new Date().toISOString()})))}X(e)};e.socket.on(`data`,n=>{e.parserBuffer=Buffer.concat([e.parserBuffer,n]),t()}),e.socket.on(`end`,()=>{e.ended=!0,X(e)}),e.socket.on(`close`,()=>{e.closed=!0,X(e)}),e.socket.on(`error`,t=>{e.error=t.message,X(e)}),t()}async readWebSocketFrame(e,t){let n=f(t,`timeoutMs`)??5e3;if(!Number.isFinite(n)||n<=0)return{ok:!1,error:`timeoutMs must be a positive number`};if(e.activeRead)return{ok:!1,error:`Session "${e.id}" already has a pending read`,sessionId:e.id,kind:e.kind,state:q(e)};e.activeRead=!0;let r=Date.now();try{for(;;){let t=e.frames.shift();if(t)return this.emitWebSocketEvent(`websocket:frame_read`,{sessionId:e.id,frameType:t.type,byteLength:t.data.length,timestamp:new Date().toISOString()}),{ok:!0,sessionId:e.id,kind:e.kind,scheme:e.scheme,frameType:t.type,fin:t.fin,opcode:t.opcode,masked:t.masked,byteLength:t.data.length,dataHex:t.data.toString(`hex`).toUpperCase(),dataText:t.type===`binary`?null:t.data.toString(`utf8`),closeCode:t.closeCode,closeReason:t.closeReason,elapsedMs:Date.now()-r,state:q(e)};if(e.error)return{ok:!1,error:e.error,sessionId:e.id,kind:e.kind,state:q(e)};if(e.closed||e.ended)return{ok:!1,error:`socket closed before a WebSocket frame was available`,sessionId:e.id,kind:e.kind,state:q(e)};let i=n-(Date.now()-r);if(i<=0||!await ae(e,i))return{ok:!1,error:`read timed out`,sessionId:e.id,kind:e.kind,state:q(e)}}}finally{e.activeRead=!1}}async sendWebSocketFrame(e,t){if(e.closed||e.socket.destroyed)return{ok:!1,error:`Session "${e.id}" is already closed`,sessionId:e.id,kind:e.kind,state:q(e)};let n=u(t,`frameType`,new Set([`text`,`binary`,`ping`,`pong`,`close`]));if(!n)return{ok:!1,error:`frameType is required`};let r=l(t,`dataHex`),i=l(t,`dataText`);if(r&&i)return{ok:!1,error:`dataHex and dataText are mutually exclusive`};let a=f(t,`timeoutMs`)??5e3;if(!Number.isFinite(a)||a<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let o=Buffer.alloc(0);if(r){let e=k(r);if(!A(e))return{ok:!1,error:`dataHex must be valid even-length hexadecimal data`};o=Buffer.from(e,`hex`)}else i!==void 0&&(o=Buffer.from(i,`utf8`));let s=null,c=null;if(n===`close`){let n=f(t,`closeCode`);if(n!==void 0){if(!Number.isInteger(n)||n<1e3||n>4999)return{ok:!1,error:`closeCode must be an integer between 1000 and 4999`};s=n}if(c=l(t,`closeReason`)??null,r||i)return{ok:!1,error:`close frames use closeCode/closeReason instead of dataHex/dataText`};e.closeSent=!0}if(n===`text`&&r)return{ok:!1,error:`text frames require UTF-8 dataText instead of dataHex`};let d=Y(n,o,s,c);return new Promise(t=>{let r=!1,i=n=>{r||(r=!0,clearTimeout(l),e.socket.off(`error`,u),t(n))},l=setTimeout(()=>{i({ok:!1,error:`write timed out`,sessionId:e.id,kind:e.kind,state:q(e)})},a),u=t=>{i({ok:!1,error:t.message,sessionId:e.id,kind:e.kind,state:q(e)})};e.socket.once(`error`,u),e.socket.write(d,()=>{this.emitWebSocketEvent(`websocket:session_written`,{sessionId:e.id,frameType:n,byteLength:n===`close`?c?Buffer.byteLength(c)+2:s?2:0:o.length,automatic:!1,timestamp:new Date().toISOString()}),i({ok:!0,sessionId:e.id,kind:e.kind,scheme:e.scheme,frameType:n,bytesWritten:d.length,payloadBytes:n===`close`?c?Buffer.byteLength(c)+2:s?2:0:o.length,state:q(e)})})})}async closeWebSocketSession(e,t){let n=this.websocketSessions.get(e);if(!n)return{ok:!1,error:`Unknown websocket sessionId "${e}"`};let r=p(t,`force`)??!1,i=f(t,`timeoutMs`)??1e3;if(!Number.isFinite(i)||i<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let a=n.frames.length;if(n.closed||n.socket.destroyed)return this.websocketSessions.delete(e),{ok:!0,sessionId:e,kind:n.kind,force:r,closed:!0,queuedFramesDiscarded:a,state:q(n)};let o=null,s=f(t,`closeCode`);if(s!==void 0){if(!Number.isInteger(s)||s<1e3||s>4999)return{ok:!1,error:`closeCode must be an integer between 1000 and 4999`};o=s}let c=l(t,`closeReason`)??null;return new Promise(t=>{let s=!1,l=i=>{s||(s=!0,clearTimeout(f),n.socket.off(`close`,u),n.socket.off(`error`,d),this.websocketSessions.delete(e),this.emitWebSocketEvent(`websocket:session_closed`,{sessionId:e,reason:n.error,timestamp:new Date().toISOString()}),t({ok:!0,sessionId:e,kind:n.kind,force:r,closed:i,queuedFramesDiscarded:a,state:q(n)}))},u=()=>l(!0),d=()=>l(n.socket.destroyed||n.closed),f=setTimeout(()=>{n.socket.destroy(),l(n.socket.destroyed||n.closed)},i);if(n.socket.once(`close`,u),n.socket.once(`error`,d),r){n.socket.destroy();return}n.closeSent||(n.closeSent=!0,n.socket.write(Y(`close`,Buffer.alloc(0),o,c)),this.emitWebSocketEvent(`websocket:session_written`,{sessionId:e,frameType:`close`,byteLength:c?Buffer.byteLength(c)+2:o?2:0,automatic:!1,timestamp:new Date().toISOString()}))})}async handleWebSocketSendFrame(e){let t=l(e,`sessionId`)?.trim()??null;if(!t)return{ok:!1,error:`sessionId is required`};let n=this.getWebSocketSession(t);return n?this.sendWebSocketFrame(n,e):{ok:!1,error:`Unknown websocket sessionId "${t}"`}}async handleWebSocketReadFrame(e){let t=l(e,`sessionId`)?.trim()??null;if(!t)return{ok:!1,error:`sessionId is required`};let n=this.getWebSocketSession(t);return n?this.readWebSocketFrame(n,e):{ok:!1,error:`Unknown websocket sessionId "${t}"`}}async handleWebSocketClose(e){let t=l(e,`sessionId`)?.trim()??null;return t?this.closeWebSocketSession(t,e):{ok:!1,error:`sessionId is required`}}};const _e=[`TLSv1`,`TLSv1.1`,`TLSv1.2`,`TLSv1.3`];var ve=class extends ge{async handleWebSocketOpen(e){let t=l(e,`url`)?.trim()??null,n=l(e,`host`)?.trim()??null,r=l(e,`path`)?.trim()??null,i=f(e,`port`),a=l(e,`scheme`)?.trim()??null;if(t&&(n||r||i!==void 0||a))return{ok:!1,error:`url is mutually exclusive with explicit scheme/host/port/path inputs`};let o=`ws`,s=n,c=i??void 0,m=J(r),h;if(t){let e;try{e=new URL(t)}catch(e){return{ok:!1,error:`Invalid url: ${O(e)}`}}if(e.protocol!==`ws:`&&e.protocol!==`wss:`)return{ok:!1,error:`url must use ws:// or wss:// protocol`};o=e.protocol===`wss:`?`wss`:`ws`,s=e.hostname,c=e.port.length>0?Number(e.port):o===`wss`?443:80,m=J(`${e.pathname}${e.search}`),h=`${o}://${e.host}${m}`}else{if(!s)return{ok:!1,error:`host or url is required`};if(a){if(a!==`ws`&&a!==`wss`)return{ok:!1,error:`scheme must be ws or wss`};o=a}c??=o===`wss`?443:80;let e=c===(o===`wss`?443:80)?s:`${s}:${String(c)}`;h=`${o}://${e}${m}`}if(!s||!c||!Number.isInteger(c)||c<1||c>65535)return{ok:!1,error:`port must be an integer between 1 and 65535`};let g=f(e,`timeoutMs`)??5e3;if(!Number.isFinite(g)||g<=0)return{ok:!1,error:`timeoutMs must be a positive number`};let _=[...new Set(d(e,`subprotocols`).map(e=>e.trim()))].filter(e=>e.length>0),y=j(s);if(y)return y;let b=p(e,`allowInvalidCertificates`)??!1,S=p(e,`skipHostnameCheck`)??!1,w=l(e,`servername`)?.trim()??null,k=[...new Set(d(e,`alpnProtocols`).map(e=>e.trim()))].filter(e=>e.length>0),A,I;try{A=u(e,`minVersion`,D),I=u(e,`maxVersion`,D)}catch(e){return{ok:!1,error:O(e)}}if(A&&I&&_e.indexOf(A)>_e.indexOf(I))return{ok:!1,error:`minVersion must not be greater than maxVersion`};let R=o===`wss`?await F(e):{ok:!0,ca:void 0,source:null,path:null,bytes:null};if(!R.ok)return{ok:!1,error:R.error};let B={scheme:o,url:h,host:s,port:c,path:m,requestedServername:o===`wss`?w??(C(s)===0?s:void 0)??null:null,validationTarget:o===`wss`?w??s:null},V=v(16).toString(`base64`),W=re(V),G=Date.now();return new Promise(e=>{let t=!1,n=Buffer.alloc(0),r=null,i=null,a=null,l=o===`wss`?E(P({host:s,port:c,servername:B.requestedServername??void 0,...A?{minVersion:A}:{},...I?{maxVersion:I}:{},...k.length>0?{ALPNProtocols:k}:{},...R.ca?{ca:R.ca}:{}},b)):new x,u=n=>{t||(t=!0,clearTimeout(f),l.off(`error`,p),l.off(`connect`,v),l.off(`secureConnect`,y),l.off(`data`,C),e(n))},d=()=>{let e=c===(o===`wss`?443:80)?s:`${s}:${String(c)}`,t=[`GET ${m} HTTP/1.1`,`Host: ${e}`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Key: ${V}`,`Sec-WebSocket-Version: 13`];return _.length>0&&t.push(`Sec-WebSocket-Protocol: ${_.join(`, `)}`),t.push(``,``),Buffer.from(t.join(`\r
|
|
2
|
+
`),`utf8`)},f=setTimeout(()=>{l.destroy(),u({ok:!1,error:`WebSocket open timed out`,target:B})},g),p=e=>{u({ok:!1,error:e.message,errorCode:e.code??null,target:B})},h=()=>{l.write(d())},v=()=>{l instanceof x&&l.setNoDelay(!0),r={...U(l),protocol:null,alpnProtocol:null,servernameSent:null,sessionReused:null},h()},y=()=>{let e=l,t=e.getPeerCertificate(!0),n=L(t),o=n?z(t):[],s=o[0]??null,c=S||!n||!B.validationTarget?void 0:T(B.validationTarget,t),d={checked:!S,target:S?null:B.validationTarget,matched:S?null:c===void 0,error:!S&&!n?`Peer certificate was not presented by the server`:c?.message??null},f=[e.authorized?`Certificate chain validated against the active trust store.`:`Certificate chain validation failed: ${e.authorizationError??`unknown_authority`}`,S?`Hostname validation was skipped by request.`:d.matched?`Hostname validation passed.`:`Hostname validation failed: ${d.error??`unknown_error`}`,!e.authorized&&b?`Policy allowed the session to continue despite certificate trust failure.`:null].filter(e=>!!e);if(i={socketAuthorized:e.authorized,authorizationError:typeof e.authorizationError==`string`?e.authorizationError:e.authorizationError?.message??null,hostnameValidation:d,policyAllowed:(e.authorized||b)&&(S||d.matched===!0),reasons:f},a={leaf:s,chain:o},r={...U(e),protocol:e.getProtocol()??null,alpnProtocol:N(e.alpnProtocol),servernameSent:M(e.servername),sessionReused:e.isSessionReused()},!i.policyAllowed){e.destroy(),u({ok:!1,error:`WebSocket TLS authorization failed`,target:B,authorization:i,certificates:a});return}h()},C=e=>{n=Buffer.concat([n,e]);let t=n.indexOf(`\r
|
|
3
|
+
\r
|
|
4
|
+
`);if(t<0)return;let d=n.subarray(0,t).toString(`utf8`).split(`\r
|
|
5
|
+
`),f=d.shift()??``;if(!/^HTTP\/1\.1 101\b/.test(f)){l.destroy(),u({ok:!1,error:`Unexpected WebSocket upgrade response: ${f}`,target:B});return}let p=new Map;for(let e of d){let t=e.indexOf(`:`);if(t<=0)continue;let n=e.slice(0,t).trim().toLowerCase(),r=e.slice(t+1).trim();p.set(n,r)}let h=p.get(`upgrade`)?.toLowerCase()??``,g=p.get(`connection`)?.toLowerCase()??``,v=p.get(`sec-websocket-accept`)??null;if(h!==`websocket`){l.destroy(),u({ok:!1,error:`Upgrade header did not confirm websocket`,target:B});return}if(!g.split(`,`).map(e=>e.trim()).includes(`upgrade`)){l.destroy(),u({ok:!1,error:`Connection header did not confirm upgrade`,target:B});return}if(v!==W){l.destroy(),u({ok:!1,error:`sec-websocket-accept did not match the client key`,target:B});return}let y=p.get(`sec-websocket-protocol`)??null;if(y&&!_.includes(y)){l.destroy(),u({ok:!1,error:`Server selected unexpected subprotocol "${y}"`,target:B});return}let b=H(`websocket`),x={id:b,kind:`websocket`,scheme:o,socket:l,host:s,port:c,path:m,createdAt:Date.now(),parserBuffer:n.subarray(t+4),frames:[],ended:!1,closed:!1,error:null,waiters:new Set,activeRead:!1,closeSent:!1,closeReceived:!1,metadata:{target:B,handshake:{requestKey:V,acceptKey:W,responseAcceptKey:v,subprotocol:y},transport:r??{...U(l),protocol:null,alpnProtocol:null,servernameSent:null,sessionReused:null},authorization:i,certificates:a}};this.attachWebSocketSession(x),this.websocketSessions.set(b,x),this.emitWebSocketEvent(`websocket:session_opened`,{sessionId:b,scheme:o,host:s,port:c,path:m,timestamp:new Date().toISOString()}),u({ok:!0,sessionId:b,kind:x.kind,scheme:o,target:B,handshake:x.metadata.handshake,transport:x.metadata.transport,authorization:x.metadata.authorization,certificates:x.metadata.certificates,timing:{handshakeMs:Date.now()-G},state:q(x)})};l.once(`error`,p),l.on(`data`,C),o===`wss`?l.once(`secureConnect`,y):(l.once(`connect`,v),l.connect(c,s))})}async handleBypassCertPinning(t){if(this.extensionInvoke)try{let n=await this.extensionInvoke(t);if(n)return e({success:!0,strategy:`frida-injection`,result:n})}catch{}return e({success:!0,strategy:`manual-bypass`,instructions:{android:[`Use Frida to hook X509TrustManager.checkServerTrusted and return without throwing.`,`Alternatively, use OkHttp CertificatePinner.Builder().add() with the target cert.`],ios:[`Hook SecTrustEvaluateWithError to always return true.`,`Or use SSLSetSessionOption to disable certificate validation.`],desktop:[`Set NODE_TLS_REJECT_UNAUTHORIZED=0 for Node.js targets.`,`Or patch the certificate comparison function in the HTTP client.`]},args:t})}},ye=class extends ve{async handleRawTcpSend(e){let t=l(e,`host`)??`127.0.0.1`,n=f(e,`port`);if(n===void 0||n<1||n>65535)return{ok:!1,error:`port must be a number between 1 and 65535`};let r=j(t);if(r)return r;let i=l(e,`dataHex`),a=l(e,`dataText`);if(!i&&!a)return{ok:!1,error:`dataHex or dataText is required`};let o=i?Buffer.from(k(i),`hex`):Buffer.from(a??``,`utf8`),s=f(e,`timeout`)??5e3;return new Promise(e=>{let r=new x,i=setTimeout(()=>{r.destroy(),e({ok:!1,error:`Connection timed out`})},s);r.on(`connect`,()=>{r.write(o,()=>{r.end()})}),r.on(`data`,a=>{clearTimeout(i),e({ok:!0,host:t,port:n,sentBytes:o.length,responseHex:a.toString(`hex`).toUpperCase(),responseText:a.toString(`utf8`)}),r.destroy()}),r.on(`error`,t=>{clearTimeout(i),e({ok:!1,error:t.message})}),r.connect(n,t)})}async handleRawTcpListen(e){let t=f(e,`port`);if(t===void 0||t<1||t>65535)return{ok:!1,error:`port must be a number between 1 and 65535`};let n=f(e,`timeout`)??1e4;return new Promise(e=>{let r=S(),i=setTimeout(()=>{r.close(),e({ok:!1,error:`Listen timed out - no connection received`})},n);r.on(`connection`,n=>{clearTimeout(i);let a=[];n.on(`data`,e=>{a.push(e)}),n.on(`end`,()=>{let n=Buffer.concat(a);r.close(),e({ok:!0,port:t,receivedBytes:n.length,dataHex:n.toString(`hex`).toUpperCase(),dataText:n.toString(`utf8`)})}),n.on(`error`,t=>{clearTimeout(i),r.close(),e({ok:!1,error:t.message})})}),r.on(`error`,t=>{clearTimeout(i),e({ok:!1,error:t.message})}),r.listen(t,`127.0.0.1`)})}async handleRawUdpSend(e){let t=l(e,`host`)??`127.0.0.1`,n=f(e,`port`);if(n===void 0||n<1||n>65535)return{ok:!1,error:`port must be a number between 1 and 65535`};let r=j(t);if(r)return r;let i=l(e,`dataHex`),a=l(e,`dataText`);if(!i&&!a)return{ok:!1,error:`dataHex or dataText is required`};let o=i?Buffer.from(k(i),`hex`):Buffer.from(a??``,`utf8`),s=f(e,`timeout`)??5e3;return new Promise(e=>{let r=w(`udp4`),i=setTimeout(()=>{r.close(),e({ok:!1,error:`UDP response timed out`})},s);r.on(`message`,a=>{clearTimeout(i),r.close(),e({ok:!0,host:t,port:n,sentBytes:o.length,responseHex:a.toString(`hex`).toUpperCase(),responseText:a.toString(`utf8`)})}),r.on(`error`,t=>{clearTimeout(i),r.close(),e({ok:!1,error:t.message})}),r.send(o,0,o.length,n,t)})}async handleRawUdpListen(e){let t=f(e,`port`);if(t===void 0||t<1||t>65535)return{ok:!1,error:`port must be a number between 1 and 65535`};let n=f(e,`timeout`)??1e4;return new Promise(e=>{let r=w(`udp4`),i=setTimeout(()=>{r.close(),e({ok:!1,error:`UDP listen timed out`})},n);r.on(`message`,(n,a)=>{clearTimeout(i),r.close(),e({ok:!0,localPort:t,receivedBytes:n.length,from:a,dataHex:n.toString(`hex`).toUpperCase(),dataText:n.toString(`utf8`)})}),r.on(`error`,t=>{clearTimeout(i),r.close(),e({ok:!1,error:t.message})}),r.bind(t,`127.0.0.1`)})}},be=class extends ye{};export{be as BoringsslInspectorHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e}from"./parse-args-Cuk7-xUt.mjs";function t(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}var n=class{sessionManager;deps;constructor(e,t={}){this.sessionManager=e,this.deps=t}async handleSessionDispatch(n){let r=e(n,`action`);switch(r){case`create`:return this.handleSessionCreate(n);case`list`:return this.handleSessionList(n);case`destroy`:return this.handleSessionDestroy(n);case`status`:return this.handleSessionStatus(n);default:return t({success:!1,error:`Unknown action: ${r}. Valid: create, list, destroy, status`})}}async handleOperationDispatch(n){let r=e(n,`action`);switch(r){case`register`:return this.handleOperationRegister(n);case`list`:return this.handleOperationList(n);default:return t({success:!1,error:`Unknown action: ${r}. Valid: register, list`})}}async handleArtifactDispatch(n){let r=e(n,`action`);switch(r){case`record`:return this.handleArtifactRecord(n);case`query`:return this.handleArtifactQuery(n);default:return t({success:!1,error:`Unknown action: ${r}. Valid: record, query`})}}async handleSessionCreate(n){try{let r=e(n,`name`);return t({success:!0,session:this.sessionManager.createSession(r||void 0)})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleSessionList(e){try{let e=this.sessionManager.listSessions();return t({success:!0,totalSessions:e.length,sessions:e})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleSessionDestroy(n){try{let r=e(n,`sessionId`,``);return r?(this.sessionManager.destroySession(r),t({success:!0,sessionId:r,message:`Session destroyed`})):t({success:!1,error:`sessionId is required`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleSessionStatus(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});let i=this.sessionManager.getSession(r);return t(i?{success:!0,session:i,stats:this.sessionManager.getSessionStats(r)}:{success:!1,error:`Session "${r}" not found`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleOperationList(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});let i=this.sessionManager.getSessionOperations(r),a=e(n,`type`);return a&&(i=i.filter(e=>e.type===a)),t({success:!0,totalOperations:i.length,operations:i})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleOperationRegister(n){try{let r=e(n,`sessionId`,``),i=e(n,`type`,``),a=e(n,`target`,``),o=n.config&&typeof n.config==`object`&&!Array.isArray(n.config)?n.config:{};return t(r?i?a?{success:!0,operation:this.sessionManager.registerOperation(r,i,a,o)}:{success:!1,error:`target is required`}:{success:!1,error:`type is required`}:{success:!1,error:`sessionId is required`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleArtifactQuery(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});let i=e(n,`type`)||void 0,a=typeof n.limit==`number`?n.limit:50,o=this.sessionManager.getArtifacts(r,i);return a>0&&(o=o.slice(0,a)),t({success:!0,totalArtifacts:o.length,artifacts:o})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleArtifactRecord(n){try{let r=e(n,`operationId`,``),i=n.data&&typeof n.data==`object`&&!Array.isArray(n.data)?n.data:void 0;return t(r?i?{success:!0,artifact:this.sessionManager.recordArtifact(r,i)}:{success:!1,error:`data is required`}:{success:!1,error:`operationId is required`})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleHookPreset(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});if(!this.deps.hookPresetHandlers)return t({success:!1,error:`hookPresetHandlers is not available`});let i={...n};delete i.sessionId;let a=await this.sessionManager.applyHookPreset(r,this.deps.hookPresetHandlers,i);return t({success:a.payload.success!==!1&&a.operation.status===`completed`,operation:a.operation,artifacts:a.artifacts,result:a.payload})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}async handleNetworkReplay(n){try{let r=e(n,`sessionId`,``);if(!r)return t({success:!1,error:`sessionId is required`});if(!this.deps.advancedHandlers)return t({success:!1,error:`advancedHandlers is not available`});let i={...n};delete i.sessionId;let a=await this.sessionManager.replayNetworkRequest(r,this.deps.advancedHandlers,i);return t({success:a.payload.success!==!1&&a.operation.status===`completed`,operation:a.operation,artifacts:a.artifacts,result:a.payload})}catch(e){return t({success:!1,error:e instanceof Error?e.message:String(e)})}}};export{n as InstrumentationHandlers};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-B5xQuEa_.mjs";import{t as n}from"./PrerequisiteError-Bl3dK8XA.mjs";import{t as r}from"./TraceRecorder-Dd8jLXpi.mjs";import{n as i}from"./parse-args-Cuk7-xUt.mjs";import{t as a}from"./ResponseBuilder-B2lu4KEl.mjs";import{readFile as o,writeFile as s}from"node:fs/promises";const c=(e,t)=>typeof e==`boolean`?e:t,l=(e,t)=>{let n=typeof e==`number`&&Number.isFinite(e)?e:t.defaultValue;return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n},u=(e,t)=>{let n={};for(let r=0;r<e.length;r++)n[e[r]]=t[r];return n},d=e=>{try{return JSON.parse(e)}catch{return e}},f=e=>({timestamp:e.timestamp,wallTime:e.wallTime??null,monotonicTime:e.monotonicTime??null,category:e.category,eventType:e.eventType,data:typeof e.data==`string`?d(e.data):e.data,scriptId:e.scriptId,lineNumber:e.lineNumber,requestId:e.requestId??null,sequence:e.sequence??null}),p=e=>({requestId:e.requestId,url:e.url,method:e.method,resourceType:e.resourceType,requestHeaders:d(e.requestHeaders),requestPostDataPresent:e.requestPostData!==null,status:e.status,statusText:e.statusText,responseHeaders:d(e.responseHeaders),mimeType:e.mimeType,protocol:e.protocol,remoteAddress:e.remoteAddress,fromDiskCache:e.fromDiskCache,fromServiceWorker:e.fromServiceWorker,startedWallTime:e.startedWallTime,responseWallTime:e.responseWallTime,finishedWallTime:e.finishedWallTime,startedMonotonicTime:e.startedMonotonicTime,responseMonotonicTime:e.responseMonotonicTime,finishedMonotonicTime:e.finishedMonotonicTime,encodedDataLength:e.encodedDataLength,receivedDataLength:e.receivedDataLength,receivedEncodedDataLength:e.receivedEncodedDataLength,chunkCount:e.chunkCount,streamingEnabled:e.streamingEnabled,streamingSupported:e.streamingSupported,streamingError:e.streamingError,bodyCaptureState:e.bodyCaptureState,bodySize:e.bodySize,bodyBase64Encoded:e.bodyBase64Encoded,bodyTruncated:e.bodyTruncated,bodyArtifactPath:e.bodyArtifactPath,bodyError:e.bodyError,failed:e.failed,errorText:e.errorText}),m=e=>({sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonicTime,dataLength:e.dataLength,encodedDataLength:e.encodedDataLength,hasChunkData:e.chunkData!==null,chunkPreview:e.chunkData===null?null:`${e.chunkData.slice(0,120)}${e.chunkData.length>120?`...`:``}`,chunkIsBase64:e.chunkIsBase64}),h=async(e,t)=>{if(e.bodyCaptureState===`none`&&e.bodyInline===null&&e.bodyArtifactPath===null)return null;let n=await y(e);if(n===null)return{state:e.bodyCaptureState,error:e.bodyError??`Body content is not available`,truncated:e.bodyTruncated};let r=e.bodySize??n.length;return t.returnSummary||r>t.maxBodyBytes?{state:e.bodyCaptureState,summary:{size:r,sizeKB:(r/1024).toFixed(2),base64Encoded:e.bodyBase64Encoded,preview:`${n.slice(0,500)}${n.length>500?`...`:``}`,truncated:e.bodyTruncated||r>t.maxBodyBytes,reason:t.returnSummary?`Summary mode enabled`:`Response too large (${(r/1024).toFixed(2)} KB > ${(t.maxBodyBytes/1024).toFixed(2)} KB)`}}:{state:e.bodyCaptureState,body:n,base64Encoded:e.bodyBase64Encoded,size:r,sizeKB:(r/1024).toFixed(2),truncated:e.bodyTruncated,...e.bodyError?{warning:e.bodyError}:{}}},g=(e,t,n,r)=>e.query(`
|
|
2
|
+
SELECT
|
|
3
|
+
timestamp,
|
|
4
|
+
category,
|
|
5
|
+
event_type,
|
|
6
|
+
data,
|
|
7
|
+
script_id,
|
|
8
|
+
line_number,
|
|
9
|
+
wall_time,
|
|
10
|
+
monotonic_time,
|
|
11
|
+
request_id,
|
|
12
|
+
sequence
|
|
13
|
+
FROM events
|
|
14
|
+
WHERE ${t} >= ${n} AND ${t} <= ${r}
|
|
15
|
+
ORDER BY ${t} ASC, sequence ASC
|
|
16
|
+
`).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:e[3],scriptId:e[4]??null,lineNumber:e[5]??null,wallTime:e[6]??null,monotonicTime:e[7]??null,requestId:e[8]??null,sequence:e[9]??null})),_=(e,t)=>{let n=e.detailedData;return n?n.smartHandle(t,25600):t},v=(e,t)=>{if(t)return new r({dbPath:t});let n=e.getDB();if(!n)throw Error(`GRACEFUL: No active recording and no dbPath specified. Start a recording or provide a dbPath.`);return n.flush(),n},y=async e=>typeof e.bodyInline==`string`?e.bodyInline:e.bodyArtifactPath?o(e.bodyArtifactPath,`utf8`):null;function b(e,t=`balanced`){if(e.length===0)return{detail:t,totalEvents:0,timeRange:{start:0,end:0,durationMs:0},categories:[],keyMoments:t===`compact`?void 0:[]};let n=e.map(e=>e.timestamp),r=Math.min(...n),i=Math.max(...n),a=new Map;for(let t of e){let e=a.get(t.category);e||(e={count:0,first:t.timestamp,last:t.timestamp,types:new Map},a.set(t.category,e)),e.count++,e.first=Math.min(e.first,t.timestamp),e.last=Math.max(e.last,t.timestamp),e.types.set(t.eventType,(e.types.get(t.eventType)??0)+1)}let o=[...a.entries()].toSorted((e,t)=>t[1].count-e[1].count).map(([e,t])=>({category:e,count:t.count,firstTimestamp:t.first,lastTimestamp:t.last,topEventTypes:[...t.types.entries()].toSorted((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({type:e,count:t}))})),s={detail:t,totalEvents:e.length,timeRange:{start:r,end:i,durationMs:i-r},categories:o};return(t===`balanced`||t===`full`)&&(s.keyMoments=x(e)),s}function x(e){let t=[];for(let n of e)n.eventType===`Debugger.paused`?t.push({timestamp:n.timestamp,type:`breakpoint`,description:`Debugger paused${n.scriptId?` at script ${n.scriptId}`:``}${n.lineNumber?`:${n.lineNumber}`:``}`,data:n.data}):n.eventType===`Network.loadingFinished`?t.push({timestamp:n.timestamp,type:`network_complete`,description:`Network request completed`,data:n.data}):n.eventType===`Runtime.exceptionThrown`?t.push({timestamp:n.timestamp,type:`exception`,description:`Runtime exception thrown`,data:n.data}):(n.eventType===`Page.frameNavigated`||n.eventType===`Page.navigatedWithinDocument`)&&t.push({timestamp:n.timestamp,type:`navigation`,description:`Page navigation`,data:n.data});return t}function S(e){if(e.length===0)return{totalDeltas:0,uniqueAddresses:0,anomalies:[],topAddresses:[]};let t=new Map;for(let n of e)t.set(n.address,(t.get(n.address)??0)+1);let n=t.size,r=e.length,i=r/n,a=[...t.entries()].toSorted((e,t)=>t[1]-e[1]),o=a.slice(0,10).map(([e,t])=>({address:e,writeCount:t})),s=i*3;return{totalDeltas:r,uniqueAddresses:n,anomalies:a.filter(([,e])=>e>s).map(([e,t])=>({address:e,writeCount:t,description:`${t} writes (${(t/i).toFixed(1)}× average)`})),topAddresses:o}}var C=class{recorder;ctx;constructor(e,t){this.recorder=e,this.ctx=t}async handleTraceRecording(e){return i(e,`action`,new Set([`start`,`stop`]))===`stop`?this.handleStopTraceRecording():this.handleStartTraceRecording(e)}async handleStartTraceRecording(e){let t=e.cdpDomains,r=e.recordMemoryDeltas,i=e.recordResponseBodies,o=e.streamResponseChunks,s=e.networkBodyMaxBytes,c=e.networkInlineBodyBytes,l=this.ctx.eventBus;if(!l)throw new n(`EventBus not available on server context`);let u=null;try{if(this.ctx.collector){let e=await this.ctx.collector.getActivePage();typeof e.createCDPSession==`function`&&(u=await e.createCDPSession())}}catch{}let d=await this.recorder.start(l,u,{cdpDomains:t,recordMemoryDeltas:r??!0,ownsSession:u!==null,network:{recordResponseBodies:i,streamResponseChunks:o,maxBodyBytes:s,inlineBodyBytes:c}});return a.ok().merge({status:`recording`,sessionId:d.sessionId,dbPath:d.dbPath,network:{recordResponseBodies:i??!0,streamResponseChunks:o??!0,maxBodyBytes:s??10*1024*1024,inlineBodyBytes:c??256*1024},message:`Recording started. CDP session: ${u?`active`:`not available`}`}).json()}async handleStopTraceRecording(){let e=await this.recorder.stop(),t=e.stoppedAt?e.stoppedAt-e.startedAt:0,n=e.cleanupErrors??[],r=n.length>0?`stopped_with_errors`:`stopped`;return a.ok().merge({status:r,sessionId:e.sessionId,dbPath:e.dbPath,eventCount:e.eventCount,memoryDeltaCount:e.memoryDeltaCount,heapSnapshotCount:e.heapSnapshotCount,networkRequestCount:e.networkRequestCount??0,networkChunkCount:e.networkChunkCount??0,networkBodyCount:e.networkBodyCount??0,durationMs:t,...n.length>0?{cleanupErrors:n}:{},message:n.length>0?`Recording stopped with cleanup errors. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`:`Recording stopped. ${e.eventCount} events, ${e.memoryDeltaCount} memory deltas, ${e.heapSnapshotCount} heap snapshots, ${e.networkRequestCount??0} network requests, ${e.networkChunkCount??0} network chunks, ${e.networkBodyCount??0} response bodies recorded.`}).json()}async handleQueryTraceSql(t){let i=t.sql,o=t.dbPath;if(!i)throw new e(`VALIDATION`,`sql parameter is required`);let s,c=null;try{if(o)c=new r({dbPath:o}),s=c.query(i);else{let e=this.recorder.getDB();if(!e)throw new n(`No active recording and no dbPath specified. Start a recording or provide a dbPath.`);e.flush(),s=e.query(i)}return a.ok().merge({columns:s.columns,rows:s.rows,rowCount:s.rowCount}).json()}finally{c&&c.close()}}async handleSeekToTimestamp(t){let n=t.timestamp,r=t.dbPath,i=t.windowMs??100,o=t.timeDomain??`wall`;if(!n)throw new e(`VALIDATION`,`timestamp parameter is required`);let s=null;try{let e=v(this.recorder,r);r&&(s=e);let t=o===`monotonic`?`COALESCE(monotonic_time, timestamp)`:`timestamp`,c=o===`monotonic`?`COALESCE(finished_monotonic_time, response_monotonic_time, started_monotonic_time)`:`COALESCE(finished_wall_time, response_wall_time, started_wall_time)`,l=o===`wall`?e.getEventsByTimeRange(n-i,n+i):g(e,t,n-i,n+i),d=e.query(`SELECT * FROM events WHERE category = 'debugger' AND ${t} <= ${n} ORDER BY ${t} DESC, sequence DESC LIMIT 5`),p=o===`wall`?e.query(`SELECT m1.* FROM memory_deltas m1
|
|
17
|
+
INNER JOIN (SELECT address, MAX(timestamp) as max_ts FROM memory_deltas WHERE timestamp <= ${n} GROUP BY address) m2
|
|
18
|
+
ON m1.address = m2.address AND m1.timestamp = m2.max_ts
|
|
19
|
+
ORDER BY m1.address`):null,m=e.query(`SELECT * FROM network_resources
|
|
20
|
+
WHERE ${c} IS NOT NULL AND ${c} <= ${n}
|
|
21
|
+
ORDER BY ${c} DESC
|
|
22
|
+
LIMIT 20`);m.rowCount===0&&(m=e.query(`SELECT * FROM events
|
|
23
|
+
WHERE category = 'network'
|
|
24
|
+
AND event_type = 'Network.loadingFinished'
|
|
25
|
+
AND ${t} <= ${n}
|
|
26
|
+
ORDER BY ${t} DESC
|
|
27
|
+
LIMIT 20`));let h=o===`wall`?e.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE timestamp <= ${n} ORDER BY timestamp DESC LIMIT 1`):null;return a.ok().merge({seekTimestamp:n,timeDomain:o,windowMs:i,events:l.map(f),debuggerState:{recentEvents:d.rows.map(e=>u(d.columns,e))},memoryState:{addressValues:p?.rows.map(e=>u(p.columns,e))??[],...o===`monotonic`?{omittedReason:`Memory state is only indexed by wall-clock timestamps and is omitted for monotonic seeks.`}:{}},networkState:{completedRequests:m.rows.map(e=>u(m.columns,e))},nearestHeapSnapshot:h&&h.rows.length>0?u(h.columns,h.rows[0]):null,...o===`monotonic`?{nearestHeapSnapshotOmittedReason:`Heap snapshots are only indexed by wall-clock timestamps and are omitted for monotonic seeks.`}:{}}).json()}finally{s&&s.close()}}async handleGetTraceNetworkFlow(t){let n=typeof t.requestId==`string`?t.requestId:``,r=t.dbPath,i=c(t.includeBody,!0),o=c(t.includeChunks,!0),s=c(t.includeEvents,!0),u=l(t.chunkLimit,{defaultValue:200,min:1,max:5e3,integer:!0}),d=l(t.maxBodyBytes,{defaultValue:1e5,min:1024,max:50*1024*1024,integer:!0}),g=c(t.returnSummary,!1);if(!n)throw new e(`VALIDATION`,`requestId parameter is required`);let y=null;try{let t=v(this.recorder,r);r&&(y=t);let c=t.getNetworkResource(n);if(!c)throw new e(`NOT_FOUND`,`No recorded network flow found for requestId: ${n}`);let l=o?t.getNetworkChunks(n,u):[],b=s?t.getEventsByRequestId(n):[],x=i?await h(c,{maxBodyBytes:d,returnSummary:g}):null,S=_(this.ctx,{requestId:n,request:p(c),body:x,chunks:o?{total:c.chunkCount,returned:l.length,limit:u,hasMore:c.chunkCount>l.length,items:l.map(m)}:null,events:s?b.map(f):null});return a.ok().merge(S).json()}finally{y&&y.close()}}async handleDiffHeapSnapshots(t){let n=t.snapshotId1,r=t.snapshotId2,i=t.dbPath;if(!n||!r)throw new e(`VALIDATION`,`snapshotId1 and snapshotId2 are required`);let o=null;try{let t=v(this.recorder,i);i&&(o=t);let s=t.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${n}`),c=t.query(`SELECT id, timestamp, summary FROM heap_snapshots WHERE id = ${r}`);if(s.rowCount===0)throw new e(`NOT_FOUND`,`Snapshot with id ${n} not found`);if(c.rowCount===0)throw new e(`NOT_FOUND`,`Snapshot with id ${r} not found`);let l=u(s.columns,s.rows[0]),f=u(c.columns,c.rows[0]),p=d(l.summary),m=d(f.summary),h=p.objectCounts??{},g=m.objectCounts??{},_=new Set([...Object.keys(h),...Object.keys(g)]),y=[],b=[],x=[];for(let e of _){let t=h[e]??0,n=g[e]??0;t===0&&n>0?y.push({name:e,count:n}):t>0&&n===0?b.push({name:e,count:t}):t!==n&&x.push({name:e,countBefore:t,countAfter:n,delta:n-t})}x.sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta));let S=p.totalSize??0,C=m.totalSize??0;return a.ok().merge({snapshot1:{id:l.id,timestamp:l.timestamp,totalSize:S,nodeCount:p.nodeCount??0},snapshot2:{id:f.id,timestamp:f.timestamp,totalSize:C,nodeCount:m.nodeCount??0},diff:{added:y.slice(0,50),removed:b.slice(0,50),changed:x.slice(0,100),totalSizeDelta:C-S,addedCount:y.length,removedCount:b.length,changedCount:x.length}}).json()}finally{o&&o.close()}}async handleExportTrace(e){let n=e.dbPath,r=e.outputPath,i=null;try{let e=v(this.recorder,n);n&&(i=e);let o=e.query(`SELECT timestamp, category, event_type, data, script_id, line_number FROM events ORDER BY timestamp ASC, sequence ASC`),c=new Set([`Debugger.paused`]),l=new Set([`Debugger.resumed`]),u=o.rows.map(e=>{let t=e[0]*1e3,n=e[1],r=e[2],i=e[3],a=`i`;return c.has(r)?a=`B`:l.has(r)&&(a=`E`),{name:r,cat:n,ph:a,ts:t,pid:1,tid:1,args:d(i),...a===`i`?{s:`g`}:{}}}),f=r||(await t({category:`traces`,toolName:`trace_export`,ext:`json`})).absolutePath;return await s(f,JSON.stringify(u,null,2),`utf-8`),a.ok().merge({exportedPath:f,eventCount:u.length,format:`Chrome Trace Event JSON`,message:`Exported ${u.length} events to ${f}. Open in chrome://tracing or ui.perfetto.dev`}).json()}finally{i&&i.close()}}async handleSummarizeTrace(e){let t=e.detail??`balanced`,i=e.dbPath,o,s=!1;if(i)o=new r({dbPath:i}),s=!0;else if(this.recorder.getState()===`recording`){let e=this.recorder.getDB();if(!e)throw new n(`Active recording has no database`);o=e}else throw new n(`No trace database specified and no active recording`);try{let e=o.query(`SELECT timestamp, category, event_type, data, script_id, line_number, wall_time, monotonic_time, request_id, sequence FROM events ORDER BY timestamp, sequence`).rows.map(e=>({timestamp:e[0],category:e[1],eventType:e[2],data:typeof e[3]==`string`?d(e[3]):e[3],scriptId:e[4]??void 0,lineNumber:e[5]??void 0})),n=o.query(`SELECT timestamp, address, old_value, new_value, size, value_type FROM memory_deltas ORDER BY timestamp`).rows.map(e=>({timestamp:e[0],address:e[1],oldValue:e[2],newValue:e[3],size:e[4],valueType:e[5]})),r=o.query(`SELECT
|
|
28
|
+
COUNT(*) as requestCount,
|
|
29
|
+
COALESCE(SUM(chunk_count), 0) as chunkCount,
|
|
30
|
+
SUM(CASE WHEN body_capture_state IN ('inline', 'artifact', 'truncated') THEN 1 ELSE 0 END) as bodyCount
|
|
31
|
+
FROM network_resources`);return a.ok().merge({events:b(e,t),memory:S(n),network:r.rows.length>0?u(r.columns,r.rows[0]):{requestCount:0,chunkCount:0,bodyCount:0},metadata:{dbPath:i??`active recording`,generatedAt:new Date().toISOString()}}).json()}finally{s&&o.close()}}};export{C as TraceToolHandlers};
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import{Cn as e,Sn as t,xn as n}from"./constants-Cp6hBrrx.mjs";import{randomUUID as r}from"node:crypto";const i=n,a=e*1024*1024;let o=null;function s(){return o||=import(`quickjs-emscripten`).then(e=>e.getQuickJS()),o}function c(e,t){if(t==null)return e.undefined;switch(typeof t){case`string`:return e.newString(t);case`number`:return e.newNumber(t);case`boolean`:return t?e.true:e.false;case`object`:{if(Array.isArray(t)){let n=e.newArray();for(let r=0;r<t.length;r++){let i=c(e,t[r]);e.setProp(n,r,i),i.dispose()}return n}let n=e.newObject();for(let[r,i]of Object.entries(t)){let t=c(e,i);e.setProp(n,r,t),t.dispose()}return n}default:return e.newString(String(t))}}function l(e,t){switch(e.typeof(t)){case`undefined`:return;case`number`:return e.getNumber(t);case`string`:return e.getString(t);case`boolean`:return e.dump(t);case`object`:return e.dump(t);default:return e.dump(t)}}var u=class{bridge=null;setBridge(e){this.bridge=e}async execute(e,t={}){let n=t.timeoutMs??i,r=t.memoryLimitBytes??a,o=(await s()).newRuntime();o.setMemoryLimit(r);let c=Date.now(),u=!1;o.setInterruptHandler(()=>Date.now()-c>n?(u=!0,!0):!1);let d=o.newContext(),f=[];try{this.injectConsole(d,f),this.injectHelpers(d),this.bridge&&this.injectBridge(d,this.bridge,f),t.globals&&this.injectGlobals(d,t.globals);let n=d.evalCode(e,`sandbox-eval.js`);if(n.error){let e=d.dump(n.error);return n.error.dispose(),u?{ok:!1,error:`Execution timed out`,timedOut:!0,durationMs:Date.now()-c,logs:f}:{ok:!1,error:typeof e==`object`?JSON.stringify(e):String(e),timedOut:!1,durationMs:Date.now()-c,logs:f}}let r=l(d,n.value);return n.value.dispose(),{ok:!0,output:r,timedOut:!1,durationMs:Date.now()-c,logs:f}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e),timedOut:u,durationMs:Date.now()-c,logs:f}}finally{d.dispose(),o.dispose()}}async executeWithOrchestration(e,t,n={}){let r=n.maxBridgeCalls??10,i=Date.now(),a=[],o=[];n.bridgeAllowlist&&t.setAllowlist(n.bridgeAllowlist);let s={},c,l=0;for(;l<=r;){let r={...n.globals,__bridgeRound:l};l>0&&(r.__bridgeResults=s);let u=await this.executeOneRound(e,t,{...n,globals:r});if(a.push(...u.logs),!u.ok||u.timedOut)return{...u,logs:a,durationMs:Date.now()-i,bridgeCallCount:o.length,bridgeCalls:o};if(c=u.output,!t.hasPending())break;let d=t.drainPending(),f={};for(let e of d)try{let n=await t.call(e.toolName,e.args);f[e.id]=n,o.push({toolName:e.toolName,args:e.args,result:n})}catch(t){let n=t instanceof Error?t.message:String(t);f[e.id]={__error:!0,message:n},o.push({toolName:e.toolName,args:e.args,result:{__error:!0,message:n}})}s={...s,...f},l++}return{ok:!0,output:c,timedOut:!1,durationMs:Date.now()-i,logs:a,bridgeCallCount:o.length,bridgeCalls:o}}async executeOneRound(e,t,n={}){let r=n.timeoutMs??i,o=n.memoryLimitBytes??a,c=(await s()).newRuntime();c.setMemoryLimit(o);let u=Date.now(),d=!1;c.setInterruptHandler(()=>Date.now()-u>r?(d=!0,!0):!1);let f=c.newContext(),p=[];try{this.injectConsole(f,p),this.injectHelpers(f),this.injectBridgeForOrchestration(f,t,p),n.globals&&this.injectGlobals(f,n.globals);let r=f.evalCode(e,`sandbox-eval.js`);if(r.error){let e=f.dump(r.error);return r.error.dispose(),d?{ok:!1,error:`Execution timed out`,timedOut:!0,durationMs:Date.now()-u,logs:p}:{ok:!1,error:typeof e==`object`?JSON.stringify(e):String(e),timedOut:!1,durationMs:Date.now()-u,logs:p}}let i=l(f,r.value);return r.value.dispose(),{ok:!0,output:i,timedOut:!1,durationMs:Date.now()-u,logs:p}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e),timedOut:d,durationMs:Date.now()-u,logs:p}}finally{f.dispose(),c.dispose()}}injectConsole(e,t){let n=e.newObject(),r=e.newFunction(`log`,(...n)=>{let r=n.map(t=>{let n=l(e,t);return typeof n==`string`?n:JSON.stringify(n)});t.push(r.join(` `))});e.setProp(n,`log`,r),e.setProp(n,`warn`,r),e.setProp(n,`error`,r),e.setProp(e.global,`console`,n),r.dispose(),n.dispose()}injectGlobals(e,t){for(let[n,r]of Object.entries(t)){let t=c(e,r);e.setProp(e.global,n,t),t.dispose()}}injectHelpers(e){let t=e.evalCode(`
|
|
2
|
+
(function() {
|
|
3
|
+
var helpers = {};
|
|
4
|
+
|
|
5
|
+
// ── base64 ──
|
|
6
|
+
helpers.base64 = {
|
|
7
|
+
_chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
|
|
8
|
+
encode: function(str) {
|
|
9
|
+
var output = '';
|
|
10
|
+
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
|
|
11
|
+
var i = 0;
|
|
12
|
+
while (i < str.length) {
|
|
13
|
+
chr1 = str.charCodeAt(i++);
|
|
14
|
+
chr2 = str.charCodeAt(i++);
|
|
15
|
+
chr3 = str.charCodeAt(i++);
|
|
16
|
+
enc1 = chr1 >> 2;
|
|
17
|
+
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
|
|
18
|
+
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
|
|
19
|
+
enc4 = chr3 & 63;
|
|
20
|
+
if (isNaN(chr2)) { enc3 = enc4 = 64; }
|
|
21
|
+
else if (isNaN(chr3)) { enc4 = 64; }
|
|
22
|
+
output += this._chars.charAt(enc1) + this._chars.charAt(enc2) +
|
|
23
|
+
this._chars.charAt(enc3) + this._chars.charAt(enc4);
|
|
24
|
+
}
|
|
25
|
+
return output;
|
|
26
|
+
},
|
|
27
|
+
decode: function(str) {
|
|
28
|
+
var output = '';
|
|
29
|
+
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
|
|
30
|
+
var i = 0;
|
|
31
|
+
str = str.replace(/[^A-Za-z0-9+/=]/g, '');
|
|
32
|
+
while (i < str.length) {
|
|
33
|
+
enc1 = this._chars.indexOf(str.charAt(i++));
|
|
34
|
+
enc2 = this._chars.indexOf(str.charAt(i++));
|
|
35
|
+
enc3 = this._chars.indexOf(str.charAt(i++));
|
|
36
|
+
enc4 = this._chars.indexOf(str.charAt(i++));
|
|
37
|
+
chr1 = (enc1 << 2) | (enc2 >> 4);
|
|
38
|
+
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
|
|
39
|
+
chr3 = ((enc3 & 3) << 6) | enc4;
|
|
40
|
+
output += String.fromCharCode(chr1);
|
|
41
|
+
if (enc3 !== 64) output += String.fromCharCode(chr2);
|
|
42
|
+
if (enc4 !== 64) output += String.fromCharCode(chr3);
|
|
43
|
+
}
|
|
44
|
+
return output;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// ── hex ──
|
|
49
|
+
helpers.hex = {
|
|
50
|
+
encode: function(str) {
|
|
51
|
+
var hex = '';
|
|
52
|
+
for (var i = 0; i < str.length; i++) {
|
|
53
|
+
hex += ('0' + str.charCodeAt(i).toString(16)).slice(-2);
|
|
54
|
+
}
|
|
55
|
+
return hex;
|
|
56
|
+
},
|
|
57
|
+
decode: function(hex) {
|
|
58
|
+
var str = '';
|
|
59
|
+
for (var i = 0; i < hex.length; i += 2) {
|
|
60
|
+
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
|
|
61
|
+
}
|
|
62
|
+
return str;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// ── hash (simple djb2/fnv for in-sandbox use; NOT cryptographic!) ──
|
|
67
|
+
helpers.hash = {
|
|
68
|
+
djb2: function(str) {
|
|
69
|
+
var hash = 5381;
|
|
70
|
+
for (var i = 0; i < str.length; i++) {
|
|
71
|
+
hash = ((hash << 5) + hash) + str.charCodeAt(i);
|
|
72
|
+
hash = hash & hash; // Convert to 32-bit
|
|
73
|
+
}
|
|
74
|
+
return (hash >>> 0).toString(16);
|
|
75
|
+
},
|
|
76
|
+
fnv1a: function(str) {
|
|
77
|
+
var hash = 0x811c9dc5;
|
|
78
|
+
for (var i = 0; i < str.length; i++) {
|
|
79
|
+
hash ^= str.charCodeAt(i);
|
|
80
|
+
hash = Math.imul(hash, 0x01000193);
|
|
81
|
+
}
|
|
82
|
+
return (hash >>> 0).toString(16);
|
|
83
|
+
},
|
|
84
|
+
/** Simple MD5 — pure JS implementation */
|
|
85
|
+
md5: function(str) {
|
|
86
|
+
// Lightweight MD5 for sandbox use
|
|
87
|
+
function md5cycle(x, k) {
|
|
88
|
+
var a = x[0], b = x[1], c = x[2], d = x[3];
|
|
89
|
+
a = ff(a,b,c,d,k[0],7,0xd76aa478);
|
|
90
|
+
d=ff(d,a,b,c,k[1],12,0xe8c7b756);
|
|
91
|
+
c=ff(c,d,a,b,k[2],17,0x242070db);
|
|
92
|
+
b=ff(b,c,d,a,k[3],22,0xc1bdceee);
|
|
93
|
+
a=ff(a,b,c,d,k[4],7,0xf57c0faf);
|
|
94
|
+
d=ff(d,a,b,c,k[5],12,0x4787c62a);
|
|
95
|
+
c=ff(c,d,a,b,k[6],17,0xa8304613);
|
|
96
|
+
b=ff(b,c,d,a,k[7],22,0xfd469501);
|
|
97
|
+
a=ff(a,b,c,d,k[8],7,0x698098d8);
|
|
98
|
+
d=ff(d,a,b,c,k[9],12,0x8b44f7af);
|
|
99
|
+
c=ff(c,d,a,b,k[10],17,0xffff5bb1);
|
|
100
|
+
b=ff(b,c,d,a,k[11],22,0x895cd7be);
|
|
101
|
+
a=ff(a,b,c,d,k[12],7,0x6b901122);
|
|
102
|
+
d=ff(d,a,b,c,k[13],12,0xfd987193);
|
|
103
|
+
c=ff(c,d,a,b,k[14],17,0xa679438e);
|
|
104
|
+
b=ff(b,c,d,a,k[15],22,0x49b40821);
|
|
105
|
+
a=gg(a,b,c,d,k[1],5,0xf61e2562);
|
|
106
|
+
d=gg(d,a,b,c,k[6],9,0xc040b340);
|
|
107
|
+
c=gg(c,d,a,b,k[11],14,0x265e5a51);
|
|
108
|
+
b=gg(b,c,d,a,k[0],20,0xe9b6c7aa);
|
|
109
|
+
a=gg(a,b,c,d,k[5],5,0xd62f105d);
|
|
110
|
+
d=gg(d,a,b,c,k[10],9,0x02441453);
|
|
111
|
+
c=gg(c,d,a,b,k[15],14,0xd8a1e681);
|
|
112
|
+
b=gg(b,c,d,a,k[4],20,0xe7d3fbc8);
|
|
113
|
+
a=gg(a,b,c,d,k[9],5,0x21e1cde6);
|
|
114
|
+
d=gg(d,a,b,c,k[14],9,0xc33707d6);
|
|
115
|
+
c=gg(c,d,a,b,k[3],14,0xf4d50d87);
|
|
116
|
+
b=gg(b,c,d,a,k[8],20,0x455a14ed);
|
|
117
|
+
a=gg(a,b,c,d,k[13],5,0xa9e3e905);
|
|
118
|
+
d=gg(d,a,b,c,k[2],9,0xfcefa3f8);
|
|
119
|
+
c=gg(c,d,a,b,k[7],14,0x676f02d9);
|
|
120
|
+
b=gg(b,c,d,a,k[12],20,0x8d2a4c8a);
|
|
121
|
+
a=hh(a,b,c,d,k[5],4,0xfffa3942);
|
|
122
|
+
d=hh(d,a,b,c,k[8],11,0x8771f681);
|
|
123
|
+
c=hh(c,d,a,b,k[11],16,0x6d9d6122);
|
|
124
|
+
b=hh(b,c,d,a,k[14],23,0xfde5380c);
|
|
125
|
+
a=hh(a,b,c,d,k[1],4,0xa4beea44);
|
|
126
|
+
d=hh(d,a,b,c,k[4],11,0x4bdecfa9);
|
|
127
|
+
c=hh(c,d,a,b,k[7],16,0xf6bb4b60);
|
|
128
|
+
b=hh(b,c,d,a,k[10],23,0xbebfbc70);
|
|
129
|
+
a=hh(a,b,c,d,k[13],4,0x289b7ec6);
|
|
130
|
+
d=hh(d,a,b,c,k[0],11,0xeaa127fa);
|
|
131
|
+
c=hh(c,d,a,b,k[3],16,0xd4ef3085);
|
|
132
|
+
b=hh(b,c,d,a,k[6],23,0x04881d05);
|
|
133
|
+
a=hh(a,b,c,d,k[9],4,0xd9d4d039);
|
|
134
|
+
d=hh(d,a,b,c,k[12],11,0xe6db99e5);
|
|
135
|
+
c=hh(c,d,a,b,k[15],16,0x1fa27cf8);
|
|
136
|
+
b=hh(b,c,d,a,k[2],23,0xc4ac5665);
|
|
137
|
+
a=ii(a,b,c,d,k[0],6,0xf4292244);
|
|
138
|
+
d=ii(d,a,b,c,k[7],10,0x432aff97);
|
|
139
|
+
c=ii(c,d,a,b,k[14],15,0xab9423a7);
|
|
140
|
+
b=ii(b,c,d,a,k[5],21,0xfc93a039);
|
|
141
|
+
a=ii(a,b,c,d,k[12],6,0x655b59c3);
|
|
142
|
+
d=ii(d,a,b,c,k[3],10,0x8f0ccc92);
|
|
143
|
+
c=ii(c,d,a,b,k[10],15,0xffeff47d);
|
|
144
|
+
b=ii(b,c,d,a,k[1],21,0x85845dd1);
|
|
145
|
+
a=ii(a,b,c,d,k[8],6,0x6fa87e4f);
|
|
146
|
+
d=ii(d,a,b,c,k[15],10,0xfe2ce6e0);
|
|
147
|
+
c=ii(c,d,a,b,k[6],15,0xa3014314);
|
|
148
|
+
b=ii(b,c,d,a,k[13],21,0x4e0811a1);
|
|
149
|
+
a=ii(a,b,c,d,k[4],6,0xf7537e82);
|
|
150
|
+
d=ii(d,a,b,c,k[11],10,0xbd3af235);
|
|
151
|
+
c=ii(c,d,a,b,k[2],15,0x2ad7d2bb);
|
|
152
|
+
b=ii(b,c,d,a,k[9],21,0xeb86d391);
|
|
153
|
+
x[0]=add32(a,x[0]);x[1]=add32(b,x[1]);x[2]=add32(c,x[2]);x[3]=add32(d,x[3]);
|
|
154
|
+
}
|
|
155
|
+
function cmn(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32((a<<s)|(a>>>(32-s)),b)}
|
|
156
|
+
function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t)}
|
|
157
|
+
function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t)}
|
|
158
|
+
function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t)}
|
|
159
|
+
function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t)}
|
|
160
|
+
function add32(a,b){return(a+b)&0xFFFFFFFF}
|
|
161
|
+
|
|
162
|
+
var n = str.length;
|
|
163
|
+
var state = [1732584193,-271733879,-1732584194,271733878];
|
|
164
|
+
var tail = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
|
165
|
+
var i;
|
|
166
|
+
for (i = 64; i <= n; i += 64) {
|
|
167
|
+
var blk = [];
|
|
168
|
+
for (var j = i - 64; j < i; j += 4) {
|
|
169
|
+
blk.push(str.charCodeAt(j)|(str.charCodeAt(j+1)<<8)|(str.charCodeAt(j+2)<<16)|(str.charCodeAt(j+3)<<24));
|
|
170
|
+
}
|
|
171
|
+
md5cycle(state, blk);
|
|
172
|
+
}
|
|
173
|
+
for (var j = 0; j < 16; j++) tail[j] = 0;
|
|
174
|
+
for (i = i - 64; i < n; i++) {
|
|
175
|
+
tail[i>>2] |= str.charCodeAt(i) << ((i%4)<<3);
|
|
176
|
+
}
|
|
177
|
+
tail[i>>2] |= 0x80 << ((i%4)<<3);
|
|
178
|
+
if (i > 55) { md5cycle(state, tail); for (j = 0; j < 16; j++) tail[j] = 0; }
|
|
179
|
+
tail[14] = n * 8;
|
|
180
|
+
md5cycle(state, tail);
|
|
181
|
+
|
|
182
|
+
var hex_chr = '0123456789abcdef';
|
|
183
|
+
var s = '';
|
|
184
|
+
for (i = 0; i < 4; i++) {
|
|
185
|
+
for (j = 0; j < 4; j++) {
|
|
186
|
+
s += hex_chr.charAt((state[i] >> (j*8+4)) & 0x0F) + hex_chr.charAt((state[i] >> (j*8)) & 0x0F);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return s;
|
|
190
|
+
},
|
|
191
|
+
sha256: function(str) {
|
|
192
|
+
// Minimal pure-JS SHA-256
|
|
193
|
+
var K = [0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
|
|
194
|
+
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
|
|
195
|
+
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
|
|
196
|
+
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
|
|
197
|
+
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
|
|
198
|
+
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
|
|
199
|
+
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
|
|
200
|
+
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2];
|
|
201
|
+
function rr(x,n){return(x>>>n)|(x<<(32-n))}
|
|
202
|
+
var H=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];
|
|
203
|
+
var msg=[];
|
|
204
|
+
for(var i=0;i<str.length;i++)msg.push(str.charCodeAt(i));
|
|
205
|
+
msg.push(0x80);
|
|
206
|
+
var l=msg.length;
|
|
207
|
+
while(l%64!==56){msg.push(0);l++;}
|
|
208
|
+
var bits=str.length*8;
|
|
209
|
+
for(i=7;i>=0;i--)msg.push((bits>>>(i*8))&0xff);
|
|
210
|
+
for(var offset=0;offset<msg.length;offset+=64){
|
|
211
|
+
var W=[];
|
|
212
|
+
for(i=0;i<16;i++)W[i]=(msg[offset+i*4]<<24)|(msg[offset+i*4+1]<<16)|(msg[offset+i*4+2]<<8)|msg[offset+i*4+3];
|
|
213
|
+
for(i=16;i<64;i++){
|
|
214
|
+
var s0=rr(W[i-15],7)^rr(W[i-15],18)^(W[i-15]>>>3);
|
|
215
|
+
var s1=rr(W[i-2],17)^rr(W[i-2],19)^(W[i-2]>>>10);
|
|
216
|
+
W[i]=(W[i-16]+s0+W[i-7]+s1)|0;
|
|
217
|
+
}
|
|
218
|
+
var a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7];
|
|
219
|
+
for(i=0;i<64;i++){
|
|
220
|
+
var S1=rr(e,6)^rr(e,11)^rr(e,25);
|
|
221
|
+
var ch=(e&f)^((~e)&g);
|
|
222
|
+
var t1=(h+S1+ch+K[i]+W[i])|0;
|
|
223
|
+
var S0=rr(a,2)^rr(a,13)^rr(a,22);
|
|
224
|
+
var maj=(a&b)^(a&c)^(b&c);
|
|
225
|
+
var t2=(S0+maj)|0;
|
|
226
|
+
h=g;g=f;f=e;e=(d+t1)|0;d=c;c=b;b=a;a=(t1+t2)|0;
|
|
227
|
+
}
|
|
228
|
+
H[0]=(H[0]+a)|0;H[1]=(H[1]+b)|0;H[2]=(H[2]+c)|0;H[3]=(H[3]+d)|0;
|
|
229
|
+
H[4]=(H[4]+e)|0;H[5]=(H[5]+f)|0;H[6]=(H[6]+g)|0;H[7]=(H[7]+h)|0;
|
|
230
|
+
}
|
|
231
|
+
var hex='';
|
|
232
|
+
for(i=0;i<8;i++)for(var j=7;j>=0;j--)hex+='0123456789abcdef'.charAt((H[i]>>>(j*4))&0xf);
|
|
233
|
+
return hex;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
// ── json ──
|
|
238
|
+
helpers.json = {
|
|
239
|
+
safeParse: function(str) {
|
|
240
|
+
try { return { ok: true, value: JSON.parse(str) }; }
|
|
241
|
+
catch(e) { return { ok: false, error: e.message }; }
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// ── array ──
|
|
246
|
+
helpers.array = {
|
|
247
|
+
chunk: function(arr, size) {
|
|
248
|
+
var result = [];
|
|
249
|
+
for (var i = 0; i < arr.length; i += size) {
|
|
250
|
+
result.push(arr.slice(i, i + size));
|
|
251
|
+
}
|
|
252
|
+
return result;
|
|
253
|
+
},
|
|
254
|
+
flatten: function(arr) {
|
|
255
|
+
var result = [];
|
|
256
|
+
for (var i = 0; i < arr.length; i++) {
|
|
257
|
+
if (Array.isArray(arr[i])) {
|
|
258
|
+
result = result.concat(this.flatten(arr[i]));
|
|
259
|
+
} else {
|
|
260
|
+
result.push(arr[i]);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return result;
|
|
264
|
+
},
|
|
265
|
+
unique: function(arr) {
|
|
266
|
+
var seen = {};
|
|
267
|
+
var result = [];
|
|
268
|
+
for (var i = 0; i < arr.length; i++) {
|
|
269
|
+
var key = JSON.stringify(arr[i]);
|
|
270
|
+
if (!seen[key]) {
|
|
271
|
+
seen[key] = true;
|
|
272
|
+
result.push(arr[i]);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
// ── string ──
|
|
280
|
+
helpers.string = {
|
|
281
|
+
camelCase: function(s) {
|
|
282
|
+
return s.replace(/[-_\\s]+(\\w)/g, function(_, c) { return c.toUpperCase(); })
|
|
283
|
+
.replace(/^\\w/, function(c) { return c.toLowerCase(); });
|
|
284
|
+
},
|
|
285
|
+
snakeCase: function(s) {
|
|
286
|
+
return s.replace(/([A-Z])/g, '_$1').toLowerCase()
|
|
287
|
+
.replace(/[-\\s]+/g, '_')
|
|
288
|
+
.replace(/^_/, '');
|
|
289
|
+
},
|
|
290
|
+
truncate: function(s, len) {
|
|
291
|
+
if (s.length <= len) return s;
|
|
292
|
+
return s.slice(0, len - 3) + '...';
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
// Expose to global scope
|
|
297
|
+
globalThis.helpers = helpers;
|
|
298
|
+
})();
|
|
299
|
+
`,`sandbox-helpers.js`);t.error?(e.dump(t.error),t.error.dispose()):t.value.dispose()}injectBridge(e,t,n){let r=e.newObject(),i=e.newFunction(`call`,(t,r)=>{let i=e.getString(t),a=e.dump(r)??{};return n.push(`[mcp.call] ${i}(${JSON.stringify(a)})`),c(e,{pending:!0,tool:i})}),a=e.newFunction(`listTools`,()=>c(e,t.listAvailableTools()));e.setProp(r,`call`,i),e.setProp(r,`listTools`,a),e.setProp(e.global,`mcp`,r),i.dispose(),a.dispose(),r.dispose()}injectBridgeForOrchestration(e,t,n){let r=e.newObject(),i=e.newFunction(`call`,(r,i)=>{let a=e.getString(r),o=e.dump(i)??{};try{let r=t.enqueue(a,o);return n.push(`[mcp.call] enqueued ${a}(${JSON.stringify(o)}) → ${r}`),c(e,{__bridgeCall:!0,callId:r})}catch(t){let r=t instanceof Error?t.message:String(t);return n.push(`[mcp.call] rejected ${a}: ${r}`),c(e,{__bridgeCall:!1,error:r})}}),a=e.newFunction(`listTools`,()=>c(e,t.listAvailableTools()));e.setProp(r,`call`,i),e.setProp(r,`listTools`,a),e.setProp(e.global,`mcp`,r),i.dispose(),a.dispose(),r.dispose()}},d=class{ctx;allowlist=null;pendingCalls=[];constructor(e){this.ctx=e}setAllowlist(e){this.allowlist=e?new Set(e):null}enqueue(e,t={}){if(!(this.ctx.selectedTools?.map(e=>e.name)??[]).includes(e))throw Error(`Tool "${e}" is not a registered MCP tool`);if(this.allowlist&&!this.allowlist.has(e))throw Error(`Tool "${e}" is not in the sandbox allowlist`);let n=r().slice(0,8);return this.pendingCalls.push({id:n,toolName:e,args:t}),n}drainPending(){let e=[...this.pendingCalls];return this.pendingCalls.length=0,e}hasPending(){return this.pendingCalls.length>0}async call(e,t={}){if(this.allowlist&&!this.allowlist.has(e))throw Error(`Tool "${e}" is not in the sandbox allowlist`);if(!this.listAvailableTools().includes(e))throw Error(`Tool "${e}" is not a registered MCP tool`);let n=await this.ctx.executeToolWithTracking(e,t);if(n.content&&Array.isArray(n.content)){let e=[];for(let t of n.content)t.type===`text`&&e.push(t.text);let t=e.join(`
|
|
300
|
+
`);try{return JSON.parse(t)}catch{return t}}return n}listAvailableTools(){let e=this.ctx.selectedTools.map(e=>e.name);return this.allowlist?e.filter(e=>this.allowlist.has(e)):e}},f=class{store=new Map;set(e,t,n){let r=this.store.get(e);r||(r=new Map,this.store.set(e,r)),r.set(t,JSON.stringify(n))}get(e,t){let n=this.store.get(e);if(!n)return;let r=n.get(t);if(r!==void 0)try{return JSON.parse(r)}catch{return r}}getAll(e){let t=this.store.get(e);if(!t)return{};let n={};for(let[e,r]of t)try{n[e]=JSON.parse(r)}catch{n[e]=r}return n}keys(e){let t=this.store.get(e);return t?Array.from(t.keys()):[]}clear(e){this.store.delete(e)}clearAll(){this.store.clear()}};async function p(e,t,n={},r=2){let i=null,a=t;for(let o=0;o<=r;o++){if(i=await e.execute(a,n),i.ok||i.timedOut)return{...i,retryCount:o};o<r&&(a=`/* Previous error (attempt ${o+1}): ${i.error??`unknown error`} */\n${t}`)}return{...i,retryCount:r}}var m=class{ctx;scratchpad=new f;constructor(e){this.ctx=e}async handleExecuteSandboxScript(e){let n=e.code,r=e.sessionId??void 0,i=e.timeoutMs??void 0,a=e.autoCorrect??!1;if(!n||typeof n!=`string`)return{content:[{type:`text`,text:JSON.stringify({ok:!1,error:`code parameter is required`})}]};let o=new u,s=new d(this.ctx);o.setBridge(s);let c={};if(i!==void 0){let e=t;c.timeoutMs=Math.min(Math.max(1,Number.isFinite(i)?i:0),e)}if(r){c.sessionId=r;let e=this.scratchpad.getAll(r);c.globals={...c.globals,__scratchpad:e}}let l;if(l=a?await p(o,n,c):await o.execute(n,c),r&&l.ok&&l.output&&typeof l.output==`object`){let e=l.output;if(e.__scratchpad&&typeof e.__scratchpad==`object`)for(let[t,n]of Object.entries(e.__scratchpad))this.scratchpad.set(r,t,n)}return{content:[{type:`text`,text:[`**Status:** ${l.ok?`✓ Success`:`✗ Failed`}`,l.timedOut?`**Timed out:** yes`:``,`**Duration:** ${l.durationMs}ms`,l.logs.length>0?`**Console output:**\n\`\`\`\n${l.logs.join(`
|
|
301
|
+
`)}\n\`\`\``:``,l.output===void 0?``:`**Result:** ${JSON.stringify(l.output)}`,l.error?`**Error:** ${l.error}`:``].filter(Boolean).join(`
|
|
302
|
+
`)}]}}};export{m as SandboxToolHandlers};
|