@jshookmcp/jshook 0.2.8 → 0.3.0

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.
Files changed (162) hide show
  1. package/README.md +36 -5
  2. package/README.zh.md +36 -5
  3. package/dist/{AntiCheatDetector-S8VRj-dD.mjs → AntiCheatDetector-CqGDXmfc.mjs} +160 -54
  4. package/dist/{CodeInjector-4Z3ngPoX.mjs → CodeInjector-BdjRfNx7.mjs} +5 -5
  5. package/dist/ConsoleMonitor-DykL3IAw.mjs +2269 -0
  6. package/dist/{DarwinAPI-B8hg_yhz.mjs → DarwinAPI-ETyy0xyo.mjs} +1 -1
  7. package/dist/DetailedDataManager-HT49OrvF.mjs +217 -0
  8. package/dist/EventBus-DFKvADm3.mjs +141 -0
  9. package/dist/EvidenceGraphBridge-318Oi0Lf.mjs +153 -0
  10. package/dist/{ExtensionManager-D5-bO9D8.mjs → ExtensionManager-BDMsY2Dz.mjs} +27 -13
  11. package/dist/{FingerprintManager-BVxFJL2-.mjs → FingerprintManager-BN4UQWnX.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-DK1yjWkV.mjs → HardwareBreakpoint-Cc2AFq1Y.mjs} +3 -3
  13. package/dist/{HeapAnalyzer-CEbo10xU.mjs → HeapAnalyzer-DruMgsgj.mjs} +21 -21
  14. package/dist/HookGeneratorBuilders.core.generators.storage-CTbB4Lcx.mjs +566 -0
  15. package/dist/InstrumentationSession-DLH0vd-z.mjs +244 -0
  16. package/dist/{MemoryController-DdtnBdD4.mjs → MemoryController-CMtviNW_.mjs} +3 -3
  17. package/dist/{MemoryScanSession-RMixN3bX.mjs → MemoryScanSession-ITgb_NMi.mjs} +81 -78
  18. package/dist/{MemoryScanner-QjK4ld0B.mjs → MemoryScanner-CiL7Z3ey.mjs} +50 -21
  19. package/dist/{NativeMemoryManager.impl-CB6gJ0NM.mjs → NativeMemoryManager.impl-D9Lkovvn.mjs} +20 -56
  20. package/dist/{NativeMemoryManager.utils-BML4q1ry.mjs → NativeMemoryManager.utils-BBlAixF5.mjs} +1 -1
  21. package/dist/{PEAnalyzer-CK0xe0Fs.mjs → PEAnalyzer-DMQ44gen.mjs} +16 -16
  22. package/dist/PageController-BPJNqqBN.mjs +431 -0
  23. package/dist/{PointerChainEngine-Cd73qu5b.mjs → PointerChainEngine-K7wN8Z-w.mjs} +10 -7
  24. package/dist/PrerequisiteError-TuyZIs6n.mjs +20 -0
  25. package/dist/ProcessRegistry-zGg12QbE.mjs +74 -0
  26. package/dist/ResponseBuilder-CJXWmWNw.mjs +143 -0
  27. package/dist/ReverseEvidenceGraph-C02-gXOh.mjs +269 -0
  28. package/dist/ScriptManager-ZuWD-0Jg.mjs +3003 -0
  29. package/dist/{Speedhack-CeF0XmEz.mjs → Speedhack-D-z0umeT.mjs} +2 -2
  30. package/dist/{StructureAnalyzer-D4GkMduU.mjs → StructureAnalyzer-Cav5AVSL.mjs} +9 -6
  31. package/dist/ToolCatalog-5OJdMiF0.mjs +582 -0
  32. package/dist/ToolError-jh9whhMd.mjs +15 -0
  33. package/dist/ToolProbe-DbCFGyrg.mjs +45 -0
  34. package/dist/ToolRegistry-B9krbTtI.mjs +180 -0
  35. package/dist/ToolRouter.policy-BGDAGyeH.mjs +344 -0
  36. package/dist/TraceRecorder-B41Z5XBj.mjs +1286 -0
  37. package/dist/{Win32API-Bc0QnQsN.mjs → Win32API-C2kjj0ze.mjs} +19 -13
  38. package/dist/{Win32Debug-DUHt9XUn.mjs → Win32Debug-CKrGOTpo.mjs} +3 -3
  39. package/dist/WorkflowEngine-DJ6M4opp.mjs +569 -0
  40. package/dist/analysis-BHeJW2Nb.mjs +1234 -0
  41. package/dist/antidebug-BRKeyt27.mjs +1081 -0
  42. package/dist/artifactRetention-CPXkUJXp.mjs +598 -0
  43. package/dist/artifacts-DkfosXH3.mjs +59 -0
  44. package/dist/authorization-schema-DRqyJMSk.mjs +31 -0
  45. package/dist/betterSqlite3-DLSBZodi.mjs +74 -0
  46. package/dist/binary-instrument--V3MAhJ4.mjs +971 -0
  47. package/dist/bind-helpers-ClV34xdn.mjs +42 -0
  48. package/dist/boringssl-inspector-Bo_LOLaS.mjs +180 -0
  49. package/dist/browser-Dx3_S2cG.mjs +4369 -0
  50. package/dist/capabilities-CcHlvWgK.mjs +33 -0
  51. package/dist/concurrency-Drev_Vz9.mjs +41 -0
  52. package/dist/{constants-CCvsN80K.mjs → constants-CDZLOoVv.mjs} +105 -48
  53. package/dist/coordination-DgItD9DL.mjs +259 -0
  54. package/dist/debugger-RS3RSAqs.mjs +1288 -0
  55. package/dist/definitions-BEoYofW5.mjs +47 -0
  56. package/dist/definitions-BRaefg3u.mjs +365 -0
  57. package/dist/definitions-BbkvZkiv.mjs +96 -0
  58. package/dist/definitions-BtWSHJ3o.mjs +17 -0
  59. package/dist/definitions-C1gCHO0i.mjs +43 -0
  60. package/dist/definitions-CDOg_b-l.mjs +138 -0
  61. package/dist/definitions-CVPD9hzZ.mjs +54 -0
  62. package/dist/definitions-Cea8Lgl7.mjs +94 -0
  63. package/dist/definitions-DAgIyjxM.mjs +10 -0
  64. package/dist/definitions-DJA27nsL.mjs +66 -0
  65. package/dist/definitions-DKPFU3LW.mjs +25 -0
  66. package/dist/definitions-DPRpZQ96.mjs +47 -0
  67. package/dist/definitions-DUE5gmdn.mjs +18 -0
  68. package/dist/definitions-DYVjOtxa.mjs +26 -0
  69. package/dist/definitions-DcYLVLCo.mjs +37 -0
  70. package/dist/definitions-Pp5LI2H4.mjs +27 -0
  71. package/dist/definitions-j9KdHVNR.mjs +14 -0
  72. package/dist/definitions-uzkjBwa7.mjs +258 -0
  73. package/dist/definitions-va-AnLuQ.mjs +28 -0
  74. package/dist/encoding-DJeqHmpd.mjs +1079 -0
  75. package/dist/evidence-graph-bridge-DcYizFk2.mjs +136 -0
  76. package/dist/{factory-CibqTNC8.mjs → factory-C90tBff6.mjs} +41 -56
  77. package/dist/flat-target-session-Dgax2Cy3.mjs +29 -0
  78. package/dist/graphql-CoHrhweh.mjs +1197 -0
  79. package/dist/handlers-4jmR0nMs.mjs +898 -0
  80. package/dist/handlers-BAHPxcch.mjs +789 -0
  81. package/dist/handlers-BOs9b907.mjs +2600 -0
  82. package/dist/handlers-BWXEy6ef.mjs +917 -0
  83. package/dist/handlers-Bndn6QvE.mjs +111 -0
  84. package/dist/handlers-BqC4bD4s.mjs +681 -0
  85. package/dist/handlers-BtYq60bM2.mjs +276 -0
  86. package/dist/handlers-BzgcB4iv.mjs +799 -0
  87. package/dist/handlers-CRyRWj2b.mjs +859 -0
  88. package/dist/handlers-CVv2H1uq.mjs +592 -0
  89. package/dist/handlers-Dl5a7JS4.mjs +572 -0
  90. package/dist/handlers-Dx2d7jt7.mjs +2537 -0
  91. package/dist/handlers-Dz9PYsCa.mjs +2805 -0
  92. package/dist/handlers-HujRKC3b.mjs +661 -0
  93. package/dist/handlers.impl-XWXkQfyi.mjs +807 -0
  94. package/dist/hooks-B1B8NRHL.mjs +898 -0
  95. package/dist/index.mjs +491 -259
  96. package/dist/{logger-BmWzC2lM.mjs → logger-Dh_xb7_2.mjs} +14 -6
  97. package/dist/maintenance-PRMkLVRW.mjs +835 -0
  98. package/dist/manifest-67Bok-Si.mjs +58 -0
  99. package/dist/manifest-6lNTMZAB2.mjs +87 -0
  100. package/dist/manifest-B2duEHiH.mjs +90 -0
  101. package/dist/manifest-B6EY9Vm8.mjs +57 -0
  102. package/dist/manifest-B6nKSbyY.mjs +95 -0
  103. package/dist/manifest-BL8AQNPF.mjs +106 -0
  104. package/dist/manifest-BSZvJJmV.mjs +47 -0
  105. package/dist/manifest-BU7qzUyX.mjs +418 -0
  106. package/dist/manifest-Bl62e8WK.mjs +49 -0
  107. package/dist/manifest-Bo5cXjdt.mjs +82 -0
  108. package/dist/manifest-BpS4gtUK.mjs +1347 -0
  109. package/dist/manifest-Bv65_e2W.mjs +101 -0
  110. package/dist/manifest-BytNIF4Z.mjs +117 -0
  111. package/dist/manifest-C-xtsjS3.mjs +81 -0
  112. package/dist/manifest-CDYl7OhA.mjs +66 -0
  113. package/dist/manifest-CRZ3xmkD.mjs +61 -0
  114. package/dist/manifest-CoW6u4Tp.mjs +132 -0
  115. package/dist/manifest-Cq5zN_8A.mjs +50 -0
  116. package/dist/manifest-D7YZM_2e.mjs +194 -0
  117. package/dist/manifest-DE_VrAeQ.mjs +314 -0
  118. package/dist/manifest-DGsXSCpT.mjs +39 -0
  119. package/dist/manifest-DJ2vfEuW.mjs +156 -0
  120. package/dist/manifest-DPXDYhEu.mjs +80 -0
  121. package/dist/manifest-Dd4fQb0a.mjs +322 -0
  122. package/dist/manifest-Deq6opGg.mjs +223 -0
  123. package/dist/manifest-DfJTafJK.mjs +37 -0
  124. package/dist/manifest-DgOdgN_j.mjs +50 -0
  125. package/dist/manifest-DlbMW4v4.mjs +47 -0
  126. package/dist/manifest-DmVfbH0w.mjs +374 -0
  127. package/dist/manifest-Dog6Ddjr.mjs +109 -0
  128. package/dist/manifest-DvgU5FWb.mjs +58 -0
  129. package/dist/manifest-HsfDBs7j.mjs +50 -0
  130. package/dist/manifest-I8oQHvCG.mjs +186 -0
  131. package/dist/manifest-NvH_a-av.mjs +786 -0
  132. package/dist/manifest-cEJU1v0Z.mjs +129 -0
  133. package/dist/manifest-wOl5XLB12.mjs +112 -0
  134. package/dist/modules-tZozf0LQ.mjs +10635 -0
  135. package/dist/mojo-ipc-DXNEXEqb.mjs +640 -0
  136. package/dist/network-CPVvwvFg.mjs +3852 -0
  137. package/dist/{artifacts-BbdOMET5.mjs → outputPaths-um7lCRY3.mjs} +219 -216
  138. package/dist/parse-args-B4cY5Vx5.mjs +39 -0
  139. package/dist/platform-CYeFoTWp.mjs +2161 -0
  140. package/dist/process-BTbgcVc6.mjs +1306 -0
  141. package/dist/proxy-r8YN6nP1.mjs +192 -0
  142. package/dist/registry-Bl8ZQW61.mjs +34 -0
  143. package/dist/response-CWhh2aLo.mjs +34 -0
  144. package/dist/server/plugin-api.mjs +2 -2
  145. package/dist/shared-state-board-BoZnSoj-.mjs +586 -0
  146. package/dist/sourcemap-BIDHUVXy.mjs +934 -0
  147. package/dist/ssrf-policy-Dsqd-DTX.mjs +166 -0
  148. package/dist/streaming-Dal6utPp.mjs +725 -0
  149. package/dist/tool-builder-BHJp32mV.mjs +186 -0
  150. package/dist/transform-DRVgGG90.mjs +1011 -0
  151. package/dist/types-Bx92KJfT.mjs +4 -0
  152. package/dist/wasm-BYx5UOeG.mjs +1044 -0
  153. package/dist/webcrack-Be0_FccV.mjs +747 -0
  154. package/dist/workflow-BpuKEtvn.mjs +725 -0
  155. package/package.json +82 -49
  156. package/dist/ExtensionManager-CPTJhHFg.mjs +0 -2
  157. package/dist/ToolCatalog-Bq4V2sbJ.mjs +0 -67201
  158. package/dist/{CacheAdapters-CzFNpD9a.mjs → CacheAdapters-jJFy20G-.mjs} +0 -0
  159. package/dist/{StealthVerifier-BzBCFiwx.mjs → StealthVerifier-BWmPgQsv.mjs} +0 -0
  160. package/dist/{VersionDetector-CNXcvD46.mjs → VersionDetector-K3V4vGsw.mjs} +0 -0
  161. package/dist/{formatAddress-ChCSIRWT.mjs → formatAddress-nnMvEohD.mjs} +0 -0
  162. package/dist/{types-BBjOqye-.mjs → types-DDBWs9UP.mjs} +1 -1
