@jshookmcp/jshook 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -661
- package/README.md +11 -3
- package/README.zh.md +11 -3
- package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
- package/dist/BrowserSessionCoordinator-QIt3tetp.mjs +1 -0
- package/dist/CodeInjector-Btj9upnf.mjs +1 -0
- package/dist/ConsoleMonitor-DIjN5Afa.mjs +306 -0
- package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
- package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
- package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
- package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
- package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
- package/dist/MCPServer.activation.ttl-CEGNBycZ.mjs +1 -0
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/MemoryController-DjtgiING.mjs +2 -0
- package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
- package/dist/MemoryScanner-Dxd657li.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
- package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
- package/dist/ProcessRegistry-D5y1yuP2.mjs +1 -0
- package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-nPXl_khE.mjs} +1 -1
- package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
- package/dist/RingBuffer-B6RTHmij.mjs +1 -0
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
- package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
- package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
- package/dist/ToolProbe-DQiREmNp.mjs +1 -0
- package/dist/ToolRegistry-eMZEBiR1.mjs +1 -0
- package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
- package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
- package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
- package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-DoP3MMHS.mjs} +1 -1
- package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
- package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
- package/dist/analysis-C-ln0Brh.mjs +6 -0
- package/dist/antidebug-CsnpOR9z.mjs +1 -0
- package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
- package/dist/{artifacts-B5xQuEa_.mjs → artifacts-D-4pSS_N.mjs} +1 -1
- package/dist/betterSqlite3-Bdo_ifuJ.mjs +1 -0
- package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
- package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
- package/dist/browser-BUaB25bk.mjs +11 -0
- package/dist/{handlers-pVNpaw4A.mjs → canvas-396ieNv5.mjs} +22 -22
- package/dist/collector-CB2syQEg.mjs +1 -0
- package/dist/constants-DMv3svps.mjs +2 -0
- package/dist/coordination-Dbohmj6D.mjs +1 -0
- package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
- package/dist/debugger-CLzkObIO.mjs +1 -0
- package/dist/{definitions-CCP9gphV.mjs → definitions-0hxnrDU72.mjs} +1 -1
- package/dist/definitions-B3a9QC2t.mjs +1 -0
- package/dist/{definitions-DtE0XLrT.mjs → definitions-BOvju5t2.mjs} +1 -1
- package/dist/definitions-CXj_cEVt.mjs +1 -0
- package/dist/definitions-Co6AvTjH.mjs +1 -0
- package/dist/{definitions-Dds_zrWx.mjs → definitions-Cv5r8xwq.mjs} +1 -1
- package/dist/definitions-DBYSxChX.mjs +1 -0
- package/dist/{definitions-DI9YXsJk.mjs → definitions-D_dTDX9B.mjs} +1 -1
- package/dist/{definitions-Dgrg7f3D.mjs → definitions-Db9t2ddh.mjs} +1 -1
- package/dist/{definitions-DZ8uKusP.mjs → definitions-DbN2CjI2.mjs} +1 -1
- package/dist/{definitions-jXPaVy4P.mjs → definitions-DlmmHmZc.mjs} +1 -1
- package/dist/definitions-DnYpoGig.mjs +1 -0
- package/dist/{definitions-CYFbewnd.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
- package/dist/{definitions-CuJRsJ6N.mjs → definitions-DuIPS8gq.mjs} +1 -1
- package/dist/{definitions-BbxOUiP-.mjs → definitions-DywfwPMb.mjs} +1 -1
- package/dist/definitions-EGmqr85H.mjs +1 -0
- package/dist/{definitions-LaYTuwQd.mjs → definitions-Fetw_Cge.mjs} +3 -3
- package/dist/{definitions-NoVp_9Pm.mjs → definitions-LdkeuOeA.mjs} +1 -1
- package/dist/{definitions-DJklW2sS.mjs → definitions-Ym8niHDb.mjs} +1 -1
- package/dist/{definitions-BGwNSkVm.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/{definitions-CIO9O-Sw.mjs → definitions-cnG6tj17.mjs} +1 -1
- package/dist/{encoding-DGcr6Aj_.mjs → encoding-B4xZWErf.mjs} +2 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
- package/dist/{factory-Cx_1LorX.mjs → factory-BxNdBiZa.mjs} +1 -1
- package/dist/{graphql-HLf3MS8H.mjs → graphql-GBWsZ9xC.mjs} +4 -4
- package/dist/{handlers-DW5AbYs5.mjs → handlers-5nzR8B0a.mjs} +3 -3
- package/dist/handlers-6iNsXOVT.mjs +7 -0
- package/dist/{handlers-BZoPla6E.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
- package/dist/{handlers-Dv_runVv.mjs → handlers-BbLxNbbT.mjs} +1 -1
- package/dist/{handlers-BP12ZsWc.mjs → handlers-BbS4hssc.mjs} +2 -2
- package/dist/{handlers-BggKiVx9.mjs → handlers-CIKOP4aI.mjs} +2 -2
- package/dist/handlers-CWKBBjai.mjs +1 -0
- package/dist/handlers-Cmb6SoRC.mjs +1 -0
- package/dist/handlers-CrJsKnEI.mjs +1 -0
- package/dist/{antidebug-BOTZH6-0.mjs → handlers-DB6xVVWq.mjs} +4 -4
- package/dist/{handlers-DmQzIc44.mjs → handlers-DOOCWUNR.mjs} +3 -3
- package/dist/{handlers-BLMa4X7l.mjs → handlers-Z_B5aVaU.mjs} +2 -2
- package/dist/handlers-gVscChvl.mjs +1 -0
- package/dist/handlers-xFvI9P_y.mjs +1 -0
- package/dist/handlers.impl-BsFTW6SD.mjs +1 -0
- package/dist/{hooks-DDKppogd.mjs → hooks-DPouiS7I.mjs} +9 -9
- package/dist/index.mjs +11 -15
- package/dist/macro-p8kuJVcm.mjs +2 -0
- package/dist/maintenance-DAqADb6Z.mjs +302 -0
- package/dist/manifest-4lmM6MZR.mjs +1 -0
- package/dist/{manifest-D610kxZr.mjs → manifest-AxaxRSt6.mjs} +2 -2
- package/dist/{manifest-CDeUZGUZ.mjs → manifest-BIqRE1Qz.mjs} +1 -1
- package/dist/{manifest-Dm0o3i2U.mjs → manifest-Box-jWfr.mjs} +1 -1
- package/dist/manifest-Bp33di0Q.mjs +1 -0
- package/dist/{manifest-CGq4NpqH2.mjs → manifest-BvRX4nRP.mjs} +1 -1
- package/dist/{manifest-yu2xiQqe.mjs → manifest-C6KoB1XE.mjs} +1 -1
- package/dist/manifest-C7TdXCWY.mjs +1 -0
- package/dist/manifest-CM-n64K0.mjs +1 -0
- package/dist/{manifest-DWUUWBz0.mjs → manifest-CUokxCUN.mjs} +1 -1
- package/dist/manifest-CWJS45iO.mjs +1 -0
- package/dist/{manifest-D44TaRJU.mjs → manifest-Cdxdgo-D.mjs} +1 -1
- package/dist/{manifest-DKUorv5M.mjs → manifest-Cf6SmamD.mjs} +1 -1
- package/dist/manifest-Cgxu2qdv.mjs +1 -0
- package/dist/manifest-CowGSURa2.mjs +1 -0
- package/dist/manifest-CsGIrh34.mjs +1 -0
- package/dist/manifest-CvDpVToN.mjs +1 -0
- package/dist/manifest-D8TL9RLE.mjs +1 -0
- package/dist/{manifest-C7qV1z7F.mjs → manifest-DIhtCBe6.mjs} +1 -1
- package/dist/{manifest-CeQmtQOY.mjs → manifest-DJbruNOg.mjs} +1 -1
- package/dist/manifest-DLGtZH-0.mjs +1 -0
- package/dist/manifest-DXHdPt2T.mjs +1 -0
- package/dist/{manifest-DMJlcsTR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
- package/dist/{manifest-C1nZkTkO.mjs → manifest-DzGoTS0R.mjs} +1 -1
- package/dist/manifest-G2H52LKz.mjs +131 -0
- package/dist/manifest-P0Futrgb.mjs +1 -0
- package/dist/{manifest-CDiCtaQT.mjs → manifest-Qw7xgvjv.mjs} +1 -1
- package/dist/{manifest-Dgh0uDW-.mjs → manifest-W3qvVrP2.mjs} +1 -1
- package/dist/manifest-dG6MuR1U.mjs +1 -0
- package/dist/manifest-nWXtgq5Y2.mjs +1 -0
- package/dist/{manifest-BPuE6oH2.mjs → manifest-vp1upSSq.mjs} +1 -1
- package/dist/modules-DO3jXCgj.mjs +333 -0
- package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
- package/dist/native/scripts/linux/enum-windows.sh +12 -12
- package/dist/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/native-g095qhpK.mjs +961 -0
- package/dist/network-Dvxm7eEI.mjs +7 -0
- package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
- package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-ngRrvF9e.mjs} +1 -1
- package/dist/platform-DjWbuiF8.mjs +93 -0
- package/dist/process-Dq5I-KZW.mjs +2 -0
- package/dist/proxy-DPNgM7TE.mjs +2 -0
- package/dist/{registry-DUHIPE-v.mjs → registry-xB8Wgmyj.mjs} +1 -1
- package/dist/renderer-pid-7jbTR8f5.mjs +1 -0
- package/dist/search-defaults-CJik67or.mjs +1 -0
- package/dist/server/plugin-api.d.mts +19 -36
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/sourcemap-DqEW15Ao.mjs +1 -0
- package/dist/streaming-Dbk4eStJ.mjs +1 -0
- package/dist/transform-D-peM3aO.mjs +103 -0
- package/dist/wasm-CZajRaad.mjs +174 -0
- package/dist/{webcrack-CsLLJIs9.mjs → webcrack-phEfVt5y.mjs} +3 -3
- package/dist/{workflow-CYIXtrWD.mjs → workflow-wkXb3x-U.mjs} +4 -4
- package/package.json +16 -15
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/CodeInjector-BlgyqTOk.mjs +0 -1
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
- package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
- package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
- package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
- package/dist/MemoryController-BaqstM5w.mjs +0 -2
- package/dist/MemoryScanner-BLYnMJy6.mjs +0 -1
- package/dist/NativeMemoryManager.impl-CI554XbY.mjs +0 -1
- package/dist/PageController-D9jVkH0i.mjs +0 -1
- package/dist/PointerChainEngine-5nF9eNlu.mjs +0 -1
- package/dist/PrerequisiteError-Bl3dK8XA.mjs +0 -1
- package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
- package/dist/ScriptManager-fgqiALgj.mjs +0 -7
- package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
- package/dist/ToolProbe-xsfALmN3.mjs +0 -1
- package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
- package/dist/ToolRouter.policy-CFHoN_Lw.mjs +0 -4
- package/dist/VersionDetector-DMoUWyNm.mjs +0 -9
- package/dist/analysis-BuR-NgX8.mjs +0 -5
- package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
- package/dist/binary-instrument-Cf9qqLlM.mjs +0 -7
- package/dist/browser-C4Le3xqA.mjs +0 -11
- package/dist/collector-CKO8RPK8.mjs +0 -1
- package/dist/constants-Cp6hBrrx.mjs +0 -1
- package/dist/coordination-BbijHEHH.mjs +0 -1
- package/dist/debugger-CRJq_krh.mjs +0 -1
- package/dist/definitions-BGobEDQa.mjs +0 -1
- package/dist/definitions-CdWEuIkI.mjs +0 -1
- package/dist/definitions-CoQFbggH.mjs +0 -1
- package/dist/definitions-OvGsfxdt.mjs +0 -1
- package/dist/ensure-browser-core-Buls24LQ.mjs +0 -1
- package/dist/flat-target-session-CO5g78k3.mjs +0 -1
- package/dist/handlers-D3iev8g1.mjs +0 -1
- package/dist/handlers-D49r1-1P.mjs +0 -1
- package/dist/handlers-DCE45Ww8.mjs +0 -2
- package/dist/handlers-De5u62Ga2.mjs +0 -1
- package/dist/handlers-DnJRGp7t.mjs +0 -302
- package/dist/handlers-S9Ws0IGy.mjs +0 -2
- package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
- package/dist/maintenance-CutEO84j.mjs +0 -1
- package/dist/manifest-BFGxlDRh.mjs +0 -123
- package/dist/manifest-BXry5N09.mjs +0 -1
- package/dist/manifest-BeP_zJGb2.mjs +0 -1
- package/dist/manifest-C0g67k6U.mjs +0 -1
- package/dist/manifest-CFn0359q2.mjs +0 -1
- package/dist/manifest-CJMGt7Qy.mjs +0 -1
- package/dist/manifest-CRIJq4Hs.mjs +0 -1
- package/dist/manifest-C_hEIjSx.mjs +0 -1
- package/dist/manifest-Cq0j7GZt.mjs +0 -1
- package/dist/manifest-CtPmHAdn.mjs +0 -1
- package/dist/manifest-Cx2IVMUY.mjs +0 -1
- package/dist/manifest-D16xPXro.mjs +0 -1
- package/dist/manifest-DC-SMF6b.mjs +0 -1
- package/dist/manifest-DD3rtxvV.mjs +0 -1
- package/dist/manifest-De-6Wf2R.mjs +0 -1
- package/dist/manifest-DsVh7Y4U.mjs +0 -1
- package/dist/manifest-DtEFSRaq.mjs +0 -1
- package/dist/manifest-H-EpAyZQ.mjs +0 -1
- package/dist/manifest-ais9Afrw.mjs +0 -1
- package/dist/manifest-tmb54wmA.mjs +0 -1
- package/dist/manifest-zrbrpKCC.mjs +0 -1
- package/dist/matchesWildcardPattern-BGqLSmEs.mjs +0 -1
- package/dist/modules-p-PUNv9r.mjs +0 -332
- package/dist/network-BjZ1Y-GB.mjs +0 -7
- package/dist/outputPaths-BonGThuc.mjs +0 -2
- package/dist/platform-C446Lf97.mjs +0 -93
- package/dist/playwright-cdp-fallback-BwVR-_T3.mjs +0 -1
- package/dist/process-C9f2A5zk.mjs +0 -962
- package/dist/proxy-CvRepxgV.mjs +0 -1
- package/dist/search-defaults-D2bY-rzH.mjs +0 -1
- package/dist/shared-state-board-Cyg-xh_k.mjs +0 -1
- package/dist/sourcemap-D6Q1UuAp.mjs +0 -1
- package/dist/streaming-CTX58tbb.mjs +0 -1
- package/dist/transform-Cv9P2vVD.mjs +0 -103
- package/dist/types-DtThH00r.mjs +0 -1
- package/dist/wasm-DaJa8J0V.mjs +0 -174
- /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
- /package/dist/{EventBus-DgciURGg.mjs → EventBus-Cm-t-B65.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
- /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
- /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
- /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
- /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
- /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
- /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-L1ax5EHS.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
- /package/dist/{concurrency-CcK46d0h.mjs → concurrency-Dehnw4JC.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
- /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
- /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
- /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
- /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
- /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
- /package/dist/{types-CuyefmGT.mjs → types-BzPBzmVB.mjs} +0 -0
package/README.md
CHANGED
|
@@ -40,11 +40,19 @@ No global install needed — add to your MCP client config and you're ready:
|
|
|
40
40
|
- ⚡ **Search-First Context Efficiency** — `search` profile ≈ 3K tokens vs `full` ≈ 40K+ tokens
|
|
41
41
|
- 🎯 **Progressive Tiers** — `search` → `workflow` → `full`, activate on demand
|
|
42
42
|
- 🌐 **Full-Stack Browser Automation** — Chromium/Camoufox + CDP + anti-detection + CAPTCHA handling
|
|
43
|
+
- 🔁 **Runtime Recovery and Session Isolation** — HTTP sessions restore activated domains, browser attach state, coverage state, and isolate browser-side session state per client
|
|
44
|
+
- 🧭 **Schema-First Meta Tools** — `describe_tool`, validated `call_tool`, and `coverage_report` reduce parameter errors and make tool coverage visible
|
|
43
45
|
- 📡 **Network Interception** — HTTP/2 frame building, MiTM capture, GraphQL, Burp Suite bridge
|
|
44
46
|
- 🛠️ **Reverse Engineering Toolchain** — WASM disassembly, binary analysis, Frida, Ghidra/IDA bridges
|
|
45
47
|
- 🧰 **Process & Memory Forensics** — Native FFI scanning, hardware breakpoints, PE introspection
|
|
46
48
|
- 🧩 **Dynamic Extensibility** — Hot-reload plugins, declarative workflows, auto-discovered domains
|
|
47
49
|
|
|
50
|
+
## Recent Runtime Notes
|
|
51
|
+
|
|
52
|
+
- HTTP transport now multiplexes independent MCP sessions and restores runtime state after reconnects.
|
|
53
|
+
- `proxy_start` auto-generates a local HTTPS interception CA when needed.
|
|
54
|
+
- Browser CAPTCHA solving is now explicit-input driven: pass `taskKind`, `siteKey`, `imageBase64`, `callbackName`, and `responseSelector` as needed. Built-in widget/page signature probing is intentionally not used.
|
|
55
|
+
|
|
48
56
|
## Architecture
|
|
49
57
|
|
|
50
58
|
- **Runtime Registry** — Domains auto-discovered via `manifest.ts`; add a domain by creating one file
|
|
@@ -57,9 +65,9 @@ No global install needed — add to your MCP client config and you're ready:
|
|
|
57
65
|
The built-in surface below is generated from the runtime registry and checked in CI.
|
|
58
66
|
|
|
59
67
|
<!-- metadata-sync:start -->
|
|
60
|
-
- Package version: `0.3.
|
|
61
|
-
- Built-in Tools: `
|
|
62
|
-
- Domains: `adb-bridge`, `
|
|
68
|
+
- Package version: `0.3.3`
|
|
69
|
+
- Built-in Tools: `451`
|
|
70
|
+
- Domains: `adb-bridge`, `binary-instrument`, `boringssl-inspector`, `browser`, `canvas`, `coordination`, `core`, `cross-domain`, `dart-inspector`, `debugger`, `encoding`, `extension-registry`, `graphql`, `instrumentation`, `maintenance`, `memory`, `mojo-ipc`, `native-emulator`, `network`, `platform`, `process`, `protocol-analysis`, `proxy`, `sourcemap`, `streaming`, `syscall-hook`, `trace`, `transform`, `v8-inspector`, `wasm`, `workflow`
|
|
63
71
|
- Note: this snapshot is generated from the runtime registry; do not edit the counts by hand.
|
|
64
72
|
<!-- metadata-sync:end -->
|
|
65
73
|
|
package/README.zh.md
CHANGED
|
@@ -40,11 +40,19 @@
|
|
|
40
40
|
- ⚡ **搜索优先** — `search` 档 ≈ 3K tokens vs `full` 档 ≈ 40K+ tokens,按需加载
|
|
41
41
|
- 🎯 **渐进分层** — `search` → `workflow` → `full`,按需激活
|
|
42
42
|
- 🌐 **全栈浏览器自动化** — Chromium/Camoufox + CDP + 反检测 + CAPTCHA 处理
|
|
43
|
+
- 🔁 **运行时恢复与会话隔离** — HTTP 会话支持恢复已激活域、浏览器 attach 状态、coverage 状态,并为每个客户端隔离浏览器侧会话状态
|
|
44
|
+
- 🧭 **Schema 优先元工具** — `describe_tool`、带参数校验的 `call_tool`、以及 `coverage_report` 降低参数错误并暴露工具覆盖率
|
|
43
45
|
- 📡 **网络拦截** — HTTP/2 帧构造、MiTM 捕获、GraphQL、Burp Suite 桥接
|
|
44
46
|
- 🛠️ **全能逆向工具链** — WASM 反编译、二进制分析、Frida、Ghidra/IDA 桥接
|
|
45
47
|
- 🧰 **进程与内存取证** — 原生 FFI 扫描、硬件断点、PE 内省
|
|
46
48
|
- 🧩 **动态热插拔** — 热重载插件、声明式工作流、自发现域
|
|
47
49
|
|
|
50
|
+
## 最近运行时变更
|
|
51
|
+
|
|
52
|
+
- HTTP 传输现在支持多路复用独立 MCP 会话,并在重连后恢复运行时状态。
|
|
53
|
+
- `proxy_start` 在需要时会自动生成本地 HTTPS 拦截 CA。
|
|
54
|
+
- Browser 域的 CAPTCHA 求解已改为显式参数驱动:按需传入 `taskKind`、`siteKey`、`imageBase64`、`callbackName`、`responseSelector`。不会再内置页面/组件特征探测。
|
|
55
|
+
|
|
48
56
|
## 架构
|
|
49
57
|
|
|
50
58
|
- **运行时注册表** — 域通过 `manifest.ts` 自发现;新增域只需创建一个文件
|
|
@@ -57,9 +65,9 @@
|
|
|
57
65
|
下面的内置能力快照由运行时 registry 动态生成,并在 CI 中校验。
|
|
58
66
|
|
|
59
67
|
<!-- metadata-sync:start -->
|
|
60
|
-
- 包版本:`0.3.
|
|
61
|
-
- 内置工具数:`
|
|
62
|
-
- 域列表:`adb-bridge`, `
|
|
68
|
+
- 包版本:`0.3.3`
|
|
69
|
+
- 内置工具数:`451`
|
|
70
|
+
- 域列表:`adb-bridge`, `binary-instrument`, `boringssl-inspector`, `browser`, `canvas`, `coordination`, `core`, `cross-domain`, `dart-inspector`, `debugger`, `encoding`, `extension-registry`, `graphql`, `instrumentation`, `maintenance`, `memory`, `mojo-ipc`, `native-emulator`, `network`, `platform`, `process`, `protocol-analysis`, `proxy`, `sourcemap`, `streaming`, `syscall-hook`, `trace`, `transform`, `v8-inspector`, `wasm`, `workflow`
|
|
63
71
|
- 说明:以上数据由运行时 registry 动态生成,不要手改计数。
|
|
64
72
|
<!-- metadata-sync:end -->
|
|
65
73
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{a as t,b as n,d as r,h as i,i as a,n as o,s,t as c,u as l}from"./Win32API-DoP3MMHS.mjs";import{PEAnalyzer as u}from"./PEAnalyzer-CMu9Ua9T.mjs";import{promises as d}from"node:fs";import{createHash as f}from"node:crypto";const p=[{dll:`kernel32.dll`,funcs:[{name:`IsDebuggerPresent`,mechanism:`anti_debug_api`,confidence:`high`,bypass:`Hook IsDebuggerPresent to return 0, or patch PEB.BeingDebugged field`},{name:`CheckRemoteDebuggerPresent`,mechanism:`anti_debug_api`,confidence:`high`,bypass:`Hook CheckRemoteDebuggerPresent to set output to FALSE and return TRUE`},{name:`OutputDebugStringA`,mechanism:`exception_based`,confidence:`low`,bypass:`May be used for anti-debug timing — monitor for exception handler abuse`},{name:`GetTickCount`,mechanism:`timing_check`,confidence:`low`,bypass:`Hook GetTickCount to return consistent delta values`},{name:`GetTickCount64`,mechanism:`timing_check`,confidence:`low`,bypass:`Hook GetTickCount64 to return consistent delta values`},{name:`QueryPerformanceCounter`,mechanism:`timing_check`,confidence:`medium`,bypass:`Hook QPC to filter out debugging time deltas`}]},{dll:`ntdll.dll`,funcs:[{name:`NtQueryInformationProcess`,mechanism:`ntquery_debug`,confidence:`high`,bypass:`Hook NtQueryInformationProcess: return 0 for ProcessDebugPort (7), ProcessDebugObjectHandle (30), ProcessDebugFlags (31)`},{name:`NtSetInformationThread`,mechanism:`thread_hiding`,confidence:`medium`,bypass:`Hook NtSetInformationThread: intercept ThreadHideFromDebugger (0x11) calls`},{name:`NtClose`,mechanism:`exception_based`,confidence:`low`,bypass:`NtClose with invalid handle detects debugger via exception — hook to suppress`},{name:`RtlGetNtGlobalFlags`,mechanism:`heap_flags`,confidence:`medium`,bypass:`Clear NtGlobalFlag (FLG_HEAP_*) in PEB at offset 0xBC (x64)`}]}],m=[`GetThreadContext`,`SetThreadContext`],h={guardPageMaxRegions:2e4,guardPageTimeoutMs:2e3,integrityMaxModules:32,integrityMaxSections:128,integrityMaxBytes:16*1024*1024,integrityMaxSectionBytes:2*1024*1024,integrityTimeoutMs:3e3};var g=class{peAnalyzer=new u;options;constructor(e={}){this.options={...h,...e}}async detect(t){let r=[],i=n(t);try{let n=this.enumerateModules(i);for(let i of n)try{let e=await this.peAnalyzer.parseImports(t,i.base);for(let t of e){let e=t.dllName.toLowerCase();for(let n of p)if(e.includes(n.dll.toLowerCase().replace(`.dll`,``)))for(let e of n.funcs)t.functions.some(t=>t.name===e.name)&&r.push({mechanism:e.mechanism,confidence:e.confidence,location:`import:${e.name}`,moduleName:i.name,details:`${i.name} imports ${e.name} from ${t.dllName}`,bypassSuggestion:e.bypass});for(let e of t.functions)m.includes(e.name)&&r.push({mechanism:`hardware_breakpoint`,confidence:`medium`,location:`import:${e.name}`,moduleName:i.name,details:`${i.name} imports ${e.name} — may check debug registers for hardware breakpoints`,bypassSuggestion:`Hook GetThreadContext to zero out DR0-DR3 and DR6/DR7 before returning`})}}catch(t){e.debug(`Import scan skipped for ${i.name}: ${t}`)}}finally{c(i)}return r}async findGuardPages(e){return(await this.scanGuardPages(e)).guardPages}async scanGuardPages(e){let t=[],r=n(e),a=Date.now(),o={scannedRegions:0,queryFailures:0,durationMs:0,timedOut:!1,truncated:!1,maxRegions:this.options.guardPageMaxRegions,timeoutMs:this.options.guardPageTimeoutMs};try{let e=this.enumerateModules(r),n=0n;for(;n<140737488355327n;){if(this.isTimedOut(a,o.timeoutMs)){o.timedOut=!0,o.truncated=!0;break}if(o.scannedRegions>=o.maxRegions){o.truncated=!0;break}try{let a=i(r,n);if(!a.success)break;let s=a.info,c=s.BaseAddress+s.RegionSize;if(o.scannedRegions+=1,(s.Protect&l.GUARD)!==0){let n=null;for(let t of e){let e=BigInt(t.base);if(s.BaseAddress>=e&&s.BaseAddress<e+BigInt(t.size)){n=t.name;break}}t.push({address:`0x${s.BaseAddress.toString(16)}`,size:Number(s.RegionSize),moduleName:n,nearbySymbol:null})}if(s.RegionSize<=0n||c<=n||c<=s.BaseAddress){o.truncated=!0;break}n=c}catch{o.queryFailures+=1,n+=4096n}}}finally{o.durationMs=Date.now()-a,c(r)}return{guardPages:t,stats:o}}async checkIntegrity(e,t){return(await this.scanIntegrity(e,t)).sections}async scanIntegrity(t,i){let a=[],o=n(t),s=Date.now(),l={scannedModules:0,scannedSections:0,hashedBytes:0,skippedModules:0,skippedSections:0,durationMs:0,timedOut:!1,truncated:!1,maxModules:this.options.integrityMaxModules,maxSections:this.options.integrityMaxSections,maxBytes:this.options.integrityMaxBytes,timeoutMs:this.options.integrityTimeoutMs},u=!1;try{let n=this.enumerateModules(o),c=i?n.filter(e=>e.name.toLowerCase().includes(i.toLowerCase())):n;for(let n of c){if(this.shouldStopIntegrityScan(l,s)){this.isTimedOut(s,l.timeoutMs)&&(l.timedOut=!0),l.truncated=!0;break}l.scannedModules+=1;try{let e=await d.readFile(n.path),i=await this.peAnalyzer.listSections(t,n.base);for(let t of i){if(this.shouldStopIntegrityScan(l,s)){this.isTimedOut(s,l.timeoutMs)&&(l.timedOut=!0),l.truncated=!0,u=!0;break}if(!t.isExecutable)continue;let i=parseInt(t.virtualAddress,16),c=Math.min(t.virtualSize,t.rawSize);if(c<=0)continue;if(c>this.options.integrityMaxSectionBytes){l.skippedSections+=1;continue}if(l.hashedBytes+c>l.maxBytes){l.truncated=!0,u=!0;break}let d=r(o,BigInt(n.base)+BigInt(i),c),p=this.rvaToFileOffset(e,i);if(p<0||p+c>e.length)continue;let m=e.subarray(p,p+c),h=f(`sha256`).update(d).digest(`hex`),g=f(`sha256`).update(m).digest(`hex`);a.push({sectionName:t.name,moduleName:n.name,diskHash:g,memoryHash:h,isModified:h!==g}),l.scannedSections+=1,l.hashedBytes+=c}}catch(t){l.skippedModules+=1,e.debug(`Integrity check skipped for ${n.name}: ${t}`)}if(u)break}}finally{l.durationMs=Date.now()-s,c(o)}return{sections:a,stats:l}}enumerateModules(n){let r=[];try{let{modules:e,count:i}=o(n);for(let o=0;o<i;o++){let i=e[o],c=a(n,i),l=s(n,i),u=t(n,i)??c;l.success&&r.push({name:c,base:`0x${l.info.lpBaseOfDll.toString(16)}`,path:u,size:l.info.SizeOfImage})}}catch(t){e.debug(`Module enumeration failed: ${t}`)}return r}rvaToFileOffset(e,t){let n=e.readUInt32LE(60),r=e.readUInt16LE(n+6),i=e.readUInt16LE(n+20),a=n+24+i;for(let n=0;n<r;n++){let r=a+n*40;if(r+40>e.length)break;let i=e.readUInt32LE(r+12),o=e.readUInt32LE(r+8),s=e.readUInt32LE(r+20);if(t>=i&&t<i+o)return s+(t-i)}return-1}isTimedOut(e,t){return Date.now()-e>=t}shouldStopIntegrityScan(e,t){return this.isTimedOut(t,e.timeoutMs)||e.scannedModules>=e.maxModules||e.scannedSections>=e.maxSections||e.hashedBytes>=e.maxBytes}};const _=new g;export{g as AntiCheatDetector,_ as antiCheatDetector};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{AsyncLocalStorage as t}from"node:async_hooks";let n=0;var r=class{pageIdByHandle=new WeakMap;tabsById=new Map;aliasToPageId=new Map;currentPageId=null;sharedContext=new Map;upsertPage(e,t){let n=this.pageIdByHandle.get(e),r=n?this.tabsById.get(n)?.meta:null,i=typeof t.index==`number`&&Number.isFinite(t.index)?t.index:r?.index??0;return this.registerPage(e,{index:i,url:t.url,title:t.title})}registerPage(t,r){let i=t,a=this.pageIdByHandle.get(i);if(a){let e=this.tabsById.get(a);return e?(e.meta=r,e.stale=!1):this.tabsById.set(a,{page:t,meta:r,stale:!1}),a}n+=1;let o=`tab-${n}`;return this.pageIdByHandle.set(i,o),this.tabsById.set(o,{page:t,meta:r,stale:!1}),e.debug(`[TabRegistry] Registered page ${o} (index=${r.index}, url=${r.url})`),o}reconcilePages(t,n){let r=new Set;for(let e=0;e<t.length;e++){let i=t[e],a=n[e]??{index:e,url:``,title:``},o=this.registerPage(i,{...a,index:e});r.add(o)}let i=[];for(let[t,n]of this.tabsById)r.has(t)||(n.stale?i.push(t):(n.stale=!0,e.debug(`[TabRegistry] Page ${t} marked stale`)));for(let t of i)this.tabsById.delete(t),e.debug(`[TabRegistry] Page ${t} pruned (was already stale)`);return this.currentPageId&&!r.has(this.currentPageId)&&(e.debug(`[TabRegistry] Current page ${this.currentPageId} is stale, clearing`),this.currentPageId=null),this.listTabs()}bindAlias(e,t){return this.tabsById.has(t)?(this.aliasToPageId.set(e,t),!0):!1}bindAliasByIndex(e,t){for(let[n,r]of this.tabsById)if(r.meta.index===t&&!r.stale)return this.aliasToPageId.set(e,n),n;return null}unbindAlias(e){return this.aliasToPageId.delete(e)}resolveAlias(e){let t=this.aliasToPageId.get(e);if(!t)return null;let n=this.tabsById.get(t);return!n||n.stale?null:t}getPageById(e){let t=this.tabsById.get(e);return!t||t.stale?null:t.page}getTabById(e){let t=this.tabsById.get(e);if(!t)return null;let n=this.getAliasesForPageId(e);return{pageId:e,index:t.meta.index,url:t.meta.url,title:t.meta.title,page:t.page,aliases:n,stale:t.stale}}getTabByIndex(e){for(let[t,n]of this.tabsById)if(n.meta.index===e&&!n.stale)return this.getTabById(t);return null}findTab(e){for(let[t]of this.tabsById){let n=this.getTabById(t);if(n&&e(n))return n}return null}setCurrentPageId(e){let t=this.tabsById.get(e);return!t||t.stale?!1:(this.currentPageId=e,!0)}setCurrentByIndex(e){let t=this.getTabByIndex(e);return t&&(this.currentPageId=t.pageId),t}getCurrentPageId(){return this.currentPageId}getCurrentPage(){return this.currentPageId?this.getPageById(this.currentPageId):null}getCurrentTabInfo(e){let t=[],n=[];for(let[e,r]of this.aliasToPageId){let i=this.tabsById.get(r),a=!i||i.stale;t.push({alias:e,pageId:r,index:i?.meta.index??null,stale:a}),a&&n.push(e)}let r=this.currentPageId?this.tabsById.get(this.currentPageId):null,i=r&&!r.stale?r:null;return{driver:e,currentPageId:i?this.currentPageId:null,currentIndex:i?.meta.index??null,url:i?.meta.url??null,title:i?.meta.title??null,aliases:t,staleAliases:n}}getContextMeta(){let e=this.currentPageId?this.tabsById.get(this.currentPageId):null,t=e&&!e.stale?e:null;return{url:t?.meta.url??null,title:t?.meta.title??null,tabIndex:t?.meta.index??null,pageId:t?this.currentPageId:null}}listTabs(){let e=[];for(let[t,n]of this.tabsById)if(!n.stale){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:!1})}return e.toSorted((e,t)=>e.index-t.index)}listAllTabs(){let e=[];for(let[t,n]of this.tabsById){let r=this.getAliasesForPageId(t);e.push({pageId:t,index:n.meta.index,url:n.meta.url,title:n.meta.title,page:n.page,aliases:r,stale:n.stale})}return e.toSorted((e,t)=>e.index-t.index)}setSharedContext(e,t){this.sharedContext.set(e,t)}getSharedContext(e){return{value:this.sharedContext.get(e)??null,found:this.sharedContext.has(e)}}getSharedContextMap(){let e={};return this.sharedContext.forEach((t,n)=>{e[n]=t}),e}clear(){this.tabsById.clear(),this.aliasToPageId.clear(),this.sharedContext.clear(),this.currentPageId=null}getAliasesForPageId(e){let t=[];for(let[n,r]of this.aliasToPageId)r===e&&t.push(n);return t}};function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(e){try{return JSON.parse(e)}catch{return null}}function o(e){if(!i(e)||!Array.isArray(e.content)||e.content.length===0)return null;let t=e.content[0];if(!i(t)||typeof t.text!=`string`)return null;let n=a(t.text);return i(n)?{currentTabIndex:typeof n.selectedIndex==`number`&&Number.isFinite(n.selectedIndex)?n.selectedIndex:typeof n.currentIndex==`number`&&Number.isFinite(n.currentIndex)?n.currentIndex:null,currentPageId:typeof n.selectedPageId==`string`?n.selectedPageId:null,currentTargetId:typeof n.targetId==`string`?n.targetId:null,lastToolName:typeof n.toolName==`string`?n.toolName:null,lastTouchedAt:new Date().toISOString()}:null}var s=class{getCollector;executionContext=new t;sessions=new Map;lastActiveSessionId=null;executionQueue=Promise.resolve();constructor(e){this.getCollector=e}normalizeSessionId(e){return typeof e!=`string`||e.trim().length===0?`default`:e}getCurrentSessionId(){return this.executionContext.getStore()?.sessionId??null}getOrCreateSession(e){let t=this.normalizeSessionId(e),n=this.sessions.get(t);return n||(n={tabRegistry:new r,currentTabIndex:null,currentPageId:null,currentTargetId:null,lastToolName:null,lastTouchedAt:null},this.sessions.set(t,n)),n}getTabRegistry(e){return this.getOrCreateSession(e).tabRegistry}noteToolResult(e,t,n){let r=this.getOrCreateSession(e);n?.currentTabIndex!==void 0&&(r.currentTabIndex=n.currentTabIndex??null),n?.currentPageId!==void 0&&(r.currentPageId=n.currentPageId??null),n?.currentTargetId!==void 0&&(r.currentTargetId=n.currentTargetId??null),r.lastToolName=t,r.lastTouchedAt=new Date().toISOString(),this.lastActiveSessionId=this.normalizeSessionId(e)}getSnapshot(e){let t=this.getOrCreateSession(e);return{currentTabIndex:t.currentTabIndex,currentPageId:t.currentPageId,currentTargetId:t.currentTargetId,lastToolName:t.lastToolName,lastTouchedAt:t.lastTouchedAt}}async restoreSessionContext(t){let n=this.normalizeSessionId(t),r=this.getOrCreateSession(n),i=this.getCollector();if(!i){this.lastActiveSessionId=n;return}if(this.lastActiveSessionId===n||r.currentTabIndex===null&&r.currentTargetId===null){this.lastActiveSessionId=n;return}if(typeof r.currentTabIndex==`number`)try{await i.selectPage(r.currentTabIndex)}catch(t){e.warn(`[browser-session] Failed to restore page index ${r.currentTabIndex} for session ${n}: ${t instanceof Error?t.message:String(t)}`)}if(r.currentTargetId)try{await i.attachCdpTarget(r.currentTargetId)}catch(t){e.warn(`[browser-session] Failed to restore target ${r.currentTargetId} for session ${n}: ${t instanceof Error?t.message:String(t)}`)}this.lastActiveSessionId=n}async runExclusive(e,t){let n=this.normalizeSessionId(e);if(this.executionContext.getStore()?.sessionId===n)return await t();let r=this.executionQueue,i,a=new Promise(e=>{i=e});this.executionQueue=r.then(()=>a),await r;try{return await this.executionContext.run({sessionId:n},t)}finally{i()}}};export{o as n,r,s as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rt as e}from"./constants-DMv3svps.mjs";import{t}from"./ToolError-g3rjWzhx.mjs";import{r as n}from"./native-g095qhpK.mjs";import{_ as r,b as i,d as a,f as o,h as s,l as c,m as l,p as u,t as d,u as f}from"./Win32API-DoP3MMHS.mjs";import{l as p}from"./Win32Debug-DwF8mQGm.mjs";import{n as m}from"./NativeMemoryManager.utils-Bu8srMEF.mjs";import{randomUUID as h}from"node:crypto";var g=class{patches=new Map;async patchBytes(e,t,n){let o=BigInt(t.startsWith(`0x`)?t:`0x${t}`),s=Buffer.from(n),c=i(e,!0);try{let t=a(c,o,s.length),{success:i,oldProtect:u}=l(c,o,s.length,f.EXECUTE_READWRITE);r(c,o,s),p(c,o,s.length),i&&l(c,o,s.length,u);let d={id:h(),pid:e,address:`0x${o.toString(16).toUpperCase()}`,originalBytes:Array.from(t),patchBytes:n,isApplied:!0,timestamp:Date.now()};return this.patches.set(d.id,d),d}finally{d(c)}}async unpatch(e){let t=this.patches.get(e);if(!t?.isApplied)return!1;let n=BigInt(t.address),a=Buffer.from(t.originalBytes),o=i(t.pid,!0);try{let{oldProtect:e}=l(o,n,a.length,f.EXECUTE_READWRITE);return r(o,n,a),p(o,n,a.length),l(o,n,a.length,e),t.isApplied=!1,!0}finally{d(o)}}async nopBytes(e,t,n){let r=Array.from({length:n},()=>144);return this.patchBytes(e,t,r)}async findCodeCaves(t,r){let o=r??e,c=[],l=i(t,!1);try{let e=await n.enumerateModules(t);if(!e.success||!e.modules)return c;for(let t of e.modules){let e=BigInt(t.baseAddress.startsWith(`0x`)?t.baseAddress:`0x${t.baseAddress}`),n=e,r=e+BigInt(t.size);for(;n<r;){let{success:e,info:r}=s(l,n);if(!e||r.RegionSize===0n)break;let i=Number(r.RegionSize);if(m(r.Protect)&&i>0)try{let e=a(l,r.BaseAddress,Math.min(i,4*1024*1024)),n=-1;for(let i=0;i<e.length;i++){let a=e[i];if(a===0||a===204)n===-1&&(n=i);else if(n!==-1){let e=i-n;if(e>=o){let i=r.BaseAddress+BigInt(n);c.push({address:`0x${i.toString(16).toUpperCase()}`,size:e,module:t.name,section:`.text`})}n=-1}}if(n!==-1){let i=e.length-n;if(i>=o){let e=r.BaseAddress+BigInt(n);c.push({address:`0x${e.toString(16).toUpperCase()}`,size:i,module:t.name,section:`.text`})}}}catch{}n=r.BaseAddress+r.RegionSize}}}finally{d(l)}return c.toSorted((e,t)=>t.size-e.size)}async allocateRemote(e,n){let r=i(e,!0);try{let e=o(r,0n,n,c.COMMIT|c.RESERVE,f.EXECUTE_READWRITE);if(e===0n)throw new t(`RUNTIME`,`VirtualAllocEx failed`);return`0x${e.toString(16).toUpperCase()}`}finally{d(r)}}async freeRemote(e,t,n){let r=BigInt(t.startsWith(`0x`)?t:`0x${t}`),a=i(e,!0);try{return u(a,r,0,c.RELEASE)}finally{d(a)}}listPatches(){return Array.from(this.patches.values())}};const _=new g;export{g as CodeInjector,_ as codeInjector};
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{_ as t,v as n}from"./ensure-browser-core-JHwDo5ql.mjs";import{randomUUID as r}from"node:crypto";var i=class{page;networkEnabled=!1;requests=new Map;responses=new Map;MAX_NETWORK_RECORDS=500;MAX_INJECTED_RECORDS=500;requestCounter=0;responseBodyCache=new Map;MAX_BODY_CACHE_ENTRIES=200;requestIdMap=new WeakMap;boundOnRequest=null;boundOnResponse=null;constructor(e){this.page=e}setPage(e){if(this.page===e)return;let t=this.page,n=this.networkEnabled,r=this.boundOnRequest,i=this.boundOnResponse;if(n&&t&&r)try{t.off(`request`,r)}catch{}if(n&&t&&i)try{t.off(`response`,i)}catch{}if(this.page=e,!n||!this.page){this.page||(this.networkEnabled=!1);return}r&&this.page.on(`request`,r),i&&this.page.on(`response`,i)}getPageOrThrow(){if(!this.page)throw Error(`Playwright page not initialized`);return this.page}async evaluateInPage(e){let t=this.getPageOrThrow();if(!t.evaluate)throw Error(`Playwright page.evaluate is not available`);return t.evaluate(e)}async evaluateOnNewDocumentInPage(e){let t=this.getPageOrThrow();if(!t.evaluateOnNewDocument)throw Error(`Playwright page.evaluateOnNewDocument is not available`);return t.evaluateOnNewDocument(e)}isUnknownArray(e){return Array.isArray(e)}isClearedBuffersResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrCleared==`number`&&typeof t.fetchCleared==`number`}isResetInterceptorsResult(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.xhrReset==`boolean`&&typeof t.fetchReset==`boolean`}isPlaywrightLikeRequest(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.url==`function`&&typeof t.method==`function`&&typeof t.headers==`function`&&typeof t.postData==`function`&&typeof t.resourceType==`function`}isPlaywrightLikeResponse(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.request==`function`&&typeof t.url==`function`&&typeof t.status==`function`&&typeof t.statusText==`function`&&typeof t.headers==`function`}normalizeHttpVersion(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`http/1.0`||t===`1.0`)return`1.0`;if(t===`http/1.1`||t===`1.1`)return`1.1`;if(t===`http/2`||t===`2`||t===`2.0`||t===`h2`)return`h2`;if(t===`http/3`||t===`3`||t===`3.0`||t===`h3`)return`h3`}detectHttpVersion(e){let t=typeof e.httpVersion==`function`?e.httpVersion():void 0,n=this.normalizeHttpVersion(t);if(n)return n;let r=typeof e.protocol==`function`?e.protocol():void 0;return this.normalizeHttpVersion(r)}async enable(){if(this.networkEnabled){e.warn(`PlaywrightNetworkMonitor already enabled`);return}this.boundOnRequest=e=>{if(!this.isPlaywrightLikeRequest(e))return;let t=`pw-${++this.requestCounter}`;this.requestIdMap.set(e,t);let n={requestId:t,url:e.url(),method:e.method(),headers:e.headers(),postData:e.postData()??void 0,timestamp:Date.now(),type:e.resourceType()};if(this.requests.set(t,n),this.requests.size>this.MAX_NETWORK_RECORDS){let e=this.requests.keys().next().value;e&&this.requests.delete(e)}},this.boundOnResponse=t=>{if(!this.isPlaywrightLikeResponse(t))return;let n=t.request(),r=`pw-res-${Date.now()}-${Math.random()}`,i=this.isPlaywrightLikeRequest(n)?this.requestIdMap.get(n)??r:r,a=this.detectHttpVersion(t),o=this.requests.get(i);o&&a&&(o.httpVersion=a);let s={requestId:i,url:t.url(),status:t.status(),statusText:t.statusText(),headers:t.headers(),mimeType:t.headers()[`content-type`]??`unknown`,timestamp:Date.now()};if(this.responses.set(i,s),this.responses.size>this.MAX_NETWORK_RECORDS){let e=this.responses.keys().next().value;e&&this.responses.delete(e)}if(typeof t.body==`function`){let n=i;t.body().then(t=>{if(t.length>1048576){e.debug(`[PW-BodyCache] Skipping oversized body for ${n} (${t.length} bytes)`);return}if(this.responseBodyCache.size>=this.MAX_BODY_CACHE_ENTRIES){let e=this.responseBodyCache.keys().next().value;e&&this.responseBodyCache.delete(e)}/^(text\/|application\/(json|javascript|xml|x-www-form-urlencoded))/i.test(s.mimeType)?this.responseBodyCache.set(n,{body:t.toString(`utf-8`),base64Encoded:!1}):this.responseBodyCache.set(n,{body:t.toString(`base64`),base64Encoded:!0}),e.debug(`[PW-BodyCache] Cached body for ${n} (${t.length} bytes)`)}).catch(t=>{e.debug(`[PW-BodyCache] Could not capture body for ${n}: ${t instanceof Error?t.message:String(t)}`)})}};let t=this.getPageOrThrow();t.on(`request`,this.boundOnRequest),t.on(`response`,this.boundOnResponse),this.networkEnabled=!0,e.info(`PlaywrightNetworkMonitor enabled`)}async disable(){let t=this.getPageOrThrow();if(this.boundOnRequest){try{t.off(`request`,this.boundOnRequest)}catch{}this.boundOnRequest=null}if(this.boundOnResponse){try{t.off(`response`,this.boundOnResponse)}catch{}this.boundOnResponse=null}this.networkEnabled=!1,e.info(`PlaywrightNetworkMonitor disabled`)}isEnabled(){return this.networkEnabled}getRequests(e){let t=Array.from(this.requests.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.method&&(t=t.filter(t=>t.method.toUpperCase()===e.method.toUpperCase())),e?.limit&&(t=t.slice(-e.limit)),t}getResponses(e){let t=Array.from(this.responses.values());return e?.url&&(t=t.filter(t=>t.url.includes(e.url))),e?.status&&(t=t.filter(t=>t.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getStatus(){return{enabled:this.networkEnabled,requestCount:this.requests.size,responseCount:this.responses.size,listenerCount:this.networkEnabled?2:0,cdpSessionActive:!1}}getActivity(e){return{request:this.requests.get(e),response:this.responses.get(e)}}clearRecords(){this.requests.clear(),this.responses.clear(),this.responseBodyCache.clear()}getStats(){let e=Array.from(this.requests.values()),t=Array.from(this.responses.values()),n={};e.forEach(e=>{n[e.method]=(n[e.method]||0)+1});let r={};t.forEach(e=>{r[e.status]=(r[e.status]||0)+1});let i={};return e.forEach(e=>{let t=e.type||`unknown`;i[t]=(i[t]||0)+1}),{totalRequests:e.length,totalResponses:t.length,byMethod:n,byStatus:r,byType:i}}async getResponseBody(t){let n=this.responseBodyCache.get(t);return n?(this.responseBodyCache.delete(t),this.responseBodyCache.set(t,n),e.debug(`[PW-BodyCache] Cache hit for ${t}`),n):(e.warn(`getResponseBody: no cached body for ${t} in Playwright mode`),null)}async injectScript(e){await this.evaluateInPage(e)}async injectXHRInterceptor(e){let t=`
|
|
2
|
+
(function() {
|
|
3
|
+
if (window.__xhrInterceptorInjected) return;
|
|
4
|
+
window.__xhrInterceptorInjected = true;
|
|
5
|
+
const maxRecords = ${this.MAX_INJECTED_RECORDS};
|
|
6
|
+
const OrigXHR = window.__pwOriginalXMLHttpRequest || window.XMLHttpRequest;
|
|
7
|
+
window.__pwOriginalXMLHttpRequest = OrigXHR;
|
|
8
|
+
if (!window.__xhrRequests) window.__xhrRequests = [];
|
|
9
|
+
window.XMLHttpRequest = function() {
|
|
10
|
+
const xhr = new OrigXHR();
|
|
11
|
+
const origOpen = xhr.open.bind(xhr);
|
|
12
|
+
const origSend = xhr.send.bind(xhr);
|
|
13
|
+
xhr.open = function(method, url, ...rest) {
|
|
14
|
+
xhr.__hookMeta = { method, url, timestamp: Date.now() };
|
|
15
|
+
return origOpen(method, url, ...rest);
|
|
16
|
+
};
|
|
17
|
+
xhr.send = function(body) {
|
|
18
|
+
xhr.addEventListener('load', function() {
|
|
19
|
+
window.__xhrRequests.push({
|
|
20
|
+
...xhr.__hookMeta, body: body ? String(body).slice(0, 2048) : null,
|
|
21
|
+
status: xhr.status, response: xhr.responseText.slice(0, 2048),
|
|
22
|
+
});
|
|
23
|
+
if (window.__xhrRequests.length > maxRecords) {
|
|
24
|
+
window.__xhrRequests.splice(0, window.__xhrRequests.length - maxRecords);
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
return origSend(body);
|
|
28
|
+
};
|
|
29
|
+
return xhr;
|
|
30
|
+
};
|
|
31
|
+
console.log('[PlaywrightXHR] XHR interceptor injected');
|
|
32
|
+
})();
|
|
33
|
+
`;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async injectFetchInterceptor(e){let t=`
|
|
34
|
+
(function() {
|
|
35
|
+
if (window.__fetchInterceptorInjected) return;
|
|
36
|
+
window.__fetchInterceptorInjected = true;
|
|
37
|
+
const maxRecords = ${this.MAX_INJECTED_RECORDS};
|
|
38
|
+
const origFetch = window.__pwOriginalFetch || window.fetch;
|
|
39
|
+
window.__pwOriginalFetch = origFetch;
|
|
40
|
+
if (!window.__fetchRequests) window.__fetchRequests = [];
|
|
41
|
+
const normalizeHeaders = (value) => {
|
|
42
|
+
if (!value) return {};
|
|
43
|
+
try {
|
|
44
|
+
if (typeof Headers !== 'undefined' && value instanceof Headers) {
|
|
45
|
+
return Object.fromEntries(value.entries());
|
|
46
|
+
}
|
|
47
|
+
} catch {}
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
try {
|
|
50
|
+
return Object.fromEntries(value);
|
|
51
|
+
} catch {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return typeof value === 'object' ? value : {};
|
|
56
|
+
};
|
|
57
|
+
window.fetch = function(...args) {
|
|
58
|
+
const [resource, opts = {}] = args;
|
|
59
|
+
const requestLike = resource && typeof resource === 'object' ? resource : null;
|
|
60
|
+
const url =
|
|
61
|
+
typeof resource === 'string'
|
|
62
|
+
? resource
|
|
63
|
+
: typeof resource?.url === 'string'
|
|
64
|
+
? resource.url
|
|
65
|
+
: String(resource);
|
|
66
|
+
const method = opts?.method || requestLike?.method || 'GET';
|
|
67
|
+
const headers = normalizeHeaders(opts?.headers || requestLike?.headers);
|
|
68
|
+
const bodySource = opts?.body;
|
|
69
|
+
const body =
|
|
70
|
+
bodySource === undefined || bodySource === null
|
|
71
|
+
? null
|
|
72
|
+
: String(bodySource).slice(0, 2048);
|
|
73
|
+
const entry = {
|
|
74
|
+
url,
|
|
75
|
+
method,
|
|
76
|
+
headers,
|
|
77
|
+
body,
|
|
78
|
+
timestamp: Date.now(),
|
|
79
|
+
response: null,
|
|
80
|
+
status: 0,
|
|
81
|
+
};
|
|
82
|
+
return origFetch.apply(this, args).then(res => {
|
|
83
|
+
entry.status = res.status;
|
|
84
|
+
return res.clone().text().then(
|
|
85
|
+
(text) => {
|
|
86
|
+
entry.response = text.slice(0, 2048);
|
|
87
|
+
return res;
|
|
88
|
+
},
|
|
89
|
+
() => {
|
|
90
|
+
entry.response = '[Unable to read response]';
|
|
91
|
+
return res;
|
|
92
|
+
},
|
|
93
|
+
).then((response) => {
|
|
94
|
+
window.__fetchRequests.push(entry);
|
|
95
|
+
if (window.__fetchRequests.length > maxRecords) {
|
|
96
|
+
window.__fetchRequests.splice(0, window.__fetchRequests.length - maxRecords);
|
|
97
|
+
}
|
|
98
|
+
// Auto-persist compact summary so data survives context compression
|
|
99
|
+
try {
|
|
100
|
+
const s = { url: entry.url, method: entry.method, status: entry.status, ts: entry.timestamp };
|
|
101
|
+
const prev = JSON.parse(localStorage.getItem('__capturedAPIs') || '[]');
|
|
102
|
+
prev.push(s);
|
|
103
|
+
if (prev.length > 500) prev.splice(0, prev.length - 500);
|
|
104
|
+
localStorage.setItem('__capturedAPIs', JSON.stringify(prev));
|
|
105
|
+
} catch(e) {}
|
|
106
|
+
return response;
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
console.log('[PlaywrightFetch] Fetch interceptor injected');
|
|
111
|
+
})();
|
|
112
|
+
`;e?.persistent?await this.evaluateOnNewDocumentInPage(t):await this.evaluateInPage(t)}async getXHRRequests(){try{let e=await this.evaluateInPage(()=>window.__xhrRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get XHR requests: ${t instanceof Error?t.message:String(t)}`),[]}}async getFetchRequests(){try{let e=await this.evaluateInPage(()=>window.__fetchRequests??[]);return this.isUnknownArray(e)?e:[]}catch(t){return e.warn(`[PW] Failed to get fetch requests: ${t instanceof Error?t.message:String(t)}`),[]}}async clearInjectedBuffers(){try{let e=await this.evaluateInPage(()=>{let e=window,t=e.__xhrRequests,n=e.__fetchRequests,r=Array.isArray(t)?t.length:0,i=Array.isArray(n)?n.length:0;return Array.isArray(t)&&(t.length=0),Array.isArray(n)&&(n.length=0),{xhrCleared:r,fetchCleared:i}});return this.isClearedBuffersResult(e)?e:{xhrCleared:0,fetchCleared:0}}catch(t){return e.warn(`[PW] Failed to clear injected buffers: ${t instanceof Error?t.message:String(t)}`),{xhrCleared:0,fetchCleared:0}}}async resetInjectedInterceptors(){try{let e=await this.evaluateInPage(()=>{let e=window,t=!1,n=!1;return e.__pwOriginalXMLHttpRequest&&(e.XMLHttpRequest=e.__pwOriginalXMLHttpRequest,t=!0),e.__pwOriginalFetch&&(e.fetch=e.__pwOriginalFetch,n=!0),Array.isArray(e.__xhrRequests)&&(e.__xhrRequests.length=0),Array.isArray(e.__fetchRequests)&&(e.__fetchRequests.length=0),e.__xhrInterceptorInjected=!1,e.__fetchInterceptorInjected=!1,{xhrReset:t,fetchReset:n}});return this.isResetInterceptorsResult(e)?e:{xhrReset:!1,fetchReset:!1}}catch(t){return e.warn(`[PW] Failed to reset interceptors: ${t instanceof Error?t.message:String(t)}`),{xhrReset:!1,fetchReset:!1}}}async getAllJavaScriptResponses(){return Array.from(this.responses.values()).filter(e=>e.mimeType.includes(`javascript`))}},a=class{cdpSession;rules=new Map;enabled=!1;eventHandler=null;compiledPatterns=new Map;constructor(e){this.cdpSession=e}async enable(t){let n=[];for(let e of t){let t=this.createRule(e);this.rules.set(t.id,t),this.compiledPatterns.set(t.id,this.compilePattern(t)),n.push(t)}return await this.applyRules(),this.eventHandler||(this.eventHandler=e=>{this.handleRequestPaused(e)},this.cdpSession.on(`Fetch.requestPaused`,this.eventHandler)),this.enabled=!0,e.info(`FetchInterceptor enabled with ${this.rules.size} rule(s)`),n}async disable(){let t=this.rules.size;if(this.eventHandler){try{this.cdpSession.off(`Fetch.requestPaused`,this.eventHandler)}catch{}this.eventHandler=null}try{await this.cdpSession.send(`Fetch.disable`)}catch(t){e.warn(`Fetch.disable failed:`,t)}return this.rules.clear(),this.compiledPatterns.clear(),this.enabled=!1,e.info(`FetchInterceptor disabled, removed ${t} rule(s)`),{removedRules:t}}async removeRule(e){let t=this.rules.delete(e);return this.compiledPatterns.delete(e),t&&(this.rules.size===0?await this.disable():await this.applyRules()),t}listRules(){let e=Array.from(this.rules.values());return{enabled:this.enabled,rules:e,totalHits:e.reduce((e,t)=>e+t.hitCount,0)}}isEnabled(){return this.enabled}createRule(e){let t=[];if(e.responseHeaders)for(let[n,r]of Object.entries(e.responseHeaders))t.push({name:n,value:r});return{id:r().slice(0,8),urlPattern:e.urlPattern,urlPatternType:e.urlPatternType??`glob`,stage:e.stage??`Response`,interceptAction:e.interceptAction??`fulfill`,responseCode:e.responseCode??200,responseHeaders:t,responseBody:e.responseBody??``,hitCount:0,createdAt:Date.now()}}compilePattern(e){if(e.urlPatternType===`regex`)try{return new RegExp(e.urlPattern,`i`)}catch{return new RegExp(e.urlPattern.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`i`)}let t=e.urlPattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`⟨GLOBSTAR⟩`).replace(/\*/g,`[^/]*`).replace(/⟨GLOBSTAR⟩/g,`.*`);return new RegExp(t,`i`)}async applyRules(){let t=[];for(let e of this.rules.values())t.push({urlPattern:e.urlPatternType===`glob`?e.urlPattern:`*`,requestStage:e.stage});if(t.length!==0)try{try{await this.cdpSession.send(`Fetch.disable`)}catch{}await this.cdpSession.send(`Fetch.enable`,{patterns:t.length>0?t:[{urlPattern:`*`,requestStage:`Response`}],handleAuthRequests:!1})}catch(t){throw e.error(`Failed to apply Fetch interception rules:`,t),t}}async handleRequestPaused(t){let n=t.request.url;for(let[r,i]of this.rules){let a=this.compiledPatterns.get(r);if(a&&a.test(n)&&(i.hitCount++,e.info(`[FetchInterceptor] Rule "${i.urlPattern}" matched: ${n}`),await this.applyMatchedRule(i,t,n)))return}await this.continueOriginalRequest(t,n)}async applyMatchedRule(t,n,r){try{switch(t.interceptAction){case`continue`:return await this.continuePausedRequest(n),!0;case`abort`:return await this.cdpSession.send(`Fetch.failRequest`,{requestId:n.requestId,errorReason:`Failed`}),!0;case`fulfill`:return await this.cdpSession.send(`Fetch.fulfillRequest`,{requestId:n.requestId,responseCode:t.responseCode,responseHeaders:this.buildFulfillHeaders(t),body:Buffer.from(t.responseBody,`utf-8`).toString(`base64`)}),!0}}catch(n){return e.error(`[FetchInterceptor] ${t.interceptAction} failed for ${r}:`,n),!1}}buildFulfillHeaders(e){let t=[...e.responseHeaders];return t.some(e=>e.name.toLowerCase()===`content-type`)||(e.responseBody.startsWith(`{`)||e.responseBody.startsWith(`[`)?t.push({name:`Content-Type`,value:`application/json`}):t.push({name:`Content-Type`,value:`text/plain`})),t.some(e=>e.name.toLowerCase()===`access-control-allow-origin`)||t.push({name:`Access-Control-Allow-Origin`,value:`*`}),t}async continuePausedRequest(e){if(e.responseStatusCode!==void 0){await this.cdpSession.send(`Fetch.continueResponse`,{requestId:e.requestId});return}await this.cdpSession.send(`Fetch.continueRequest`,{requestId:e.requestId})}async continueOriginalRequest(t,n){try{await this.continuePausedRequest(t)}catch(t){e.warn(`[FetchInterceptor] continue failed for ${n}:`,t)}}};function o(e){return e}function s(t,n){let r=o(t);if(r.contextSwitchPending)return[];let i=r.messages;n?.type&&(i=i.filter(e=>e.type===n.type));let a=n?.since;return a!==void 0&&(i=i.filter(e=>e.timestamp>=a)),n?.limit&&(i=i.slice(-n.limit)),e.debug(`getLogs: ${i.length} messages`),i}function c(t){let n=o(t);n.messages=[],e.info(`Console logs cleared`)}function l(e){let t=o(e);if(t.contextSwitchPending)return{totalMessages:0,byType:{}};let n={};for(let e of t.messages)n[e.type]=(n[e.type]||0)+1;return{totalMessages:t.messages.length,byType:n}}function u(e,t){let n=o(e);if(n.contextSwitchPending)return[];let r=n.exceptions;t?.url&&(r=r.filter(e=>e.url?.includes(t.url)));let i=t?.since;return i!==void 0&&(r=r.filter(e=>e.timestamp>=i)),t?.limit&&(r=r.slice(-t.limit)),r}function d(t){let n=o(t);n.exceptions=[],e.info(`Exceptions cleared`)}function f(e){return e}function p(e){return e.contextSwitchPending===!0}function m(e){let t=f(e);return p(t)?!1:(t.networkMonitor?.isEnabled()??!1)||(t.playwrightNetworkMonitor?.isEnabled()??!1)}function h(e){let t=f(e);return p(t)?{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:!1}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStatus():t.networkMonitor?t.networkMonitor.getStatus():{enabled:!1,requestCount:0,responseCount:0,listenerCount:0,cdpSessionActive:t.cdpSession!==null}}function g(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getRequests(t):n.networkMonitor?.getRequests(t)??[]}function _(e,t){let n=f(e);return p(n)?[]:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getResponses(t):n.networkMonitor?.getResponses(t)??[]}function v(e,t){let n=f(e);return p(n)?{}:n.playwrightNetworkMonitor?n.playwrightNetworkMonitor.getActivity(t):n.networkMonitor?.getActivity(t)??{}}async function y(t,n){let r=f(t);return p(r)?null:r.playwrightNetworkMonitor?r.playwrightNetworkMonitor.getResponseBody(n):r.networkMonitor?r.networkMonitor.getResponseBody(n):(e.error(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`),null)}async function b(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getAllJavaScriptResponses():t.networkMonitor?t.networkMonitor.getAllJavaScriptResponses():[]}function x(e){let t=f(e);t.networkMonitor?.clearRecords(),t.playwrightNetworkMonitor?.clearRecords()}async function S(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.clearInjectedBuffers(),dynamicScriptsCleared:0};let n=t.networkMonitor?await t.networkMonitor.clearInjectedBuffers():{xhrCleared:0,fetchCleared:0},r=await t.clearDynamicScriptBuffer();return{...n,...r}}async function C(e){let t=f(e);if(t.playwrightNetworkMonitor)return{...await t.playwrightNetworkMonitor.resetInjectedInterceptors(),scriptMonitorReset:!1};let n=t.networkMonitor?await t.networkMonitor.resetInjectedInterceptors():{xhrReset:!1,fetchReset:!1},r=await t.resetDynamicScriptMonitoring();return{...n,...r}}function w(e){let t=f(e);return p(t)?{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getStats():t.networkMonitor?.getStats()??{totalRequests:0,totalResponses:0,byMethod:{},byStatus:{},byType:{}}}async function T(e,t){let r=f(e);if(p(r))throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectXHRInterceptor(t);if(!r.networkMonitor)throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectXHRInterceptor(t)}async function E(e,t){let r=f(e);if(p(r))throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);if(r.playwrightNetworkMonitor)return r.playwrightNetworkMonitor.injectFetchInterceptor(t);if(!r.networkMonitor)throw new n(`Network monitoring is not enabled. Call enable() with enableNetwork: true first.`);return r.networkMonitor.injectFetchInterceptor(t)}async function D(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getXHRRequests():t.networkMonitor?t.networkMonitor.getXHRRequests():[]}async function O(e){let t=f(e);return p(t)?[]:t.playwrightNetworkMonitor?t.playwrightNetworkMonitor.getFetchRequests():t.networkMonitor?t.networkMonitor.getFetchRequests():[]}async function k(t,n){let r=t;if(await r.ensureSession(),!r.cdpSession)throw Error(`CDP session not available after reconnect attempt`);if(r.objectCache.has(n)){let e=r.objectCache.get(n);if(e!==void 0)return e}try{let t=await r.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),i={};for(let e of t.result){if(!e.value)continue;let t=e.value;i[e.name]={value:r.extractValue(t),type:t.type,objectId:t.objectId,description:t.description}}if(!r.objectCache.has(n))for(;r.objectCache.size>=r.MAX_OBJECT_CACHE_SIZE;){let e=r.objectCache.keys().next().value;if(e===void 0)break;r.objectCache.delete(e)}return r.objectCache.set(n,i),e.info(`Object inspected: ${n}`,{propertyCount:Object.keys(i).length}),i}catch(t){throw e.error(`Failed to inspect object:`,t),t}}function A(t){t.objectCache.clear(),e.info(`Object cache cleared`)}function j(e){return e}async function M(t,r){let i=j(t);if(await i.ensureSession(),!i.cdpSession)throw new n(`CDP session not available after reconnect attempt`);let a=`
|
|
113
|
+
(function() {
|
|
114
|
+
if (window.__dynamicScriptMonitorInstalled) {
|
|
115
|
+
console.log('[ScriptMonitor] Already installed');
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
window.__dynamicScriptMonitorInstalled = true;
|
|
119
|
+
|
|
120
|
+
const maxRecords = ${i.MAX_INJECTED_DYNAMIC_SCRIPTS};
|
|
121
|
+
if (!window.__dynamicScripts) {
|
|
122
|
+
window.__dynamicScripts = [];
|
|
123
|
+
}
|
|
124
|
+
const dynamicScripts = window.__dynamicScripts;
|
|
125
|
+
const state = window.__dynamicScriptMonitorState || {};
|
|
126
|
+
if (!state.originalCreateElement) state.originalCreateElement = document.createElement;
|
|
127
|
+
if (!state.originalEval) state.originalEval = window.eval;
|
|
128
|
+
if (!state.originalFunction) state.originalFunction = window.Function;
|
|
129
|
+
window.__dynamicScriptMonitorState = state;
|
|
130
|
+
|
|
131
|
+
const observer = new MutationObserver((mutations) => {
|
|
132
|
+
mutations.forEach((mutation) => {
|
|
133
|
+
mutation.addedNodes.forEach((node) => {
|
|
134
|
+
if (node.nodeName === 'SCRIPT') {
|
|
135
|
+
const script = node;
|
|
136
|
+
const info = {
|
|
137
|
+
type: 'dynamic',
|
|
138
|
+
src: script.src || '(inline)',
|
|
139
|
+
content: script.src ? null : script.textContent,
|
|
140
|
+
timestamp: Date.now(),
|
|
141
|
+
async: script.async,
|
|
142
|
+
defer: script.defer,
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
dynamicScripts.push(info);
|
|
146
|
+
if (dynamicScripts.length > maxRecords) {
|
|
147
|
+
dynamicScripts.splice(0, dynamicScripts.length - maxRecords);
|
|
148
|
+
}
|
|
149
|
+
console.log('[ScriptMonitor] Dynamic script added:', info);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
observer.observe(document.documentElement, {
|
|
156
|
+
childList: true,
|
|
157
|
+
subtree: true,
|
|
158
|
+
});
|
|
159
|
+
state.observer = observer;
|
|
160
|
+
|
|
161
|
+
const originalCreateElement = state.originalCreateElement;
|
|
162
|
+
document.createElement = function(tagName) {
|
|
163
|
+
const element = originalCreateElement.call(document, tagName);
|
|
164
|
+
|
|
165
|
+
if (tagName.toLowerCase() === 'script') {
|
|
166
|
+
console.log('[ScriptMonitor] Script element created via createElement');
|
|
167
|
+
|
|
168
|
+
const originalSetAttribute = element.setAttribute;
|
|
169
|
+
element.setAttribute = function(name, value) {
|
|
170
|
+
if (name === 'src') {
|
|
171
|
+
console.log('[ScriptMonitor] Script src set to:', value);
|
|
172
|
+
}
|
|
173
|
+
return originalSetAttribute.call(element, name, value);
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return element;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const originalEval = state.originalEval;
|
|
181
|
+
window.eval = function(code) {
|
|
182
|
+
console.log('[ScriptMonitor] eval() called with code:',
|
|
183
|
+
typeof code === 'string' ? code.substring(0, 100) + '...' : code);
|
|
184
|
+
return originalEval.call(window, code);
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const originalFunction = state.originalFunction;
|
|
188
|
+
window.Function = function(...args) {
|
|
189
|
+
console.log('[ScriptMonitor] Function() constructor called with args:', args);
|
|
190
|
+
return originalFunction.apply(this, args);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
window.__getDynamicScripts = function() {
|
|
194
|
+
return dynamicScripts;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
console.log('[ScriptMonitor] Dynamic script monitoring enabled');
|
|
198
|
+
})();
|
|
199
|
+
`;r?.persistent?(await i.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:a}),e.info(`Dynamic script monitoring enabled (persistent)`)):(await i.cdpSession.send(`Runtime.evaluate`,{expression:a}),e.info(`Dynamic script monitoring enabled`))}async function N(t){let n=j(t);if(!n.cdpSession)return{dynamicScriptsCleared:0};try{let e=(await n.cdpSession.send(`Runtime.evaluate`,{expression:`
|
|
200
|
+
(() => {
|
|
201
|
+
const store = Array.isArray(window.__dynamicScripts)
|
|
202
|
+
? window.__dynamicScripts
|
|
203
|
+
: (typeof window.__getDynamicScripts === 'function'
|
|
204
|
+
? window.__getDynamicScripts()
|
|
205
|
+
: null);
|
|
206
|
+
const dynamicScriptsCleared = Array.isArray(store) ? store.length : 0;
|
|
207
|
+
if (Array.isArray(store)) {
|
|
208
|
+
store.length = 0;
|
|
209
|
+
}
|
|
210
|
+
return { dynamicScriptsCleared };
|
|
211
|
+
})()
|
|
212
|
+
`,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`dynamicScriptsCleared`in e&&typeof e.dynamicScriptsCleared==`number`?e:{dynamicScriptsCleared:0}}catch(t){return e.error(`Failed to clear dynamic script buffer:`,t),{dynamicScriptsCleared:0}}}async function P(t){let n=j(t);if(!n.cdpSession)return{scriptMonitorReset:!1};try{let e=(await n.cdpSession.send(`Runtime.evaluate`,{expression:`
|
|
213
|
+
(() => {
|
|
214
|
+
const state = window.__dynamicScriptMonitorState;
|
|
215
|
+
let scriptMonitorReset = false;
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
if (state && state.observer && typeof state.observer.disconnect === 'function') {
|
|
219
|
+
state.observer.disconnect();
|
|
220
|
+
state.observer = null;
|
|
221
|
+
scriptMonitorReset = true;
|
|
222
|
+
}
|
|
223
|
+
} catch (_) {}
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
if (state && state.originalCreateElement) {
|
|
227
|
+
document.createElement = state.originalCreateElement;
|
|
228
|
+
scriptMonitorReset = true;
|
|
229
|
+
}
|
|
230
|
+
} catch (_) {}
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
if (state && state.originalEval) {
|
|
234
|
+
window.eval = state.originalEval;
|
|
235
|
+
scriptMonitorReset = true;
|
|
236
|
+
}
|
|
237
|
+
} catch (_) {}
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
if (state && state.originalFunction) {
|
|
241
|
+
window.Function = state.originalFunction;
|
|
242
|
+
scriptMonitorReset = true;
|
|
243
|
+
}
|
|
244
|
+
} catch (_) {}
|
|
245
|
+
|
|
246
|
+
if (Array.isArray(window.__dynamicScripts)) {
|
|
247
|
+
window.__dynamicScripts.length = 0;
|
|
248
|
+
}
|
|
249
|
+
delete window.__getDynamicScripts;
|
|
250
|
+
window.__dynamicScriptMonitorInstalled = false;
|
|
251
|
+
|
|
252
|
+
return { scriptMonitorReset };
|
|
253
|
+
})()
|
|
254
|
+
`,returnByValue:!0})).result?.value;return typeof e==`object`&&e&&`scriptMonitorReset`in e&&typeof e.scriptMonitorReset==`boolean`?e:{scriptMonitorReset:!1}}catch(t){return e.error(`Failed to reset dynamic script monitoring:`,t),{scriptMonitorReset:!1}}}async function F(t){let r=j(t);if(!r.cdpSession)throw new n(`CDP session not initialized`);try{let e=(await r.cdpSession.send(`Runtime.evaluate`,{expression:`window.__getDynamicScripts ? window.__getDynamicScripts() : []`,returnByValue:!0})).result?.value;return Array.isArray(e)?e:[]}catch(t){return e.error(`Failed to get dynamic scripts:`,t),[]}}async function I(t,r,i){let a=j(t);if(!a.cdpSession)throw new n(`CDP session not initialized`);let o=`
|
|
255
|
+
(function() {
|
|
256
|
+
const originalFunc = window.${r};
|
|
257
|
+
if (typeof originalFunc !== 'function') {
|
|
258
|
+
console.error('[Tracer] ${r} is not a function');
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
window.${r} = new Proxy(originalFunc, {
|
|
263
|
+
apply: function(target, thisArg, args) {
|
|
264
|
+
console.log('[Tracer] ${r} called with args:', args);
|
|
265
|
+
const startTime = performance.now();
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
const result = target.apply(thisArg, args);
|
|
269
|
+
const endTime = performance.now();
|
|
270
|
+
console.log('[Tracer] ${r} returned:', result, 'Time:', (endTime - startTime).toFixed(2), 'ms');
|
|
271
|
+
return result;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
console.error('[Tracer] ${r} threw error:', error);
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
console.log('[Tracer] ${r} is now being traced');
|
|
280
|
+
})();
|
|
281
|
+
`;i?.persistent?(await a.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:o}),e.info(`Function tracer injected for: ${r} (persistent)`)):(await a.cdpSession.send(`Runtime.evaluate`,{expression:o}),e.info(`Function tracer injected for: ${r}`))}async function L(t,r,i,a){let o=j(t);if(!o.cdpSession)throw new n(`CDP session not initialized`);let s=`
|
|
282
|
+
(function() {
|
|
283
|
+
const obj = ${r};
|
|
284
|
+
if (!obj) {
|
|
285
|
+
console.error('[Watcher] Object not found: ${r}');
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let value = obj.${i};
|
|
290
|
+
|
|
291
|
+
Object.defineProperty(obj, '${i}', {
|
|
292
|
+
get: function() {
|
|
293
|
+
console.log('[Watcher] ${r}.${i} accessed, value:', value);
|
|
294
|
+
return value;
|
|
295
|
+
},
|
|
296
|
+
set: function(newValue) {
|
|
297
|
+
console.log('[Watcher] ${r}.${i} changed from', value, 'to', newValue);
|
|
298
|
+
value = newValue;
|
|
299
|
+
},
|
|
300
|
+
enumerable: true,
|
|
301
|
+
configurable: true
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
console.log('[Watcher] Property watcher installed for ${r}.${i}');
|
|
305
|
+
})();
|
|
306
|
+
`;a?.persistent?(await o.cdpSession.send(`Page.addScriptToEvaluateOnNewDocument`,{source:s}),e.info(`Property watcher injected for: ${r}.${i} (persistent)`)):(await o.cdpSession.send(`Runtime.evaluate`,{expression:s}),e.info(`Property watcher injected for: ${r}.${i}`))}function R(e){return e}async function z(n,r,i,a){let o=R(n);o.cdpSession=r,o.usingManagedTargetSession=i,o.lastEnableOptions={...a},o.cdpSession.on(`disconnected`,()=>{e.warn(`ConsoleMonitor CDP session disconnected`),o.cdpSession=null,o.networkMonitor=null,o.usingManagedTargetSession=!1}),await H(o.cdpSession,`Runtime.enable`,{},5e3),await H(o.cdpSession,`Console.enable`,{},5e3),o.cdpSession.on(`Runtime.consoleAPICalled`,t=>{let n=t.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],r={type:t.type,text:t.args.map(e=>o.formatRemoteObject(e)).join(` `),args:t.args.map(e=>o.extractValue(e)),timestamp:t.timestamp,stackTrace:n,url:n[0]?.url,lineNumber:n[0]?.lineNumber,columnNumber:n[0]?.columnNumber};o.messages.push(r),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2))),e.debug(`Console ${t.type}: ${r.text}`)}),o.cdpSession.on(`Console.messageAdded`,e=>{let t=e.message,n={type:t.level||`log`,text:t.text,timestamp:Date.now(),url:t.url,lineNumber:t.line,columnNumber:t.column};o.messages.push(n),o.messages.length>o.MAX_MESSAGES&&(o.messages=o.messages.slice(-Math.floor(o.MAX_MESSAGES/2)))}),a?.enableExceptions!==!1&&o.cdpSession.on(`Runtime.exceptionThrown`,t=>{let n=t.exceptionDetails,r=n.stackTrace?.callFrames?.map(e=>({functionName:e.functionName||`(anonymous)`,url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber}))||[],i={text:n.exception?.description||n.text,exceptionId:n.exceptionId,timestamp:Date.now(),stackTrace:r,url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,scriptId:n.scriptId};o.exceptions.push(i),o.exceptions.length>o.MAX_EXCEPTIONS&&(o.exceptions=o.exceptions.slice(-Math.floor(o.MAX_EXCEPTIONS/2))),e.error(`Exception thrown: ${i.text}`,{url:i.url,line:i.lineNumber})}),a?.enableNetwork&&(o.networkMonitor=o.getManagedTargetNetworkMonitor?.()??new t(o.cdpSession),await o.networkMonitor.enable()),e.info(`ConsoleMonitor enabled`,{network:a?.enableNetwork||!1,exceptions:a?.enableExceptions!==!1})}async function B(t,n){let r=R(t);if(r.playwrightConsoleHandler){n?.enableNetwork&&!r.playwrightNetworkMonitor&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor Playwright session`));return}let a=r.playwrightPage;r.playwrightConsoleHandler=e=>{let t={type:e.type()||`log`,text:e.text(),timestamp:Date.now()};r.messages.push(t),r.messages.length>r.MAX_MESSAGES&&(r.messages=r.messages.slice(-Math.floor(r.MAX_MESSAGES/2)))},a.on(`console`,r.playwrightConsoleHandler),n?.enableExceptions!==!1&&(r.playwrightErrorHandler=e=>{let t={text:e.message,exceptionId:Date.now(),timestamp:Date.now()};r.exceptions.push(t),r.exceptions.length>r.MAX_EXCEPTIONS&&(r.exceptions=r.exceptions.slice(-Math.floor(r.MAX_EXCEPTIONS/2)))},a.on(`pageerror`,r.playwrightErrorHandler)),n?.enableNetwork&&(r.playwrightNetworkMonitor=new i(r.playwrightPage),await r.playwrightNetworkMonitor.enable()),e.info(`ConsoleMonitor enabled (Playwright/camoufox mode)`,{network:n?.enableNetwork||!1})}async function V(t){let n=R(t);if(n.playwrightPage){let e=n.playwrightPage;if(n.playwrightConsoleHandler){try{e.off(`console`,n.playwrightConsoleHandler)}catch{}n.playwrightConsoleHandler=null}if(n.playwrightErrorHandler){try{e.off(`pageerror`,n.playwrightErrorHandler)}catch{}n.playwrightErrorHandler=null}}if(n.playwrightNetworkMonitor&&=(await n.playwrightNetworkMonitor.disable(),null),n.cdpSession){n.networkMonitor&&=(await n.networkMonitor.disable(),null);try{await n.cdpSession.send(`Console.disable`)}catch(t){e.warn(`Failed to disable Console domain:`,t)}try{await n.cdpSession.send(`Runtime.disable`)}catch(t){e.warn(`Failed to disable Runtime domain:`,t)}if(n.usingManagedTargetSession)e.debug(`ConsoleMonitor released managed target session without detaching target`);else try{await n.cdpSession.detach()}catch(t){e.warn(`Failed to detach ConsoleMonitor CDP session:`,t)}n.cdpSession=null,n.usingManagedTargetSession=!1,e.info(`ConsoleMonitor disabled`)}}async function H(e,t,n,r=3e4){return Promise.race([e.send(t,n),new Promise((e,n)=>setTimeout(()=>n(Error(`CDP ${t} timed out after ${r}ms`)),r))])}var U=class{collector;cdpSession=null;networkMonitor=null;fetchInterceptor=null;playwrightNetworkMonitor=null;playwrightPage=null;usingManagedTargetSession=!1;contextSwitchPending=!1;playwrightConsoleHandler=null;playwrightErrorHandler=null;messages=[];MAX_MESSAGES=1e3;exceptions=[];MAX_EXCEPTIONS=500;MAX_INJECTED_DYNAMIC_SCRIPTS=500;MAX_OBJECT_CACHE_SIZE=1e3;objectCache=new Map;initPromise;lastEnableOptions={};constructor(e){this.collector=e,this.touchSplitMembersForTypeCheck()}touchSplitMembersForTypeCheck(){this.MAX_INJECTED_DYNAMIC_SCRIPTS,this.MAX_OBJECT_CACHE_SIZE,this.clearDynamicScriptBuffer,this.resetDynamicScriptMonitoring,this.usingManagedTargetSession,this.playwrightErrorHandler,this.messages,this.MAX_MESSAGES,this.exceptions,this.MAX_EXCEPTIONS,this.formatRemoteObject,this.extractValue}setPlaywrightPage(e){this.playwrightPage=e,this.playwrightNetworkMonitor?.setPage(e)}clearPlaywrightPage(){this.playwrightPage=null,this.contextSwitchPending=!1,this.playwrightConsoleHandler=null,this.playwrightErrorHandler=null,this.playwrightNetworkMonitor?.setPage(null),this.playwrightNetworkMonitor=null}getManagedTargetSession(){return this.collector.getAttachedTargetSession?.()??null}getManagedTargetNetworkMonitor(){return this.collector.getBrowserTargetSessionManager?.()??null}async createCdpSession(){let e=this.getManagedTargetSession();if(e)return{session:e,managed:!0};let t=await this.collector.getActivePage();return{session:await Promise.race([t.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),managed:!1}}markContextChanged(){!this.cdpSession&&!this.playwrightPage&&!this.networkMonitor&&!this.playwrightNetworkMonitor&&!this.fetchInterceptor||(this.contextSwitchPending=!0,this.clearLogs(),this.clearExceptions(),this.networkMonitor?.persistsAcrossContextSwitches?.()||this.clearNetworkRecords(),this.clearObjectCache(),e.info(`ConsoleMonitor marked stale after active context switch`))}async enable(e){if(this.contextSwitchPending&&await this.disable(),this.initPromise){await this.initPromise,await this.applyPostEnableOptions(e);return}this.initPromise=this.doEnable(e);try{await this.initPromise}finally{this.initPromise=void 0}}async doEnable(n){if(this.playwrightPage)return this.lastEnableOptions={...n},B(this,n);if(this.cdpSession){n?.enableNetwork&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new t(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`));return}let{session:r,managed:i}=await this.createCdpSession();await z(this,r,i,n)}async applyPostEnableOptions(n){if(n?.enableNetwork){if(this.lastEnableOptions={...this.lastEnableOptions,...n},this.playwrightPage&&this.playwrightConsoleHandler&&!this.playwrightNetworkMonitor){await B(this,n);return}this.cdpSession&&!this.networkMonitor&&(this.networkMonitor=this.getManagedTargetNetworkMonitor()??new t(this.cdpSession),await this.networkMonitor.enable(),e.info(`Network monitoring added to existing ConsoleMonitor session`))}}async disable(){try{this.cdpSession&&this.fetchInterceptor&&(await this.fetchInterceptor.disable(),this.fetchInterceptor=null),await V(this)}finally{this.fetchInterceptor=null,this.initPromise=void 0,this.contextSwitchPending=!1,this.objectCache.clear()}}async ensureSession(){if(this.contextSwitchPending){e.info(`ConsoleMonitor context switched, rebinding on demand...`);let t={...this.lastEnableOptions};await this.disable(),await this.enable(t);return}if(!this.cdpSession&&!this.playwrightPage){e.info(`ConsoleMonitor CDP session lost, reinitializing...`),await this.enable(this.lastEnableOptions);return}if(this.cdpSession)try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{e.warn(`ConsoleMonitor CDP session unresponsive (zombie), reinitializing...`),this.cdpSession=null,this.networkMonitor=null,this.fetchInterceptor=null,this.usingManagedTargetSession=!1,await this.enable(this.lastEnableOptions)}}isSessionActive(){return!this.contextSwitchPending&&(this.cdpSession!==null||this.playwrightPage!==null)}getLogs(e){return s(this,e)}async execute(t){await this.ensureSession();try{let n=await H(this.cdpSession,`Runtime.evaluate`,{expression:t,returnByValue:!0});if(n.exceptionDetails)throw e.error(`Console execute error:`,n.exceptionDetails),Error(n.exceptionDetails.text);return e.info(`Console expression executed`),n.result.value}catch(t){throw e.error(`Console execute failed:`,t),t}}clearLogs(){c(this)}getStats(){return l(this)}async close(){try{await this.disable()}finally{this.initPromise=void 0,this.objectCache.clear()}}isNetworkEnabled(){return m(this)}getNetworkStatus(){return h(this)}getNetworkRequests(e){return g(this,e)}getNetworkResponses(e){return _(this,e)}getNetworkActivity(e){return v(this,e)}async getResponseBody(e){return y(this,e)}async getAllJavaScriptResponses(){return b(this)}clearNetworkRecords(){x(this)}async clearInjectedBuffers(){return S(this)}async resetInjectedInterceptors(){return C(this)}getNetworkStats(){return w(this)}async injectXHRInterceptor(e){return T(this,e)}async injectFetchInterceptor(e){return E(this,e)}async getXHRRequests(){return D(this)}async getFetchRequests(){return O(this)}getExceptions(e){return u(this,e)}clearExceptions(){d(this)}async inspectObject(e){return k(this,e)}clearObjectCache(){A(this)}async enableDynamicScriptMonitoring(e){return M(this,e)}async clearDynamicScriptBuffer(){return N(this)}async resetDynamicScriptMonitoring(){return P(this)}async getDynamicScripts(){return F(this)}async injectFunctionTracer(e,t){return I(this,e,t)}async injectPropertyWatcher(e,t,n){return L(this,e,t,n)}async enableFetchIntercept(e){if(await this.ensureSession(),!this.cdpSession)throw Error(`No CDP session available for Fetch interception`);return this.fetchInterceptor||=new a(this.cdpSession),this.fetchInterceptor.enable(e)}async disableFetchIntercept(){if(!this.fetchInterceptor)return{removedRules:0};let e=await this.fetchInterceptor.disable();return this.fetchInterceptor=null,e}async removeFetchInterceptRule(e){if(!this.fetchInterceptor)return!1;let t=await this.fetchInterceptor.removeRule(e);return this.fetchInterceptor.isEnabled()||(this.fetchInterceptor=null),t}getFetchInterceptStatus(){return this.fetchInterceptor?this.fetchInterceptor.listRules():{enabled:!1,rules:[],totalHits:0}}formatRemoteObject(e){return e.value===void 0?e.description?e.description:e.type===`undefined`?`undefined`:e.type===`object`&&e.subtype===`null`?`null`:`[${e.type}]`:String(e.value)}extractValue(e){if(e.value!==void 0)return e.value;if(e.type!==`undefined`)return e.type===`object`&&e.subtype===`null`?null:e.objectId?{__objectId:e.objectId,__type:e.type,__description:e.description}:e.description||`[${e.type}]`}};export{U as ConsoleMonitor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import n from"koffi";var r=e({KERN:()=>i,SM:()=>l,VM_FLAGS:()=>c,VM_PROT:()=>s,VM_REGION_BASIC_INFO_64:()=>9,VM_REGION_BASIC_INFO_COUNT_64:()=>9,dyldGetImageHeader:()=>O,dyldGetImageName:()=>D,dyldImageCount:()=>E,isDarwin:()=>f,isKoffiAvailableOnDarwin:()=>p,kernReturnName:()=>o,machPortDeallocate:()=>_,machTaskSelf:()=>h,machVmAllocate:()=>S,machVmDeallocate:()=>C,machVmProtect:()=>x,machVmReadOverwrite:()=>v,machVmRegion:()=>b,machVmWrite:()=>y,taskForPid:()=>g,taskResume:()=>T,taskSuspend:()=>w});const i={SUCCESS:0,INVALID_ADDRESS:1,PROTECTION_FAILURE:2,NO_SPACE:3,INVALID_ARGUMENT:4,FAILURE:5,RESOURCE_SHORTAGE:6,NOT_RECEIVER:7,NO_ACCESS:8,MEMORY_FAILURE:9,MEMORY_ERROR:10,ALREADY_IN_SET:11,NOT_IN_SET:12,NAME_EXISTS:13,ABORTED:14,INVALID_NAME:15,INVALID_TASK:16,INVALID_RIGHT:17,INVALID_VALUE:18,UREFS_OVERFLOW:19,INVALID_CAPABILITY:20,RIGHT_EXISTS:21,INVALID_HOST:22,MEMORY_PRESENT:23,MEMORY_DATA_MOVED:24,MEMORY_RESTART_COPY:25,INVALID_PROCESSOR_SET:26,POLICY_LIMIT:27,INVALID_POLICY:28,INVALID_OBJECT:29,ALREADY_WAITING:30,DEFAULT_SET:31,EXCEPTION_PROTECTED:32,INVALID_LEDGER:33,INVALID_MEMORY_CONTROL:34,INVALID_SECURITY:35,NOT_DEPRESSED:36,TERMINATED:37,LOCK_SET_DESTROYED:38,LOCK_UNSTABLE:39,LOCK_OWNED:40,LOCK_OWNED_SELF:41,SEMAPHORE_DESTROYED:42,RPC_SERVER_TERMINATED:43,RPC_TERMINATE_ORPHAN:44,RPC_CONTINUE_ORPHAN:45,NOT_SUPPORTED:46,NODE_DOWN:47,NOT_WAITING:48,OPERATION_TIMED_OUT:49,CODESIGN_ERROR:50,POLICY_STATIC:51},a={[i.SUCCESS]:`KERN_SUCCESS`,[i.INVALID_ADDRESS]:`KERN_INVALID_ADDRESS`,[i.PROTECTION_FAILURE]:`KERN_PROTECTION_FAILURE`,[i.NO_SPACE]:`KERN_NO_SPACE`,[i.INVALID_ARGUMENT]:`KERN_INVALID_ARGUMENT`,[i.FAILURE]:`KERN_FAILURE`,[i.NO_ACCESS]:`KERN_NO_ACCESS`,[i.INVALID_TASK]:`KERN_INVALID_TASK`,[i.INVALID_RIGHT]:`KERN_INVALID_RIGHT`,[i.CODESIGN_ERROR]:`KERN_CODESIGN_ERROR`};function o(e){return a[e]??`KERN_UNKNOWN(${e})`}const s={NONE:0,READ:1,WRITE:2,EXECUTE:4,ALL:7},c={FIXED:0,ANYWHERE:1,PURGABLE:2,RANDOM_ADDR:8,OVERWRITE:16384},l={COW:1,PRIVATE:2,EMPTY:3,SHARED:4,TRUESHARED:5,PRIVATE_ALIASED:6,SHARED_ALIASED:7,LARGE_PAGE:8};let u=null,d=null;function f(){return process.platform===`darwin`}function p(){if(d!==null)return d;try{return n.load(`/usr/lib/libSystem.B.dylib`).unload(),d=!0,!0}catch{return d=!1,!1}}function m(){return u||(u=n.load(`/usr/lib/libSystem.B.dylib`),t.debug(`Loaded libSystem.B.dylib via koffi`)),u}function h(){return m().func(`uint32 mach_task_self()`)()}function g(e,t){let n=m().func(`int32 task_for_pid(uint32, int32, _Out_ uint32 *)`),r=Buffer.alloc(4);return{kr:n(e,t,r),task:r.readUInt32LE(0)}}function _(e,t){return m().func(`int32 mach_port_deallocate(uint32, uint32)`)(e,t)}function v(e,t,n){let r=m().func(`int32 mach_vm_read_overwrite(uint32, uint64, uint64, _Out_ uint8_t *, uint64, _Out_ uint64 *)`),i=Buffer.alloc(n),a=Buffer.alloc(8);return{kr:r(e,t,BigInt(n),i,BigInt(n),a),data:i,outsize:a.readBigUInt64LE(0)}}function y(e,t,n){return m().func(`int32 mach_vm_write(uint32, uint64, uint8_t *, uint32)`)(e,t,n,n.length)}function b(e,t){let n=m().func(`int32 mach_vm_region(uint32, _Inout_ uint64 *, _Out_ uint64 *, int32, _Out_ uint8_t *, _Inout_ uint32 *, _Out_ uint32 *)`),r=Buffer.alloc(8);r.writeBigUInt64LE(t);let i=Buffer.alloc(8),a=Buffer.alloc(36),o=Buffer.alloc(4);o.writeUInt32LE(9);let s=n(e,r,i,9,a,o,Buffer.alloc(4)),c={protection:a.readUInt32LE(0),max_protection:a.readUInt32LE(4),inheritance:a.readUInt32LE(8),shared:a.readUInt32LE(12)!==0,reserved:a.readUInt32LE(16)!==0,offset:a.readBigUInt64LE(20),behavior:a.readUInt32LE(28),user_wired_count:a.readUInt32LE(32)};return{kr:s,address:r.readBigUInt64LE(0),size:i.readBigUInt64LE(0),info:c}}function x(e,t,n,r,i){return m().func(`int32 mach_vm_protect(uint32, uint64, uint64, int32, int32)`)(e,t,n,+!!r,i)}function S(e,t,n){let r=m().func(`int32 mach_vm_allocate(uint32, _Inout_ uint64 *, uint64, int32)`),i=Buffer.alloc(8);return i.writeBigUInt64LE(0n),{kr:r(e,i,t,n),address:i.readBigUInt64LE(0)}}function C(e,t,n){return m().func(`int32 mach_vm_deallocate(uint32, uint64, uint64)`)(e,t,n)}function w(e){return m().func(`int32 task_suspend(uint32)`)(e)}function T(e){return m().func(`int32 task_resume(uint32)`)(e)}function E(){return m().func(`uint32 _dyld_image_count()`)()}function D(e){let t=m().func(`const char * _dyld_get_image_name(uint32)`)(e);return t?String(t):``}function O(e){let t=m().func(`void * _dyld_get_image_header(uint32)`);return BigInt(t(e))}export{v as _,s as a,g as b,E as c,o as d,_ as f,x as g,C as h,c as i,f as l,S as m,i as n,O as o,h as p,l as r,D as s,r as t,p as u,b as v,y};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{At as t,Mt as n,jt as r,tr as i}from"./constants-DMv3svps.mjs";import{i as a}from"./outputPaths-D2ddHrOJ.mjs";import{n as o,r as s}from"./artifacts-D-4pSS_N.mjs";import{mkdirSync as c,promises as l,readFileSync as u,writeFileSync as d}from"node:fs";import{join as f,relative as p,resolve as m}from"node:path";import{gunzipSync as h,gzip as g}from"node:zlib";import{promisify as _}from"node:util";const v=/^data:([a-zA-Z0-9/+.-]+);base64,/;function y(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function b(e){return`_offload`in e}function x(e,t,n){c(n,{recursive:!0});let r=m(n,`offload-${new Date().toISOString().replace(/[:.]/g,`-`).replace(`T`,`_`).slice(0,19)}-${Math.random().toString(36).substring(2,8)}.${t?`bin`:`txt`}`),i=t?e.match(v):null;if(i){let t=e.slice(i[0].length);d(r,Buffer.from(t,`base64`))}else d(r,e,`utf8`);return p(a(),r).replace(/\\/g,`/`)}function S(t,n){let r=t.match(v)?.[1],i=t.slice(0,128),a=``;if(n.writeFile)try{a=x(t,r,n.outputDir)}catch(t){e.warn(`[sanitizeForCache] Failed to offload field to disk: ${String(t)}`)}return{_offload:{type:`file`,path:a,size:y(Buffer.byteLength(t,`utf8`)),...r?{mimeType:r}:{},sample:i}}}function C(e,t){return v.test(e)||e.length>t}function w(e,t,n){if(typeof e==`string`)return C(e,t.threshold)?S(e,t):e;if(typeof e!=`object`||!e||b(e)||n.has(e))return e;if(n.add(e),Array.isArray(e)){let r=!1,i=e.map(e=>{let i=w(e,t,n);return i!==e&&(r=!0),i});return n.delete(e),r?i:e}let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=w(o,t,n);e!==o&&(r=!0),i[a]=e}return n.delete(e),r?i:e}function T(e,t={}){return w(e,{threshold:t.threshold??i,outputDir:t.outputDir??o(`offloaded`),writeFile:t.writeFile??!0},new WeakSet)}function E(){return s()}const D=_(g),O=1024;var k=class i{static instance;cache=new Map;cleanupInterval=null;persistDir;metadataPath;persistenceEnabled=!0;disposed=!1;DEFAULT_TTL=t;MAX_TTL=r;MAX_CACHE_SIZE=100;MAX_TOTAL_MEMORY_BYTES=50*1024*1024;AUTO_EXTEND_ON_ACCESS=!0;EXTEND_DURATION=900*1e3;serializationMemo=new WeakMap;metrics={diskWriteCount:0,diskWriteFailCount:0,diskReadCount:0,diskReadFailCount:0,diskReadLazyCount:0,gzipCompressCount:0,gzipDecompressCount:0,evictedBySizeCount:0,evictedByLRUCount:0,totalBytesWritten:0,totalBytesRead:0};constructor(){this.persistDir=f(o(`tmp`),`detailed-data`),this.metadataPath=f(this.persistDir,`.metadata.jsonl`),this.cleanupInterval=setInterval(()=>this.cleanup(),300*1e3),typeof this.cleanupInterval==`object`&&`unref`in this.cleanupInterval&&this.cleanupInterval.unref(),this.init()}static getInstance(){return this.instance||=new i,this.instance}shutdown(){this.disposed=!0,this.cleanupInterval&&=(clearInterval(this.cleanupInterval),null),this.cache.clear(),i.instance=void 0}async init(){try{if(await l.mkdir(this.persistDir,{recursive:!0}),this.disposed||(await this.loadPersistedEntries(),this.disposed))return;await this.cleanupExpired()}catch(t){if(this.disposed)return;e.warn(`Failed to initialize persistence, falling back to memory-only`,t),this.persistenceEnabled=!1}}async loadPersistedEntries(){try{let t=await l.readFile(this.metadataPath,`utf-8`);if(this.disposed)return;let n=t.trim().split(`
|
|
2
|
+
`).filter(Boolean),r=Date.now();for(let e of n){if(this.disposed)return;let t=JSON.parse(e);t.expiresAt>r&&this.cache.set(t.detailId,{data:null,expiresAt:t.expiresAt,createdAt:t.createdAt,lastAccessedAt:r,accessCount:0,size:t.size,persistPath:f(this.persistDir,`${t.detailId}${t.compressed?`.gz`:`.json`}`),compressed:t.compressed})}this.disposed||e.info(`Loaded ${this.cache.size} persisted detail entries`)}catch(t){!this.disposed&&t.code!==`ENOENT`&&e.warn(`Failed to load persisted metadata`,t)}}async cleanupExpired(){if(this.disposed||!this.persistenceEnabled)return;let t=Date.now(),n=[];for(let[e,r]of this.cache.entries())if(r.expiresAt<=t&&(n.push(e),r.persistPath&&(await l.unlink(r.persistPath).catch(()=>{}),this.disposed)))return;n.length>0&&(n.forEach(e=>this.cache.delete(e)),await this.rebuildMetadata(),this.disposed||e.info(`Cleaned up ${n.length} expired detail entries`))}async rebuildMetadata(){if(this.disposed||!this.persistenceEnabled)return;let e=[];for(let[t,n]of this.cache.entries())if(n.persistPath){let r={detailId:t,expiresAt:n.expiresAt,createdAt:n.createdAt,size:n.size};e.push(JSON.stringify(r))}this.disposed||await l.writeFile(this.metadataPath,e.join(`
|
|
3
|
+
`)+`
|
|
4
|
+
`).catch(()=>{})}serializeWithMemo(e){if(typeof e==`object`&&e){let t=this.serializationMemo.get(e);if(t)return t}let t=JSON.stringify(e),n={json:t,size:t.length};return typeof e==`object`&&e&&this.serializationMemo.set(e,n),n}isRecord(e){return typeof e==`object`&&!!e}readPathSegment(e,t){return Object(e)[t]}smartHandle(t,r=n){if(t==null||typeof t!=`object`&&typeof t!=`string`||typeof t==`string`&&t.length<=r)return t;let{json:i,size:a}=this.serializeWithMemo(t);return a<=r?t:(e.info(`Data too large (${(a/1024).toFixed(1)}KB), returning summary with detailId`),this.createDetailedResponseWithSize(t,i,a))}createDetailedResponseWithSize(e,t,n){let r=this.storeWithSize(e,n);return{summary:this.generateSummaryFromJson(e,t,n),detailId:r,hint:`Data too large. Use get_detailed_data("${r}") to retrieve full data, or get_detailed_data("${r}", path="key.subkey") for specific part.`,expiresAt:Date.now()+this.DEFAULT_TTL}}store(e,t){let{size:n}=this.serializeWithMemo(e);return this.storeWithSize(e,n,t)}storeWithSize(t,n,r){this.cache.size>=this.MAX_CACHE_SIZE&&this.evictLRU();let i=T(t),a=i===t?n:this.serializeWithMemo(i).size,o=`detail_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,s=Date.now(),c=r||this.DEFAULT_TTL,l=s+c,u=a>O,d=this.persistenceEnabled?f(this.persistDir,`${o}${u?`.gz`:`.json`}`):void 0,p={data:i,expiresAt:l,createdAt:s,lastAccessedAt:s,accessCount:0,size:a,persistPath:d,compressed:u};return this.cache.set(o,p),d&&this.persistToDisk(d,i,u).then(e=>(this.metrics.diskWriteCount++,this.metrics.totalBytesWritten+=e,this.appendMetadata({detailId:o,expiresAt:l,createdAt:s,size:a,compressed:u}))).catch(t=>{this.metrics.diskWriteFailCount++,e.warn(`Failed to persist ${o}`,t)}),e.debug(`Stored detailed data: ${o}, size: ${(a/1024).toFixed(1)}KB, expires in ${c/1e3}s`),o}async appendMetadata(t){try{await l.appendFile(this.metadataPath,JSON.stringify(t)+`
|
|
5
|
+
`)}catch(t){e.warn(`Failed to append metadata`,t)}}retrieve(t,n){let r=this.cache.get(t);if(!r)throw Error(`DetailId not found or expired: ${t}`);let i=Date.now();if(i>r.expiresAt)throw this.cache.delete(t),r.persistPath&&l.unlink(r.persistPath).catch(()=>{}),Error(`DetailId expired: ${t}`);if(r.data===null&&r.persistPath)try{let e=u(r.persistPath);if(r.compressed){let t=h(e);r.data=JSON.parse(t.toString(`utf-8`)),this.metrics.gzipDecompressCount++,this.metrics.totalBytesRead+=t.length}else r.data=JSON.parse(e.toString(`utf-8`)),this.metrics.totalBytesRead+=e.length;this.metrics.diskReadCount++,this.metrics.diskReadLazyCount++}catch(n){throw this.metrics.diskReadFailCount++,e.warn(`Failed to load persisted data for ${t}`,n),Error(`DetailId not found or expired: ${t}`,{cause:n})}return r.lastAccessedAt=i,r.accessCount++,this.AUTO_EXTEND_ON_ACCESS&&r.expiresAt-i<300*1e3&&(r.expiresAt=Math.min(i+this.EXTEND_DURATION,i+this.MAX_TTL),e.debug(`Auto-extended detailId ${t}, new expiry: ${new Date(r.expiresAt).toISOString()}`)),n?this.getByPath(r.data,n):r.data}getByPath(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)throw Error(`Path not found: ${t} (stopped at ${e})`);r=this.readPathSegment(r,e)}return r}generateSummaryFromJson(e,t,n){let r={type:Array.isArray(e)?`array`:typeof e,size:n,sizeKB:(n/1024).toFixed(1)+`KB`,preview:t.substring(0,200)+(n>200?`...`:``)};if(this.isRecord(e)){let t=Object.keys(e);if(r.structure={keys:t.slice(0,50)},Array.isArray(e))r.structure.length=e.length;else{let n=t.filter(t=>typeof e[t]==`function`),i=t.filter(t=>typeof e[t]!=`function`);r.structure.methods=n.slice(0,30),r.structure.properties=i.slice(0,50)}}return r}cleanup(){let t=Date.now(),n=0;for(let[e,r]of this.cache.entries())t>r.expiresAt&&(this.cache.delete(e),n++);n>0&&e.debug(`Cleaned ${n} expired detailed data entries`)}evictLRU(){if(this.cache.size===0)return;let t=this.computeTotalMemory();if(t>this.MAX_TOTAL_MEMORY_BYTES){this.evictBySize(t-this.MAX_TOTAL_MEMORY_BYTES);return}let n=null,r=1/0;for(let[e,t]of this.cache.entries())t.lastAccessedAt<r&&(r=t.lastAccessedAt,n=e);if(n){let t=this.cache.get(n);this.cache.delete(n),this.metrics.evictedByLRUCount++,e.info(`Evicted LRU entry: ${n}, last accessed: ${new Date(t.lastAccessedAt).toISOString()}, access count: ${t.accessCount}`)}}evictBySize(t){let n=Array.from(this.cache.entries()).toSorted((e,t)=>e[1].lastAccessedAt-t[1].lastAccessedAt),r=0;for(let[i,a]of n){if(r>=t)break;this.cache.delete(i),r+=a.size,this.metrics.evictedBySizeCount++,e.info(`Evicted oversized entry: ${i}, freed: ${(a.size/1024).toFixed(1)}KB`)}}computeTotalMemory(){let e=0;for(let t of this.cache.values())e+=t.size;return e}async persistToDisk(e,t,n){let r=JSON.stringify(t);if(n){let t=await D(Buffer.from(r,`utf-8`));return await l.writeFile(e,t),this.metrics.gzipCompressCount++,t.length}return await l.writeFile(e,r,`utf-8`),r.length}extend(t,n){let r=this.cache.get(t);if(!r)throw Error(`DetailId not found: ${t}`);let i=Date.now();if(i>r.expiresAt)throw Error(`DetailId already expired: ${t}`);let a=n||this.EXTEND_DURATION,o=Math.min(r.expiresAt+a,i+this.MAX_TTL);r.expiresAt=o,e.info(`Extended detailId ${t} by ${a/1e3}s, new expiry: ${new Date(o).toISOString()}`)}getStats(){let e=0,t=0,n=0,r=0,i=Array.from(this.cache.values());for(let a of i)e+=a.size,t+=a.accessCount,a.persistPath&&n++,a.compressed&&r++;return{cacheSize:this.cache.size,maxCacheSize:this.MAX_CACHE_SIZE,totalMemoryMB:(e/(1024*1024)).toFixed(2),maxMemoryMB:(this.MAX_TOTAL_MEMORY_BYTES/(1024*1024)).toFixed(0),memoryUtilization:(e/this.MAX_TOTAL_MEMORY_BYTES*100).toFixed(1)+`%`,defaultTTLSeconds:this.DEFAULT_TTL/1e3,maxTTLSeconds:this.MAX_TTL/1e3,totalSizeKB:(e/1024).toFixed(1),avgAccessCount:i.length>0?(t/i.length).toFixed(1):`0`,autoExtendEnabled:this.AUTO_EXTEND_ON_ACCESS,extendDurationSeconds:this.EXTEND_DURATION/1e3,persistence:{enabled:this.persistenceEnabled,persistedCount:n,compressedCount:r,gzipEnabled:!0,gzipThresholdKB:(O/1024).toFixed(1)},metrics:{...this.metrics}}}getDetailedStats(){let e=Date.now(),t=Array.from(this.cache.entries()).map(([t,n])=>({detailId:t,sizeKB:(n.size/1024).toFixed(1),createdAt:new Date(n.createdAt).toISOString(),lastAccessedAt:new Date(n.lastAccessedAt).toISOString(),expiresAt:new Date(n.expiresAt).toISOString(),remainingSeconds:Math.max(0,Math.floor((n.expiresAt-e)/1e3)),accessCount:n.accessCount,isExpired:e>n.expiresAt}));return t.sort((e,t)=>new Date(t.lastAccessedAt).getTime()-new Date(e.lastAccessedAt).getTime()),t}clear(){this.cache.clear(),e.info(`Cleared all detailed data cache`)}};export{T as a,E as i,v as n,y as r,k as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./ToolCatalog-DgmQXdsm.mjs";const t=[`search`,`workflow`,`full`];function n(e){return e.profiles&&e.profiles.length>0?e.profiles:t}function r(t,n){for(let r of t.selectedTools)if(e(r.name)===n)return!0;for(let r of t.activatedToolNames){let i=t.extensionToolsByName.get(r);if(i){if(i.domain===n)return!0;continue}if(e(r)===n)return!0}return!1}function i(e,t){if(r(e,t)){e.enabledDomains.add(t);return}e.enabledDomains.delete(t)}function a(e,t){return n(t).includes(e)}function o(e,t,n=`activate_tools`){if(e.activatedToolNames.has(t.name))return e.enabledDomains.add(t.domain),t.activationSource??=n,t.activatedAt??=new Date().toISOString(),!1;let r=e.registerSingleTool(t.tool);return e.activatedToolNames.add(t.name),e.activatedRegisteredTools.set(t.name,r),t.registeredTool=r,t.activationSource=n,t.activatedAt=new Date().toISOString(),e.enabledDomains.add(t.domain),t.handler&&e.router.addHandlers({[t.name]:t.handler}),!0}function s(e,t,n={}){let r=t.registeredTool??e.activatedRegisteredTools.get(t.name),a=!!r||e.activatedToolNames.has(t.name)||e.activatedRegisteredTools.has(t.name);if(r&&!n.skipRegisteredToolRemoval)try{r.remove()}catch(e){n.onRemoveError?.(e)}return e.router.removeHandler(t.name),e.activatedToolNames.delete(t.name),e.activatedRegisteredTools.delete(t.name),t.registeredTool=void 0,t.activationSource=void 0,t.activatedAt=void 0,n.removeDefinition&&e.extensionToolsByName.delete(t.name),i(e,t.domain),a}export{a as n,s as r,o as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./chunk-
|
|
1
|
+
import{n as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";var n=class n{static instance=null;activeProfile=null;available=null;constructor(){}static getInstance(){return n.instance||=new n,n.instance}isAvailable(){if(this.available!==null)return this.available;try{e.resolve(`fingerprint-generator`),e.resolve(`fingerprint-injector`),this.available=!0}catch{this.available=!1}return this.available}async generateFingerprint(e){if(!this.isAvailable())return t.warn(`fingerprint-generator not installed. Run: pnpm add fingerprint-generator fingerprint-injector`),null;try{let{FingerprintGenerator:n}=await import(`fingerprint-generator`),r=new n,i={};e?.os&&(i.operatingSystems=[{windows:`windows`,macos:`macos`,linux:`linux`}[e.os]??`windows`]),e?.browser&&(i.browsers=[e.browser]),e?.locale&&(i.locales=[e.locale]),e?.screen&&(i.screen=e.screen);let a=r.getFingerprint(i);return this.activeProfile={fingerprint:a.fingerprint,headers:a.headers??{},generatedAt:Date.now(),os:e?.os??`windows`,browser:e?.browser??`chrome`},t.info(`Fingerprint generated for ${this.activeProfile.os}/${this.activeProfile.browser}`),this.activeProfile}catch(e){return t.error(`Failed to generate fingerprint:`,e),null}}async injectFingerprint(e,n){if(!this.isAvailable())throw Error(`fingerprint-injector not installed`);try{let{newInjectedPage:r}=await import(`fingerprint-injector`);await r(e,{fingerprint:`fingerprint`in n?n.fingerprint:n}),t.info(`Fingerprint injected into page`)}catch(e){throw t.error(`Failed to inject fingerprint:`,e),e}}getActiveProfile(){return this.activeProfile}clearProfile(){this.activeProfile=null}static resetInstance(){n.instance=null}};export{n as FingerprintManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{U as e,W as t}from"./constants-DMv3svps.mjs";import{t as n}from"./ToolError-g3rjWzhx.mjs";import{t as r}from"./Win32API-DoP3MMHS.mjs";import{_ as i,a,c as o,d as s,f as c,g as l,h as u,i as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v,v as y,y as b}from"./Win32Debug-DwF8mQGm.mjs";import{randomUUID as x}from"node:crypto";const S=e=>`0x${e.toString(16).toUpperCase()}`;var C=class{breakpoints=new Map;attachedPids=new Set;drAllocation=[!1,!1,!1,!1];async attach(e){if(!this.attachedPids.has(e)){d(e),p(!1),this.attachedPids.add(e);for(let e=0;e<100;e++){let e=u(100);if(!e)break;f(e.processId,e.threadId,h.CONTINUE)}}}async detach(e){for(let[t,n]of this.breakpoints)n.pid===e&&(this.clearDR(e,n.drIndex),this.drAllocation[n.drIndex]=!1,this.breakpoints.delete(t));if(this.attachedPids.has(e)){try{a(e)}catch{}this.attachedPids.delete(e)}}async setBreakpoint(e,t,n,r=4){this.attachedPids.has(e)||await this.attach(e);let i=this.allocateDR(),a=BigInt(t.startsWith(`0x`)?t:`0x${t}`);this.applyDRToAllThreads(e,i,a,n,r,!0);let o={id:x(),pid:e,address:`0x${a.toString(16).toUpperCase()}`,access:n,size:r,enabled:!0,drIndex:i,hitCount:0};return this.breakpoints.set(o.id,o),o}async removeBreakpoint(e){let t=this.breakpoints.get(e);return t?(this.clearDR(t.pid,t.drIndex),this.drAllocation[t.drIndex]=!1,this.breakpoints.delete(e),!0):!1}listBreakpoints(){return Array.from(this.breakpoints.values()).map(e=>({id:e.id,address:e.address,access:e.access,size:e.size,enabled:e.enabled,hitCount:e.hitCount,lastHit:e.lastHit}))}async waitForHit(t){let n=t??e,r=Date.now()+n;for(;Date.now()<r;){let e=Math.max(100,r-Date.now()),t=u(Math.min(e,500));if(t)if(t.exceptionCode===g.SINGLE_STEP){let e=this.processHit(t.threadId,t.processId,t.exceptionAddress);if(f(t.processId,t.threadId,h.CONTINUE),e)return e}else f(t.processId,t.threadId,h.CONTINUE)}return null}async traceAccess(n,r,i,a,o){let s=a??t,c=o??e,l=await this.setBreakpoint(n,r,i),u=[],d=Date.now()+c;for(;u.length<s&&Date.now()<d;){let e=await this.waitForHit(Math.min(1e3,d-Date.now()));e?.breakpointId===l.id&&u.push(e)}return await this.removeBreakpoint(l.id),u}allocateDR(){for(let e=0;e<4;e++)if(!this.drAllocation[e])return this.drAllocation[e]=!0,e;throw new n(`PREREQUISITE`,`All 4 hardware breakpoint registers (DR0-DR3) are in use`)}applyDRToAllThreads(e,t,n,a,u,d){let f=o(e),p={execute:`execute`,write:`write`,readwrite:`readwrite`,read:`read`};for(let e of f){let o;try{o=i(e)}catch{continue}try{m(o);let e=v(o,_.ALL),r=[72,80,88,96];d?e.writeBigUInt64LE(n,r[t]):e.writeBigUInt64LE(0n,r[t]);let i=Array.from(this.breakpoints.values()).filter(e=>e.enabled).map(e=>({drIndex:e.drIndex,enabled:!0,access:p[e.access],size:e.size}));d&&i.push({drIndex:t,enabled:!0,access:p[a],size:u});let f=l(i);e.writeBigUInt64LE(f,112),b(e,{contextFlags:_.ALL}),c(o,e),s(o)}catch{try{s(o)}catch{}}finally{r(o)}}}clearDR(e,t){this.applyDRToAllThreads(e,t,0n,`write`,1,!1)}processHit(e,t,n){let a;try{a=i(e)}catch{return null}try{let n=v(a,_.ALL),r=y(n);for(let[i,o]of this.breakpoints){if(o.pid!==t)continue;let s=1n<<BigInt(o.drIndex);if(r.dr6&s)return o.hitCount++,o.lastHit=Date.now(),n.writeBigUInt64LE(0n,104),c(a,n),{breakpointId:i,address:o.address,accessAddress:o.address,instructionAddress:S(r.rip),threadId:e,accessType:o.access,timestamp:Date.now(),registers:{rax:S(r.rax),rbx:S(r.rbx),rcx:S(r.rcx),rdx:S(r.rdx),rsi:S(r.rsi),rdi:S(r.rdi),rsp:S(r.rsp),rbp:S(r.rbp),r8:S(r.r8),r9:S(r.r9),r10:S(r.r10),r11:S(r.r11),r12:S(r.r12),r13:S(r.r13),r14:S(r.r14),r15:S(r.r15),rip:S(r.rip),rflags:`0x${r.eflags.toString(16).toUpperCase()}`}}}return null}finally{r(a)}}};const w=new C;export{C as HardwareBreakpointEngine,w as hardwareBreakpointEngine};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-
|
|
1
|
+
import{t as e}from"./logger-CCikqqvj.mjs";import{cn as t,ln as n,on as r,sn as i}from"./constants-DMv3svps.mjs";import{t as a}from"./ToolError-g3rjWzhx.mjs";import{b as o,d as s,t as c}from"./Win32API-DoP3MMHS.mjs";import{m as l}from"./Win32Debug-DwF8mQGm.mjs";import u from"koffi";const d={FIXED:1,FREE:2,MOVEABLE:4},f={DEFAULT:1,SHARED:2};let p=null;function m(){let e=u.load(`kernel32.dll`);return{CreateToolhelp32Snapshot:e.func(`CreateToolhelp32Snapshot`,`intptr`,[`uint32`,`uint32`]),Heap32ListFirst:e.func(`Heap32ListFirst`,`bool`,[`intptr`,`_Inout_ uint8_t *`]),Heap32ListNext:e.func(`Heap32ListNext`,`bool`,[`intptr`,`_Inout_ uint8_t *`]),Heap32First:e.func(`Heap32First`,`bool`,[`_Inout_ uint8_t *`,`uint32`,`uintptr_t`]),Heap32Next:e.func(`Heap32Next`,`bool`,[`_Inout_ uint8_t *`]),CloseHandle:e.func(`int CloseHandle(intptr)`),HEAPLIST32_SIZE:36,HEAPENTRY32_SIZE:56}}function h(){return p||=m(),p}const g=[[`0-64B`,0,64],[`64-256B`,64,256],[`256B-1KB`,256,1024],[`1-4KB`,1024,4096],[`4-16KB`,4096,16384],[`16-64KB`,16384,65536],[`64KB-1MB`,65536,1048576],[`>1MB`,1048576,2**53-1]];function _(e){for(let t=0;t<g.length;t++){let n=g[t];if(e>=n[1]&&e<n[2])return t}return g.length-1}var v=class{async enumerateHeaps(e){let t=h(),n=t.CreateToolhelp32Snapshot(l.SNAPHEAPLIST,e);if(n===-1n&&typeof n==`bigint`)throw new a(`RUNTIME`,`Failed to create heap snapshot for PID ${e}`);let i=[];try{let a=Buffer.alloc(t.HEAPLIST32_SIZE);a.writeBigUInt64LE(BigInt(t.HEAPLIST32_SIZE),0);let o=t.Heap32ListFirst(n,a);for(;o;){let s=a.readUInt32LE(8),c=a.readBigUInt64LE(12),l=a.readUInt32LE(20),u=await this.enumerateBlocksInternal(e,c,r);i.push({heapId:`0x${c.toString(16)}`,processId:s,flags:l,isDefault:(l&f.DEFAULT)!==0,blockCount:u.length,totalSize:u.reduce((e,t)=>e+t.size,0)}),a.writeBigUInt64LE(BigInt(t.HEAPLIST32_SIZE),0),o=t.Heap32ListNext(n,a)}}finally{t.CloseHandle(n)}return{heaps:i,stats:this.computeStats(i,[])}}async enumerateBlocks(e,t,n){let i=BigInt(t),a=n?.maxBlocks??r;return this.enumerateBlocksInternal(e,i,a)}async getStats(e){let{heaps:t}=await this.enumerateHeaps(e),n=[];for(let i of t){let t=await this.enumerateBlocksInternal(e,BigInt(i.heapId),r);n.push(...t)}return this.computeStats(t,n)}async detectAnomalies(e){let t=[],{heaps:n}=await this.enumerateHeaps(e);for(let i of n){let n=await this.enumerateBlocksInternal(e,BigInt(i.heapId),r);this.detectSpray(n,i.heapId,t),this.detectSuspiciousSizes(n,i.heapId,t),await this.detectPossibleUaf(e,n,i.heapId,t)}return t}async enumerateBlocksInternal(e,t,n){let r=h(),i=[],a=Buffer.alloc(r.HEAPENTRY32_SIZE);a.writeBigUInt64LE(BigInt(r.HEAPENTRY32_SIZE),0);let o=r.Heap32First(a,e,t);for(;o&&i.length<n;){let e=a.readBigUInt64LE(16),n=Number(a.readBigUInt64LE(24)),s=a.readUInt32LE(32);i.push({address:`0x${e.toString(16)}`,size:n,flags:s,heapId:`0x${t.toString(16)}`,isFree:(s&d.FREE)!==0}),a.writeBigUInt64LE(BigInt(r.HEAPENTRY32_SIZE),0),o=r.Heap32Next(a)}return i}computeStats(e,t){let n=g.map(([e])=>({range:e,count:0,totalBytes:0})),r=0,i=0,a=0,o=2**53-1;for(let e of t){r+=e.size,e.isFree&&(i+=e.size),e.size>a&&(a=e.size),!e.isFree&&e.size<o&&(o=e.size);let t=_(e.size);n[t].count++,n[t].totalBytes+=e.size}return o===2**53-1&&(o=0),r===0&&e.length>0&&(r=e.reduce((e,t)=>e+t.totalSize,0)),{totalHeaps:e.length,totalBlocks:t.length||e.reduce((e,t)=>e+t.blockCount,0),totalSize:r,freeSize:i,usedSize:r-i,largestBlock:a,smallestBlock:o,averageBlockSize:t.length>0?Math.round(r/t.length):0,sizeDistribution:n,fragmentationRatio:r>0?i/r:0}}detectSpray(e,n,r){let a=new Map;for(let t of e){if(t.isFree)continue;let e=Math.round(t.size/i)*i,n=a.get(e)??[];n.push(t),a.set(e,n)}for(let[e,i]of a)i.length>=t&&r.push({type:`heap_spray_pattern`,severity:`high`,address:i[0].address,details:`${i.length} blocks of ~${e} bytes detected — possible heap spray`,heapId:n})}detectSuspiciousSizes(e,t,r){for(let i of e)i.size===0?r.push({type:`suspicious_size`,severity:`medium`,address:i.address,details:`Block with zero size`,heapId:t}):i.size>n&&r.push({type:`suspicious_size`,severity:`medium`,address:i.address,details:`Unusually large block: ${(i.size/(1024*1024)).toFixed(1)} MB`,heapId:t})}async detectPossibleUaf(t,n,r,i){let a=n.filter(e=>e.isFree&&e.size>=8).slice(0,100),l=null;try{l=o(t);for(let e of a){let t=BigInt(e.address),n=s(l,t,8);n&&n.readBigUInt64LE(0)!==0n&&i.push({type:`possible_uaf`,severity:`low`,address:e.address,details:`Free block has non-zero data: 0x${n.readBigUInt64LE(0).toString(16)}`,heapId:r})}}catch(n){e.debug(`UAF check failed for PID ${t}: ${n}`)}finally{l&&c(l)}}};const y=new v;export{v as HeapAnalyzer,y as heapAnalyzer};
|