@@ -0,0 +1,898 @@
1
+ import { t as logger } from "./logger-Dh_xb7_2.mjs";
2
+ import { a as argString, o as argStringArray, s as argStringRequired, t as argBool } from "./parse-args-B4cY5Vx5.mjs";
3
+ import { o as evaluateOnNewDocumentWithTimeout, s as evaluateWithTimeout } from "./PageController-BPJNqqBN.mjs";
4
+ import "./definitions-C1gCHO0i.mjs";
5
+ //#region src/server/domains/hooks/ai-handlers.ts
6
+ var AIHookToolHandlers = class {
7
+ injectedHooks = /* @__PURE__ */ new Map();
8
+ constructor(pageController) {
9
+ this.pageController = pageController;
10
+ }
11
+ hasAttachedTargetSession() {
12
+ return this.pageController.hasAttachedTargetSession();
13
+ }
14
+ async evaluateInAttachedTarget(expression) {
15
+ return await this.pageController.evaluateAttachedTarget(expression, {
16
+ returnByValue: true,
17
+ awaitPromise: true
18
+ });
19
+ }
20
+ async addScriptToAttachedTarget(source) {
21
+ await this.pageController.addScriptToAttachedTarget(source);
22
+ }
23
+ async handleAIHookInject(args) {
24
+ try {
25
+ const hookId = argStringRequired(args, "hookId");
26
+ const code = argStringRequired(args, "code");
27
+ const method = argString(args, "method", "evaluate");
28
+ if (this.hasAttachedTargetSession()) if (method === "evaluateOnNewDocument") {
29
+ await this.addScriptToAttachedTarget(code);
30
+ logger.info(`Hook injected into attached target (evaluateOnNewDocument): ${hookId}`);
31
+ } else {
32
+ await this.evaluateInAttachedTarget(code);
33
+ logger.info(`Hook injected into attached target (evaluate): ${hookId}`);
34
+ }
35
+ else {
36
+ const page = await this.pageController.getPage();
37
+ if (method === "evaluateOnNewDocument") {
38
+ await evaluateOnNewDocumentWithTimeout(page, code);
39
+ logger.info(`Hook injected (evaluateOnNewDocument): ${hookId}`);
40
+ } else {
41
+ await evaluateWithTimeout(page, code);
42
+ logger.info(`Hook injected (evaluate): ${hookId}`);
43
+ }
44
+ }
45
+ this.injectedHooks.set(hookId, {
46
+ code,
47
+ injectionTime: Date.now()
48
+ });
49
+ return { content: [{
50
+ type: "text",
51
+ text: JSON.stringify({
52
+ success: true,
53
+ hookId,
54
+ message: `Hook (: ${method})`,
55
+ injectionTime: (/* @__PURE__ */ new Date()).toISOString()
56
+ }, null, 2)
57
+ }] };
58
+ } catch (error) {
59
+ logger.error("Hook injection failed", error);
60
+ return { content: [{
61
+ type: "text",
62
+ text: JSON.stringify({
63
+ success: false,
64
+ error: error instanceof Error ? error.message : String(error)
65
+ }, null, 2)
66
+ }] };
67
+ }
68
+ }
69
+ async handleAIHookGetData(args) {
70
+ try {
71
+ const hookId = argStringRequired(args, "hookId");
72
+ const hookData = this.hasAttachedTargetSession() ? await this.evaluateInAttachedTarget(`(() => {
73
+ const hookId = ${JSON.stringify(hookId)};
74
+ const hooks = globalThis.__aiHooks;
75
+ if (!hooks?.[hookId]) {
76
+ return null;
77
+ }
78
+ return {
79
+ hookId,
80
+ metadata: globalThis.__aiHookMetadata?.[hookId],
81
+ records: hooks[hookId],
82
+ totalRecords: hooks[hookId].length,
83
+ };
84
+ })()`) : await evaluateWithTimeout(await this.pageController.getPage(), (id) => {
85
+ if (!window.__aiHooks?.[id]) return null;
86
+ return {
87
+ hookId: id,
88
+ metadata: window.__aiHookMetadata?.[id],
89
+ records: window.__aiHooks[id],
90
+ totalRecords: window.__aiHooks[id].length
91
+ };
92
+ }, hookId);
93
+ if (!hookData) return { content: [{
94
+ type: "text",
95
+ text: JSON.stringify({
96
+ success: false,
97
+ message: `Hook: ${hookId}`
98
+ }, null, 2)
99
+ }] };
100
+ return { content: [{
101
+ type: "text",
102
+ text: JSON.stringify({
103
+ success: true,
104
+ ...hookData
105
+ }, null, 2)
106
+ }] };
107
+ } catch (error) {
108
+ logger.error("Failed to get hook data", error);
109
+ return { content: [{
110
+ type: "text",
111
+ text: JSON.stringify({
112
+ success: false,
113
+ error: error instanceof Error ? error.message : String(error)
114
+ }, null, 2)
115
+ }] };
116
+ }
117
+ }
118
+ async handleAIHookList(_args) {
119
+ try {
120
+ const allHooks = this.hasAttachedTargetSession() ? await this.evaluateInAttachedTarget(`(() => {
121
+ const metadata = globalThis.__aiHookMetadata;
122
+ const hooks = globalThis.__aiHooks;
123
+ if (!metadata) {
124
+ return [];
125
+ }
126
+ return Object.keys(metadata).map((hookId) => ({
127
+ hookId,
128
+ metadata: metadata[hookId],
129
+ recordCount: hooks?.[hookId]?.length || 0,
130
+ }));
131
+ })()`) : await evaluateWithTimeout(await this.pageController.getPage(), () => {
132
+ if (!window.__aiHookMetadata) return [];
133
+ return Object.keys(window.__aiHookMetadata).map((hookId) => ({
134
+ hookId,
135
+ metadata: window.__aiHookMetadata[hookId],
136
+ recordCount: window.__aiHooks?.[hookId]?.length || 0
137
+ }));
138
+ });
139
+ return { content: [{
140
+ type: "text",
141
+ text: JSON.stringify({
142
+ success: true,
143
+ totalHooks: allHooks.length,
144
+ hooks: allHooks
145
+ }, null, 2)
146
+ }] };
147
+ } catch (error) {
148
+ logger.error("Failed to list hooks", error);
149
+ return { content: [{
150
+ type: "text",
151
+ text: JSON.stringify({
152
+ success: false,
153
+ error: error instanceof Error ? error.message : String(error)
154
+ }, null, 2)
155
+ }] };
156
+ }
157
+ }
158
+ async handleAIHookClear(args) {
159
+ try {
160
+ const hookId = argString(args, "hookId");
161
+ if (hookId) {
162
+ if (this.hasAttachedTargetSession()) await this.evaluateInAttachedTarget(`(() => {
163
+ const hookId = ${JSON.stringify(hookId)};
164
+ if (globalThis.__aiHooks?.[hookId]) {
165
+ globalThis.__aiHooks[hookId] = [];
166
+ }
167
+ return true;
168
+ })()`);
169
+ else await evaluateWithTimeout(await this.pageController.getPage(), (id) => {
170
+ if (window.__aiHooks?.[id]) window.__aiHooks[id] = [];
171
+ }, hookId);
172
+ return { content: [{
173
+ type: "text",
174
+ text: JSON.stringify({
175
+ success: true,
176
+ message: `Hook: ${hookId}`
177
+ }, null, 2)
178
+ }] };
179
+ } else {
180
+ if (this.hasAttachedTargetSession()) await this.evaluateInAttachedTarget(`(() => {
181
+ if (globalThis.__aiHooks) {
182
+ for (const key in globalThis.__aiHooks) {
183
+ globalThis.__aiHooks[key] = [];
184
+ }
185
+ }
186
+ return true;
187
+ })()`);
188
+ else await evaluateWithTimeout(await this.pageController.getPage(), () => {
189
+ if (window.__aiHooks) for (const key in window.__aiHooks) window.__aiHooks[key] = [];
190
+ });
191
+ return { content: [{
192
+ type: "text",
193
+ text: JSON.stringify({
194
+ success: true,
195
+ message: "Hook"
196
+ }, null, 2)
197
+ }] };
198
+ }
199
+ } catch (error) {
200
+ logger.error("Failed to clear hook data", error);
201
+ return { content: [{
202
+ type: "text",
203
+ text: JSON.stringify({
204
+ success: false,
205
+ error: error instanceof Error ? error.message : String(error)
206
+ }, null, 2)
207
+ }] };
208
+ }
209
+ }
210
+ async handleAIHookToggle(args) {
211
+ try {
212
+ const hookId = argStringRequired(args, "hookId");
213
+ const enabled = argBool(args, "enabled");
214
+ if (this.hasAttachedTargetSession()) await this.evaluateInAttachedTarget(`(() => {
215
+ const hookId = ${JSON.stringify(hookId)};
216
+ const enabled = ${JSON.stringify(enabled)};
217
+ if (globalThis.__aiHookMetadata?.[hookId]) {
218
+ globalThis.__aiHookMetadata[hookId].enabled = enabled;
219
+ }
220
+ return true;
221
+ })()`);
222
+ else await evaluateWithTimeout(await this.pageController.getPage(), (id, enable) => {
223
+ if (window.__aiHookMetadata?.[id]) window.__aiHookMetadata[id].enabled = enable;
224
+ }, hookId, enabled);
225
+ return { content: [{
226
+ type: "text",
227
+ text: JSON.stringify({
228
+ success: true,
229
+ hookId,
230
+ enabled,
231
+ message: `Hook${enabled ? "" : ""}`
232
+ }, null, 2)
233
+ }] };
234
+ } catch (error) {
235
+ logger.error("Failed to toggle hook", error);
236
+ return { content: [{
237
+ type: "text",
238
+ text: JSON.stringify({
239
+ success: false,
240
+ error: error instanceof Error ? error.message : String(error)
241
+ }, null, 2)
242
+ }] };
243
+ }
244
+ }
245
+ async handleAIHookExport(args) {
246
+ try {
247
+ const hookId = argString(args, "hookId");
248
+ const format = argString(args, "format", "json");
249
+ const exportData = this.hasAttachedTargetSession() ? await this.evaluateInAttachedTarget(`(() => {
250
+ const hookId = ${JSON.stringify(hookId)};
251
+ if (hookId) {
252
+ return {
253
+ hookId,
254
+ metadata: globalThis.__aiHookMetadata?.[hookId],
255
+ records: globalThis.__aiHooks?.[hookId] || [],
256
+ };
257
+ }
258
+ return {
259
+ metadata: globalThis.__aiHookMetadata || {},
260
+ records: globalThis.__aiHooks || {},
261
+ };
262
+ })()`) : await evaluateWithTimeout(await this.pageController.getPage(), (id) => {
263
+ if (id) return {
264
+ hookId: id,
265
+ metadata: window.__aiHookMetadata?.[id],
266
+ records: window.__aiHooks?.[id] || []
267
+ };
268
+ else return {
269
+ metadata: window.__aiHookMetadata || {},
270
+ records: window.__aiHooks || {}
271
+ };
272
+ }, hookId);
273
+ return { content: [{
274
+ type: "text",
275
+ text: JSON.stringify({
276
+ success: true,
277
+ format,
278
+ data: exportData,
279
+ exportTime: (/* @__PURE__ */ new Date()).toISOString()
280
+ }, null, 2)
281
+ }] };
282
+ } catch (error) {
283
+ logger.error("Failed to export hook data", error);
284
+ return { content: [{
285
+ type: "text",
286
+ text: JSON.stringify({
287
+ success: false,
288
+ error: error instanceof Error ? error.message : String(error)
289
+ }, null, 2)
290
+ }] };
291
+ }
292
+ }
293
+ async handleAIHook(args) {
294
+ const action = String(args["action"] ?? "");
295
+ switch (action) {
296
+ case "inject": return this.handleAIHookInject(args);
297
+ case "get_data": return this.handleAIHookGetData(args);
298
+ case "list": return this.handleAIHookList(args);
299
+ case "clear": return this.handleAIHookClear(args);
300
+ case "toggle": return this.handleAIHookToggle(args);
301
+ case "export": return this.handleAIHookExport(args);
302
+ default: return { content: [{
303
+ type: "text",
304
+ text: JSON.stringify({
305
+ success: false,
306
+ error: `Unknown action: ${action}. Valid actions: inject, get_data, list, clear, toggle, export`
307
+ })
308
+ }] };
309
+ }
310
+ }
311
+ };
312
+ //#endregion
313
+ //#region src/server/domains/hooks/preset-builder.ts
314
+ function buildHookCode(name, body, captureStack, logToConsole) {
315
+ const stackCode = captureStack ? `const __stack = new Error().stack?.split('\\n').slice(1,4).join(' | ') || '';` : `const __stack = '';`;
316
+ const logFn = logToConsole ? `console.log(__msg + (__stack ? ' | Stack: ' + __stack : ''));` : ``;
317
+ return `
318
+ (function() {
319
+ if (window.__hookPresets === undefined) window.__hookPresets = {};
320
+ if (window.__hookPresets['${name}']) return;
321
+ ${body.replace(/\{\{STACK_CODE\}\}/g, stackCode).replace(/\{\{LOG_FN\}\}/g, logFn)}
322
+ window.__hookPresets['${name}'] = true;
323
+ window.__aiHooks = window.__aiHooks || {};
324
+ window.__aiHooks['preset-${name}'] = window.__aiHooks['preset-${name}'] || [];
325
+ })();`;
326
+ }
327
+ //#endregion
328
+ //#region src/server/domains/hooks/preset-definitions.core.ts
329
+ const CORE_PRESETS = {
330
+ eval: {
331
+ description: " Hook eval() to capture dynamic code execution",
332
+ buildCode: (cs, lc) => buildHookCode("eval", `
333
+ const _orig = window.eval;
334
+ window.eval = function(code) {
335
+ {{STACK_CODE}}
336
+ const __msg = '[Hook:eval] code=' + String(code).substring(0, 200);
337
+ {{LOG_FN}}
338
+ window.__aiHooks['preset-eval'].push({ code: String(code).substring(0, 500), stack: __stack, ts: Date.now() });
339
+ return _orig.call(this, code);
340
+ };`, cs, lc)
341
+ },
342
+ "function-constructor": {
343
+ description: " Hook new Function() to capture dynamic function creation",
344
+ buildCode: (cs, lc) => buildHookCode("function-constructor", `
345
+ const _orig = Function;
346
+ window.Function = function(...args) {
347
+ {{STACK_CODE}}
348
+ const __msg = '[Hook:Function] args=' + JSON.stringify(args).substring(0, 200);
349
+ {{LOG_FN}}
350
+ window.__aiHooks['preset-function-constructor'].push({ args: args.map(a => String(a).substring(0,200)), stack: __stack, ts: Date.now() });
351
+ return _orig(...args);
352
+ };
353
+ window.Function.prototype = _orig.prototype;`, cs, lc)
354
+ },
355
+ "atob-btoa": {
356
+ description: " Hook atob/btoa to capture Base64 encode/decode operations",
357
+ buildCode: (cs, lc) => buildHookCode("atob-btoa", `
358
+ const _atob = window.atob.bind(window);
359
+ const _btoa = window.btoa.bind(window);
360
+ window.atob = function(s) {
361
+ {{STACK_CODE}}
362
+ const result = _atob(s);
363
+ const __msg = '[Hook:atob] in=' + String(s).substring(0,100) + ' out=' + result.substring(0,100);
364
+ {{LOG_FN}}
365
+ window.__aiHooks['preset-atob-btoa'].push({ fn:'atob', input: String(s).substring(0,200), output: result.substring(0,200), stack: __stack, ts: Date.now() });
366
+ return result;
367
+ };
368
+ window.btoa = function(s) {
369
+ {{STACK_CODE}}
370
+ const result = _btoa(s);
371
+ const __msg = '[Hook:btoa] in=' + String(s).substring(0,100) + ' out=' + result;
372
+ {{LOG_FN}}
373
+ window.__aiHooks['preset-atob-btoa'].push({ fn:'btoa', input: String(s).substring(0,200), output: result, stack: __stack, ts: Date.now() });
374
+ return result;
375
+ };`, cs, lc)
376
+ },
377
+ "crypto-subtle": {
378
+ description: " Hook crypto.subtle.encrypt/decrypt to intercept WebCrypto operations",
379
+ buildCode: (cs, lc) => buildHookCode("crypto-subtle", `
380
+ if (window.crypto && window.crypto.subtle) {
381
+ const _enc = window.crypto.subtle.encrypt.bind(window.crypto.subtle);
382
+ const _dec = window.crypto.subtle.decrypt.bind(window.crypto.subtle);
383
+ window.crypto.subtle.encrypt = function(algo, key, data) {
384
+ {{STACK_CODE}}
385
+ const __msg = '[Hook:crypto.encrypt] algo=' + JSON.stringify(algo);
386
+ {{LOG_FN}}
387
+ window.__aiHooks['preset-crypto-subtle'].push({ fn:'encrypt', algo: JSON.stringify(algo), stack: __stack, ts: Date.now() });
388
+ return _enc(algo, key, data);
389
+ };
390
+ window.crypto.subtle.decrypt = function(algo, key, data) {
391
+ {{STACK_CODE}}
392
+ const __msg = '[Hook:crypto.decrypt] algo=' + JSON.stringify(algo);
393
+ {{LOG_FN}}
394
+ window.__aiHooks['preset-crypto-subtle'].push({ fn:'decrypt', algo: JSON.stringify(algo), stack: __stack, ts: Date.now() });
395
+ return _dec(algo, key, data);
396
+ };
397
+ }`, cs, lc)
398
+ },
399
+ "json-stringify": {
400
+ description: " Hook JSON.stringify/parse to capture serialization activity",
401
+ buildCode: (cs, lc) => buildHookCode("json-stringify", `
402
+ const _stringify = JSON.stringify;
403
+ const _parse = JSON.parse;
404
+ JSON.stringify = function(v, r, s) {
405
+ {{STACK_CODE}}
406
+ const result = _stringify(v, r, s);
407
+ const __msg = '[Hook:JSON.stringify] out=' + (result||'').substring(0,100);
408
+ {{LOG_FN}}
409
+ window.__aiHooks['preset-json-stringify'].push({ fn:'stringify', output: (result||'').substring(0,300), stack: __stack, ts: Date.now() });
410
+ return result;
411
+ };
412
+ JSON.parse = function(text, r) {
413
+ {{STACK_CODE}}
414
+ const result = _parse(text, r);
415
+ const __msg = '[Hook:JSON.parse] in=' + String(text).substring(0,100);
416
+ {{LOG_FN}}
417
+ window.__aiHooks['preset-json-stringify'].push({ fn:'parse', input: String(text).substring(0,300), stack: __stack, ts: Date.now() });
418
+ return result;
419
+ };`, cs, lc)
420
+ },
421
+ "object-defineproperty": {
422
+ description: " Hook Object.defineProperty to monitor property definitions",
423
+ buildCode: (cs, lc) => buildHookCode("object-defineproperty", `
424
+ const _define = Object.defineProperty;
425
+ Object.defineProperty = function(obj, prop, descriptor) {
426
+ {{STACK_CODE}}
427
+ const __msg = '[Hook:Object.defineProperty] prop=' + String(prop);
428
+ {{LOG_FN}}
429
+ window.__aiHooks['preset-object-defineproperty'].push({ prop: String(prop), descriptor: JSON.stringify(descriptor||{}).substring(0,200), stack: __stack, ts: Date.now() });
430
+ return _define(obj, prop, descriptor);
431
+ };`, cs, lc)
432
+ },
433
+ settimeout: {
434
+ description: " Hook setTimeout to capture timer callbacks and delays",
435
+ buildCode: (cs, lc) => buildHookCode("settimeout", `
436
+ const _orig = window.setTimeout;
437
+ window.setTimeout = function(fn, delay, ...args) {
438
+ {{STACK_CODE}}
439
+ const fnStr = typeof fn === 'string' ? fn : fn?.toString().substring(0,100);
440
+ const __msg = '[Hook:setTimeout] delay=' + delay + ' fn=' + fnStr;
441
+ {{LOG_FN}}
442
+ window.__aiHooks['preset-settimeout'].push({ delay, fn: fnStr, stack: __stack, ts: Date.now() });
443
+ return _orig(fn, delay, ...args);
444
+ };`, cs, lc)
445
+ },
446
+ setinterval: {
447
+ description: " Hook setInterval to capture repeating timer callbacks",
448
+ buildCode: (cs, lc) => buildHookCode("setinterval", `
449
+ const _orig = window.setInterval;
450
+ window.setInterval = function(fn, delay, ...args) {
451
+ {{STACK_CODE}}
452
+ const fnStr = typeof fn === 'string' ? fn : fn?.toString().substring(0,100);
453
+ const __msg = '[Hook:setInterval] delay=' + delay + ' fn=' + fnStr;
454
+ {{LOG_FN}}
455
+ window.__aiHooks['preset-setinterval'].push({ delay, fn: fnStr, stack: __stack, ts: Date.now() });
456
+ return _orig(fn, delay, ...args);
457
+ };`, cs, lc)
458
+ },
459
+ addeventlistener: {
460
+ description: " Hook addEventListener to trace event listener registrations",
461
+ buildCode: (cs, lc) => buildHookCode("addeventlistener", `
462
+ const _orig = EventTarget.prototype.addEventListener;
463
+ EventTarget.prototype.addEventListener = function(type, listener, options) {
464
+ {{STACK_CODE}}
465
+ const __msg = '[Hook:addEventListener] type=' + type;
466
+ {{LOG_FN}}
467
+ window.__aiHooks['preset-addeventlistener'].push({ type, target: this?.tagName || String(this).substring(0,50), stack: __stack, ts: Date.now() });
468
+ return _orig.call(this, type, listener, options);
469
+ };`, cs, lc)
470
+ },
471
+ postmessage: {
472
+ description: " Hook postMessage to capture cross-origin and iframe messages",
473
+ buildCode: (cs, lc) => buildHookCode("postmessage", `
474
+ const _orig = window.postMessage.bind(window);
475
+ window.postMessage = function(data, origin, transfer) {
476
+ {{STACK_CODE}}
477
+ const __msg = '[Hook:postMessage] origin=' + origin + ' data=' + JSON.stringify(data).substring(0,100);
478
+ {{LOG_FN}}
479
+ window.__aiHooks['preset-postmessage'].push({ origin, data: JSON.stringify(data||{}).substring(0,300), stack: __stack, ts: Date.now() });
480
+ return _orig(data, origin, transfer);
481
+ };
482
+ window.addEventListener('message', function(e) {
483
+ window.__aiHooks['preset-postmessage'].push({ direction:'received', origin: e.origin, data: JSON.stringify(e.data||{}).substring(0,300), ts: Date.now() });
484
+ });`, cs, lc)
485
+ },
486
+ webassembly: {
487
+ description: " Hook WebAssembly.instantiate/compile to detect WASM module loading",
488
+ buildCode: (cs, lc) => buildHookCode("webassembly", `
489
+ if (typeof WebAssembly !== 'undefined') {
490
+ const _inst = WebAssembly.instantiate;
491
+ WebAssembly.instantiate = function(bufferSource, importObject) {
492
+ {{STACK_CODE}}
493
+ const size = bufferSource?.byteLength || bufferSource?.length || 0;
494
+ const __msg = '[Hook:WebAssembly.instantiate] size=' + size;
495
+ {{LOG_FN}}
496
+ window.__aiHooks['preset-webassembly'].push({ fn:'instantiate', size, stack: __stack, ts: Date.now() });
497
+ return _inst(bufferSource, importObject);
498
+ };
499
+ }`, cs, lc)
500
+ },
501
+ proxy: {
502
+ description: " Hook Proxy constructor to detect proxy-based anti-debugging",
503
+ buildCode: (cs, lc) => buildHookCode("proxy", `
504
+ const _Proxy = window.Proxy;
505
+ window.Proxy = function(target, handler) {
506
+ {{STACK_CODE}}
507
+ const __msg = '[Hook:Proxy] target=' + String(target).substring(0,50);
508
+ {{LOG_FN}}
509
+ window.__aiHooks['preset-proxy'].push({ target: String(target).substring(0,100), handlerKeys: Object.keys(handler||{}), stack: __stack, ts: Date.now() });
510
+ return new _Proxy(target, handler);
511
+ };
512
+ window.Proxy.prototype = _Proxy.prototype;
513
+ window.Proxy.revocable = _Proxy.revocable;`, cs, lc)
514
+ },
515
+ reflect: {
516
+ description: " Hook Reflect.apply to capture indirect function calls",
517
+ buildCode: (cs, lc) => buildHookCode("reflect", `
518
+ const _apply = Reflect.apply;
519
+ Reflect.apply = function(target, thisArg, args) {
520
+ {{STACK_CODE}}
521
+ const __msg = '[Hook:Reflect.apply] fn=' + (target?.name || 'anonymous');
522
+ {{LOG_FN}}
523
+ window.__aiHooks['preset-reflect'].push({ fn: target?.name || 'anonymous', argsCount: (args||[]).length, stack: __stack, ts: Date.now() });
524
+ return _apply(target, thisArg, args);
525
+ };`, cs, lc)
526
+ },
527
+ "history-pushstate": {
528
+ description: " Hook history.pushState/replaceState to trace SPA navigation",
529
+ buildCode: (cs, lc) => buildHookCode("history-pushstate", `
530
+ const _push = history.pushState.bind(history);
531
+ const _replace = history.replaceState.bind(history);
532
+ history.pushState = function(state, title, url) {
533
+ {{STACK_CODE}}
534
+ const __msg = '[Hook:history.pushState] url=' + url;
535
+ {{LOG_FN}}
536
+ window.__aiHooks['preset-history-pushstate'].push({ fn:'pushState', url: String(url), state: JSON.stringify(state||{}).substring(0,100), stack: __stack, ts: Date.now() });
537
+ return _push(state, title, url);
538
+ };
539
+ history.replaceState = function(state, title, url) {
540
+ {{STACK_CODE}}
541
+ const __msg = '[Hook:history.replaceState] url=' + url;
542
+ {{LOG_FN}}
543
+ window.__aiHooks['preset-history-pushstate'].push({ fn:'replaceState', url: String(url), state: JSON.stringify(state||{}).substring(0,100), stack: __stack, ts: Date.now() });
544
+ return _replace(state, title, url);
545
+ };`, cs, lc)
546
+ },
547
+ "location-href": {
548
+ description: " Hook location.href setter to intercept URL redirects",
549
+ buildCode: (cs, lc) => buildHookCode("location-href", `
550
+ const _desc = Object.getOwnPropertyDescriptor(window.location, 'href') ||
551
+ Object.getOwnPropertyDescriptor(Location.prototype, 'href');
552
+ if (_desc && _desc.set) {
553
+ const _origSet = _desc.set;
554
+ Object.defineProperty(window.location, 'href', {
555
+ get: _desc.get,
556
+ set: function(url) {
557
+ {{STACK_CODE}}
558
+ const __msg = '[Hook:location.href] url=' + url;
559
+ {{LOG_FN}}
560
+ window.__aiHooks['preset-location-href'].push({ url: String(url), stack: __stack, ts: Date.now() });
561
+ return _origSet.call(this, url);
562
+ },
563
+ configurable: true,
564
+ });
565
+ }`, cs, lc)
566
+ },
567
+ "navigator-useragent": {
568
+ description: " Hook navigator.userAgent getter to detect UA fingerprinting",
569
+ buildCode: (cs, lc) => buildHookCode("navigator-useragent", `
570
+ const _desc = Object.getOwnPropertyDescriptor(Navigator.prototype, 'userAgent');
571
+ if (_desc && _desc.get) {
572
+ const _origGet = _desc.get;
573
+ Object.defineProperty(Navigator.prototype, 'userAgent', {
574
+ get: function() {
575
+ {{STACK_CODE}}
576
+ const result = _origGet.call(this);
577
+ const __msg = '[Hook:navigator.userAgent] ua=' + result.substring(0,80);
578
+ {{LOG_FN}}
579
+ window.__aiHooks['preset-navigator-useragent'].push({ ua: result.substring(0,200), stack: __stack, ts: Date.now() });
580
+ return result;
581
+ },
582
+ configurable: true,
583
+ });
584
+ }`, cs, lc)
585
+ },
586
+ eventsource: {
587
+ description: " Hook EventSource to capture SSE connections",
588
+ buildCode: (cs, lc) => buildHookCode("eventsource", `
589
+ if (typeof EventSource !== 'undefined') {
590
+ const _ES = EventSource;
591
+ window.EventSource = function(url, opts) {
592
+ {{STACK_CODE}}
593
+ const __msg = '[Hook:EventSource] url=' + url;
594
+ {{LOG_FN}}
595
+ window.__aiHooks['preset-eventsource'].push({ url: String(url), stack: __stack, ts: Date.now() });
596
+ return new _ES(url, opts);
597
+ };
598
+ window.EventSource.prototype = _ES.prototype;
599
+ }`, cs, lc)
600
+ },
601
+ "window-open": {
602
+ description: " Hook window.open to capture popup and new tab creation",
603
+ buildCode: (cs, lc) => buildHookCode("window-open", `
604
+ const _orig = window.open.bind(window);
605
+ window.open = function(url, target, features) {
606
+ {{STACK_CODE}}
607
+ const __msg = '[Hook:window.open] url=' + url + ' target=' + target;
608
+ {{LOG_FN}}
609
+ window.__aiHooks['preset-window-open'].push({ url: String(url), target: String(target||''), stack: __stack, ts: Date.now() });
610
+ return _orig(url, target, features);
611
+ };`, cs, lc)
612
+ },
613
+ mutationobserver: {
614
+ description: " Hook MutationObserver to track dynamic DOM mutation watchers",
615
+ buildCode: (cs, lc) => buildHookCode("mutationobserver", `
616
+ const _MO = MutationObserver;
617
+ window.MutationObserver = function(callback) {
618
+ {{STACK_CODE}}
619
+ const __msg = '[Hook:MutationObserver] created';
620
+ {{LOG_FN}}
621
+ window.__aiHooks['preset-mutationobserver'].push({ stack: __stack, ts: Date.now() });
622
+ return new _MO(callback);
623
+ };
624
+ window.MutationObserver.prototype = _MO.prototype;`, cs, lc)
625
+ },
626
+ formdata: {
627
+ description: " Hook FormData.append to capture form data before submission",
628
+ buildCode: (cs, lc) => buildHookCode("formdata", `
629
+ const _orig = FormData.prototype.append;
630
+ FormData.prototype.append = function(name, value, filename) {
631
+ {{STACK_CODE}}
632
+ const __msg = '[Hook:FormData.append] name=' + name + ' value=' + String(value).substring(0,100);
633
+ {{LOG_FN}}
634
+ window.__aiHooks['preset-formdata'].push({ name: String(name), value: String(value).substring(0,200), stack: __stack, ts: Date.now() });
635
+ return _orig.call(this, name, value, filename);
636
+ };`, cs, lc)
637
+ }
638
+ };
639
+ //#endregion
640
+ //#region src/server/domains/hooks/preset-definitions.security.ts
641
+ const SECURITY_PRESETS = {
642
+ "anti-debug-bypass": {
643
+ description: " Block anti-debugging: setInterval/setTimeout debugger traps, console.clear spam, timing attacks (performance.now freeze), outerWidth/outerHeight devtools detection",
644
+ buildCode: (cs, lc) => buildHookCode("anti-debug-bypass", `
645
+ window.__aiHooks['preset-anti-debug-bypass'] = window.__aiHooks['preset-anti-debug-bypass'] || [];
646
+ // 1. Block setInterval/setTimeout containing debugger/devtools
647
+ const _si = window.setInterval;
648
+ window.setInterval = function(fn, delay) {
649
+ const rest = Array.prototype.slice.call(arguments, 2);
650
+ const fnStr = typeof fn === 'function' ? fn.toString() : String(fn);
651
+ if (fnStr.includes('debugger') || fnStr.includes('devtools') || fnStr.includes('disable-devtool')) {
652
+ window.__aiHooks['preset-anti-debug-bypass'].push({ blocked: 'setInterval', fn: fnStr.substring(0, 200), ts: Date.now() });
653
+ return -1;
654
+ }
655
+ return _si.apply(this, [fn, delay].concat(rest));
656
+ };
657
+ const _st = window.setTimeout;
658
+ window.setTimeout = function(fn, delay) {
659
+ const rest = Array.prototype.slice.call(arguments, 2);
660
+ const fnStr = typeof fn === 'function' ? fn.toString() : String(fn);
661
+ if (fnStr.includes('debugger') || fnStr.includes('devtools')) {
662
+ window.__aiHooks['preset-anti-debug-bypass'].push({ blocked: 'setTimeout', fn: fnStr.substring(0, 200), ts: Date.now() });
663
+ return -1;
664
+ }
665
+ return _st.apply(this, [fn, delay].concat(rest));
666
+ };
667
+ // 2. Suppress console.clear spam
668
+ console.clear = function() {
669
+ window.__aiHooks['preset-anti-debug-bypass'].push({ blocked: 'console.clear', ts: Date.now() });
670
+ };
671
+ // 3. Freeze performance.now to defeat timing attacks
672
+ const _pn = performance.now.bind(performance);
673
+ let _t = _pn();
674
+ performance.now = function() { return (_t += 0.001); };
675
+ // 4. Fix outerWidth/outerHeight DevTools size detection
676
+ Object.defineProperty(window, 'outerWidth', { get: function() { return window.innerWidth; }, configurable: true });
677
+ Object.defineProperty(window, 'outerHeight', { get: function() { return window.innerHeight; }, configurable: true });`, cs, lc)
678
+ },
679
+ "crypto-key-capture": {
680
+ description: " Force extractable:true on all WebCrypto importKey calls and capture plaintext/ciphertext + key material for encrypt/decrypt/sign/verify",
681
+ buildCode: (cs, lc) => buildHookCode("crypto-key-capture", `
682
+ if (window.crypto && window.crypto.subtle) {
683
+ const _subtle = window.crypto.subtle;
684
+ const _importKey = _subtle.importKey.bind(_subtle);
685
+ const _encrypt = _subtle.encrypt.bind(_subtle);
686
+ const _decrypt = _subtle.decrypt.bind(_subtle);
687
+ const _sign = _subtle.sign.bind(_subtle);
688
+ const _verify = _subtle.verify.bind(_subtle);
689
+ const _exportKey = _subtle.exportKey.bind(_subtle);
690
+ const toHex = function(buf) {
691
+ return Array.from(new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer || buf))
692
+ .map(function(b) { return b.toString(16).padStart(2,'0'); }).join('');
693
+ };
694
+ const tryExport = async function(key) {
695
+ try { return await _exportKey('jwk', key); } catch(e) { return null; }
696
+ };
697
+ _subtle.importKey = async function(format, keyData, algorithm, extractable, usages) {
698
+ {{STACK_CODE}}
699
+ const keyHex = (keyData instanceof ArrayBuffer || ArrayBuffer.isView(keyData)) ? toHex(keyData) : JSON.stringify(keyData);
700
+ const __msg = '[Hook:importKey] format=' + format + ' algo=' + JSON.stringify(algorithm) + ' key=' + keyHex.substring(0,64);
701
+ {{LOG_FN}}
702
+ const key = await _importKey(format, keyData, algorithm, true, usages);
703
+ window.__aiHooks['preset-crypto-key-capture'].push({ fn:'importKey', format, algorithm: JSON.stringify(algorithm), keyHex, stack: __stack, ts: Date.now() });
704
+ return key;
705
+ };
706
+ _subtle.encrypt = async function(algo, key, data) {
707
+ {{STACK_CODE}}
708
+ const plainHex = toHex(data);
709
+ const result = await _encrypt(algo, key, data);
710
+ const cipherHex = toHex(result);
711
+ const keyJwk = await tryExport(key);
712
+ const __msg = '[Hook:encrypt] algo=' + JSON.stringify(algo) + ' plain=' + plainHex.substring(0,64);
713
+ {{LOG_FN}}
714
+ window.__aiHooks['preset-crypto-key-capture'].push({ fn:'encrypt', algo: JSON.stringify(algo), plainHex, cipherHex, key: keyJwk, stack: __stack, ts: Date.now() });
715
+ return result;
716
+ };
717
+ _subtle.decrypt = async function(algo, key, data) {
718
+ {{STACK_CODE}}
719
+ const result = await _decrypt(algo, key, data);
720
+ const plainHex = toHex(result);
721
+ const keyJwk = await tryExport(key);
722
+ const __msg = '[Hook:decrypt] algo=' + JSON.stringify(algo) + ' plain=' + new TextDecoder().decode(new Uint8Array(result instanceof ArrayBuffer ? result : result.buffer, 0, Math.min(100, (result.byteLength || result.length || 0))));
723
+ {{LOG_FN}}
724
+ window.__aiHooks['preset-crypto-key-capture'].push({ fn:'decrypt', algo: JSON.stringify(algo), plainHex, key: keyJwk, stack: __stack, ts: Date.now() });
725
+ return result;
726
+ };
727
+ _subtle.sign = async function(algo, key, data) {
728
+ {{STACK_CODE}}
729
+ const result = await _sign(algo, key, data);
730
+ const keyJwk = await tryExport(key);
731
+ const __msg = '[Hook:sign] algo=' + JSON.stringify(algo);
732
+ {{LOG_FN}}
733
+ window.__aiHooks['preset-crypto-key-capture'].push({ fn:'sign', algo: JSON.stringify(algo), sigHex: toHex(result), key: keyJwk, stack: __stack, ts: Date.now() });
734
+ return result;
735
+ };
736
+ }`, cs, lc)
737
+ },
738
+ "webassembly-full": {
739
+ description: " Hook WebAssembly.instantiate to log all import calls, export names, and memory creation",
740
+ buildCode: (cs, lc) => buildHookCode("webassembly-full", `
741
+ if (typeof WebAssembly !== 'undefined') {
742
+ const _inst = WebAssembly.instantiate;
743
+ WebAssembly.instantiate = async function(bufferSource, importObject) {
744
+ {{STACK_CODE}}
745
+ const size = bufferSource && (bufferSource.byteLength || bufferSource.length) || 0;
746
+ const __msg = '[Hook:WASM.instantiate] size=' + size;
747
+ {{LOG_FN}}
748
+ // Wrap all imported functions to trace calls
749
+ if (importObject && typeof importObject === 'object') {
750
+ Object.keys(importObject).forEach(function(modName) {
751
+ const mod = importObject[modName];
752
+ if (mod && typeof mod === 'object') {
753
+ Object.keys(mod).forEach(function(fnName) {
754
+ if (typeof mod[fnName] === 'function') {
755
+ const _fn = mod[fnName];
756
+ mod[fnName] = function() {
757
+ const args = Array.prototype.slice.call(arguments);
758
+ window.__aiHooks['preset-webassembly-full'].push({ type:'import_call', mod: modName, fn: fnName, args: args.map(function(a){ return typeof a === 'number' ? a : '?'; }), ts: Date.now() });
759
+ return _fn.apply(this, args);
760
+ };
761
+ }
762
+ });
763
+ }
764
+ });
765
+ }
766
+ const result = await _inst(bufferSource, importObject);
767
+ const exports = result && result.instance ? Object.keys(result.instance.exports) : [];
768
+ window.__aiHooks['preset-webassembly-full'].push({ type:'instantiated', size, exports, importMods: importObject ? Object.keys(importObject) : [], stack: __stack, ts: Date.now() });
769
+ return result;
770
+ };
771
+ // Also hook WebAssembly.Memory creation
772
+ const _Memory = WebAssembly.Memory;
773
+ WebAssembly.Memory = function(descriptor) {
774
+ window.__aiHooks['preset-webassembly-full'].push({ type:'memory_created', initial: descriptor && descriptor.initial, maximum: descriptor && descriptor.maximum, shared: descriptor && descriptor.shared, ts: Date.now() });
775
+ return new _Memory(descriptor);
776
+ };
777
+ WebAssembly.Memory.prototype = _Memory.prototype;
778
+ }`, cs, lc)
779
+ }
780
+ };
781
+ //#endregion
782
+ //#region src/server/domains/hooks/preset-definitions.ts
783
+ const PRESETS = {
784
+ ...CORE_PRESETS,
785
+ ...SECURITY_PRESETS
786
+ };
787
+ const PRESET_LIST = Object.entries(PRESETS).map(([id, p]) => ({
788
+ id,
789
+ description: p.description
790
+ }));
791
+ //#endregion
792
+ //#region src/server/domains/hooks/preset-handlers.ts
793
+ var HookPresetToolHandlers = class {
794
+ pageController;
795
+ constructor(pageController) {
796
+ this.pageController = pageController;
797
+ }
798
+ async handleHookPreset(args) {
799
+ try {
800
+ const customPresetMap = this.buildCustomPresetMap(args);
801
+ const availablePresets = {
802
+ ...PRESETS,
803
+ ...customPresetMap
804
+ };
805
+ const availablePresetList = [...PRESET_LIST, ...Object.entries(customPresetMap).map(([id, preset]) => ({
806
+ id,
807
+ description: `${preset.description} (custom)`
808
+ }))];
809
+ if (args.listPresets === true) return { content: [{
810
+ type: "text",
811
+ text: JSON.stringify({
812
+ success: true,
813
+ totalPresets: availablePresetList.length,
814
+ presets: availablePresetList
815
+ }, null, 2)
816
+ }] };
817
+ const captureStack = argBool(args, "captureStack", false);
818
+ const logToConsole = argBool(args, "logToConsole", true);
819
+ const method = argString(args, "method", "evaluate");
820
+ let targets = [];
821
+ if (args.preset) targets = [argString(args, "preset")];
822
+ else if (Array.isArray(args.presets)) targets = argStringArray(args, "presets");
823
+ else return { content: [{
824
+ type: "text",
825
+ text: JSON.stringify({
826
+ success: false,
827
+ error: " Provide either preset (single) or presets (multiple), or set listPresets=true to list available presets"
828
+ }, null, 2)
829
+ }] };
830
+ const invalid = targets.filter((t) => !availablePresets[t]);
831
+ if (invalid.length > 0) return { content: [{
832
+ type: "text",
833
+ text: JSON.stringify({
834
+ success: false,
835
+ error: `: ${invalid.join(", ")}`,
836
+ availablePresets: availablePresetList.map((p) => p.id)
837
+ }, null, 2)
838
+ }] };
839
+ const page = await this.pageController.getPage();
840
+ const injected = [];
841
+ const errors = [];
842
+ for (const presetId of targets) try {
843
+ const code = availablePresets[presetId].buildCode(captureStack, logToConsole);
844
+ if (method === "evaluateOnNewDocument") await page.evaluateOnNewDocument(code);
845
+ else await page.evaluate(code);
846
+ injected.push(presetId);
847
+ logger.info(` Hook preset injected: ${presetId}`);
848
+ } catch (err) {
849
+ const errorMessage = err instanceof Error ? err.message : String(err);
850
+ errors.push({
851
+ preset: presetId,
852
+ error: errorMessage
853
+ });
854
+ logger.error(` Failed to inject preset ${presetId}:`, err);
855
+ }
856
+ return { content: [{
857
+ type: "text",
858
+ text: JSON.stringify({
859
+ success: errors.length === 0,
860
+ injected,
861
+ failed: errors,
862
+ method,
863
+ captureStack,
864
+ message: ` ${injected.length}/${targets.length} Hook`,
865
+ usage: ` ai_hook_get_data(hookId: "preset-<>") `
866
+ }, null, 2)
867
+ }] };
868
+ } catch (error) {
869
+ logger.error("Hook preset injection failed", error);
870
+ return { content: [{
871
+ type: "text",
872
+ text: JSON.stringify({
873
+ success: false,
874
+ error: error instanceof Error ? error.message : String(error)
875
+ }, null, 2)
876
+ }] };
877
+ }
878
+ }
879
+ buildCustomPresetMap(args) {
880
+ const rawTemplates = [];
881
+ if (args.customTemplate && typeof args.customTemplate === "object") rawTemplates.push(args.customTemplate);
882
+ if (Array.isArray(args.customTemplates)) rawTemplates.push(...args.customTemplates);
883
+ const customPresets = {};
884
+ for (const template of rawTemplates) {
885
+ const id = template.id?.trim();
886
+ const body = template.body?.trim();
887
+ if (!id || !body) throw new Error("Each custom template requires non-empty id and body");
888
+ if (PRESETS[id]) throw new Error(`Custom template id conflicts with built-in preset: ${id}`);
889
+ customPresets[id] = {
890
+ description: template.description?.trim() || `Custom inline preset: ${id}`,
891
+ buildCode: (captureStack, logToConsole) => buildHookCode(id, body, captureStack, logToConsole)
892
+ };
893
+ }
894
+ return customPresets;
895
+ }
896
+ };
897
+ //#endregion
898
+ export { AIHookToolHandlers, HookPresetToolHandlers };