@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 { fr as SYSCALL_TRACE_DURATION_DEFAULT_SEC, mr as SYSCALL_TRACE_DURATION_MIN_SEC, pr as SYSCALL_TRACE_DURATION_MAX_SEC } from "./constants-CDZLOoVv.mjs";
2
+ //#region src/modules/syscall-hook/SyscallMonitor.ts
3
+ const SUPPORTED_BACKENDS = [
4
+ "etw",
5
+ "strace",
6
+ "dtrace"
7
+ ];
8
+ const TRACE_SPAWN_TIMEOUT_MS = 3e3;
9
+ const SYNTHETIC_EVENT_SEEDS = {
10
+ etw: [
11
+ {
12
+ syscall: "NtCreateFile",
13
+ args: ["C:\\Windows\\Temp\\jshookmcp.log", "GENERIC_READ"],
14
+ returnValue: 0,
15
+ duration: .7
16
+ },
17
+ {
18
+ syscall: "NtReadFile",
19
+ args: ["handle=0x90", "buffer=4096"],
20
+ returnValue: 512,
21
+ duration: .2
22
+ },
23
+ {
24
+ syscall: "NtWriteFile",
25
+ args: ["handle=0x90", "buffer=128"],
26
+ returnValue: 128,
27
+ duration: .3
28
+ },
29
+ {
30
+ syscall: "NtDeviceIoControlFile",
31
+ args: ["handle=0x44", "code=0x222004"],
32
+ returnValue: 0,
33
+ duration: 1.1
34
+ }
35
+ ],
36
+ strace: [
37
+ {
38
+ syscall: "openat",
39
+ args: ["/tmp/jshookmcp.log", "O_RDONLY"],
40
+ returnValue: 3,
41
+ duration: .4
42
+ },
43
+ {
44
+ syscall: "read",
45
+ args: ["fd=3", "count=4096"],
46
+ returnValue: 256,
47
+ duration: .1
48
+ },
49
+ {
50
+ syscall: "write",
51
+ args: ["fd=3", "count=128"],
52
+ returnValue: 128,
53
+ duration: .2
54
+ },
55
+ {
56
+ syscall: "connect",
57
+ args: ["fd=18", "127.0.0.1:9222"],
58
+ returnValue: 0,
59
+ duration: 1.4
60
+ }
61
+ ],
62
+ dtrace: [
63
+ {
64
+ syscall: "open_nocancel",
65
+ args: ["/private/tmp/jshookmcp.log", "O_RDONLY"],
66
+ returnValue: 3,
67
+ duration: .5
68
+ },
69
+ {
70
+ syscall: "read_nocancel",
71
+ args: ["fd=3", "count=4096"],
72
+ returnValue: 320,
73
+ duration: .1
74
+ },
75
+ {
76
+ syscall: "write_nocancel",
77
+ args: ["fd=3", "count=128"],
78
+ returnValue: 128,
79
+ duration: .2
80
+ },
81
+ {
82
+ syscall: "connect",
83
+ args: ["fd=21", "127.0.0.1:9222"],
84
+ returnValue: 0,
85
+ duration: 1.3
86
+ }
87
+ ]
88
+ };
89
+ function isBackendSupportedOnCurrentPlatform(backend) {
90
+ if (backend === "etw") return process.platform === "win32";
91
+ if (backend === "strace") return process.platform === "linux";
92
+ if (backend === "dtrace") return process.platform === "darwin";
93
+ return false;
94
+ }
95
+ function chooseDefaultBackend() {
96
+ if (process.platform === "win32") return "etw";
97
+ if (process.platform === "linux") return "strace";
98
+ if (process.platform === "darwin") return "dtrace";
99
+ return "etw";
100
+ }
101
+ function cloneEvent(event) {
102
+ return {
103
+ timestamp: event.timestamp,
104
+ pid: event.pid,
105
+ syscall: event.syscall,
106
+ args: [...event.args],
107
+ returnValue: event.returnValue,
108
+ duration: event.duration
109
+ };
110
+ }
111
+ function createSpawnReadyGuard(label, resolve, reject, terminate) {
112
+ let settled = false;
113
+ const timer = setTimeout(() => {
114
+ if (settled) return;
115
+ settled = true;
116
+ try {
117
+ terminate?.();
118
+ } catch {}
119
+ reject(/* @__PURE__ */ new Error(`${label} did not signal readiness within ${TRACE_SPAWN_TIMEOUT_MS}ms`));
120
+ }, TRACE_SPAWN_TIMEOUT_MS);
121
+ return {
122
+ resolveReady(process) {
123
+ if (settled) return;
124
+ settled = true;
125
+ clearTimeout(timer);
126
+ resolve(process);
127
+ },
128
+ rejectReady(error) {
129
+ if (settled) return;
130
+ settled = true;
131
+ clearTimeout(timer);
132
+ reject(error);
133
+ }
134
+ };
135
+ }
136
+ function matchesFilter(event, filter) {
137
+ if (!filter) return true;
138
+ if (filter.pid !== void 0 && event.pid !== filter.pid) return false;
139
+ if (filter.name && filter.name.length > 0 && !filter.name.includes(event.syscall)) return false;
140
+ return true;
141
+ }
142
+ /**
143
+ * Parse a strace output line into a SyscallEvent.
144
+ *
145
+ * Example strace line:
146
+ * 12345 14:30:00.123456 openat(AT_FDCWD, "/tmp/foo", O_RDONLY) = 3 <0.000123>
147
+ */
148
+ function parseStraceLine(line, targetPid, startedAt) {
149
+ const match = /^(\d+)\s+([\d:.]+)\s+(\w+)\(([^)]*)\)\s*=\s*(-?\d+)(?:\s+<([\d.]+)>)?$/u.exec(line.trim());
150
+ if (!match) return null;
151
+ const syscall = match[3] ?? "unknown";
152
+ const rawArgs = match[4] ?? "";
153
+ const returnValue = Number(match[5]);
154
+ const duration = match[6] ? Number(match[6]) : void 0;
155
+ const args = rawArgs.split(",").map((a) => a.trim()).filter((a) => a.length > 0);
156
+ return {
157
+ timestamp: Date.now() - startedAt,
158
+ pid: targetPid,
159
+ syscall,
160
+ args,
161
+ returnValue: Number.isFinite(returnValue) ? returnValue : void 0,
162
+ duration: duration !== void 0 && Number.isFinite(duration) ? duration * 1e3 : void 0
163
+ };
164
+ }
165
+ /**
166
+ * Parse an ETW trace line (simplified from logman/wpr output).
167
+ *
168
+ * Example ETW line:
169
+ * [2024-01-15 14:30:00.123] PID=1234 NtCreateFile Handle=0x90 Status=0x00000000
170
+ */
171
+ function parseETWLine(line, targetPid, startedAt) {
172
+ const match = /^\[([^\]]+)\]\s+PID=(\d+)\s+(\w+)\s+(.*)$/u.exec(line.trim());
173
+ if (!match) return null;
174
+ const syscall = match[3] ?? "unknown";
175
+ const rawArgs = match[4] ?? "";
176
+ const pid = Number(match[2]);
177
+ const args = rawArgs.split(/\s+/u).filter((a) => a.length > 0);
178
+ return {
179
+ timestamp: Date.now() - startedAt,
180
+ pid: Number.isFinite(pid) ? pid : targetPid,
181
+ syscall,
182
+ args
183
+ };
184
+ }
185
+ /**
186
+ * Parse a dtrace output line.
187
+ *
188
+ * Example dtrace line:
189
+ * 1234 0 12345 open_nocancel:entry /private/tmp/foo O_RDONLY
190
+ */
191
+ function parseDTraceLine(line, targetPid, startedAt) {
192
+ const match = /^\s*(\d+)\s+\d+\s+(\d+)\s+(\w+):\w+\s+(.*)$/u.exec(line.trim());
193
+ if (!match) return null;
194
+ const syscall = match[3] ?? "unknown";
195
+ const rawArgs = match[4] ?? "";
196
+ const pid = Number(match[2]);
197
+ const args = rawArgs.split(/\s+/u).filter((a) => a.length > 0);
198
+ return {
199
+ timestamp: Date.now() - startedAt,
200
+ pid: Number.isFinite(pid) ? pid : targetPid,
201
+ syscall,
202
+ args
203
+ };
204
+ }
205
+ var SyscallMonitor = class {
206
+ activeState;
207
+ capturedEvents = [];
208
+ lastBackend = chooseDefaultBackend();
209
+ subprocessError;
210
+ async start(options) {
211
+ const requestedBackend = options?.backend ?? chooseDefaultBackend();
212
+ const startedAt = Date.now();
213
+ if (!isBackendSupportedOnCurrentPlatform(requestedBackend)) throw new Error(`Backend "${requestedBackend}" is not available on platform "${process.platform}"`);
214
+ if (options?.simulate ?? process.env["JSHOOK_SIMULATE"] === "1") {
215
+ this.activeState = {
216
+ backend: requestedBackend,
217
+ pid: options?.pid,
218
+ startedAt,
219
+ generatedEvents: 0
220
+ };
221
+ this.lastBackend = requestedBackend;
222
+ this.capturedEvents.length = 0;
223
+ this.generateSyntheticEvents();
224
+ return;
225
+ }
226
+ const pid = options?.pid ?? process.pid;
227
+ let subprocess;
228
+ try {
229
+ if (requestedBackend === "strace") subprocess = await this.captureWithStrace(pid, startedAt);
230
+ else if (requestedBackend === "etw") subprocess = await this.captureWithETW(pid, startedAt);
231
+ else if (requestedBackend === "dtrace") subprocess = await this.captureWithDTrace(pid, startedAt);
232
+ } catch (error) {
233
+ this.subprocessError = error instanceof Error ? error.message : String(error);
234
+ this.activeState = {
235
+ backend: requestedBackend,
236
+ pid: options?.pid,
237
+ startedAt,
238
+ generatedEvents: 0
239
+ };
240
+ this.lastBackend = requestedBackend;
241
+ this.capturedEvents.length = 0;
242
+ this.generateSyntheticEvents();
243
+ return;
244
+ }
245
+ this.activeState = {
246
+ backend: requestedBackend,
247
+ pid: options?.pid,
248
+ startedAt,
249
+ generatedEvents: 0,
250
+ subprocess
251
+ };
252
+ this.lastBackend = requestedBackend;
253
+ this.capturedEvents.length = 0;
254
+ this.subprocessError = void 0;
255
+ }
256
+ async stop() {
257
+ if (this.activeState?.subprocess) {
258
+ this.activeState.subprocess.kill("SIGTERM");
259
+ this.activeState.subprocess = void 0;
260
+ }
261
+ this.activeState = void 0;
262
+ }
263
+ async captureEvents(filter) {
264
+ if (this.activeState && !this.activeState.subprocess) this.generateSyntheticEvents();
265
+ return this.capturedEvents.filter((event) => matchesFilter(event, filter)).map(cloneEvent);
266
+ }
267
+ getStats() {
268
+ const backend = this.activeState?.backend ?? this.lastBackend;
269
+ const uptime = this.activeState ? Date.now() - this.activeState.startedAt : 0;
270
+ return {
271
+ eventsCaptured: this.capturedEvents.length,
272
+ uptime,
273
+ backend,
274
+ subprocessActive: !!this.activeState?.subprocess,
275
+ subprocessError: this.subprocessError
276
+ };
277
+ }
278
+ getSupportedBackends() {
279
+ return SUPPORTED_BACKENDS.filter((backend) => isBackendSupportedOnCurrentPlatform(backend));
280
+ }
281
+ isRunning() {
282
+ return this.activeState !== void 0;
283
+ }
284
+ /**
285
+ * Spawn strace for syscall tracing on Linux.
286
+ * Parses stdout into SyscallEvent objects.
287
+ */
288
+ async captureWithStrace(pid, startedAt = this.activeState?.startedAt ?? Date.now()) {
289
+ const { spawn } = await import("node:child_process");
290
+ return new Promise((resolve, reject) => {
291
+ const subprocess = spawn("strace", [
292
+ "-p",
293
+ String(pid),
294
+ "-f",
295
+ "-e",
296
+ "trace=all",
297
+ "-t"
298
+ ], { stdio: [
299
+ "ignore",
300
+ "pipe",
301
+ "pipe"
302
+ ] });
303
+ const ready = createSpawnReadyGuard("strace process", resolve, reject, () => subprocess.kill("SIGTERM"));
304
+ let stderrBuffer = "";
305
+ let lineAccumulator = "";
306
+ subprocess.stdout?.on("data", (chunk) => {
307
+ lineAccumulator += chunk.toString();
308
+ this.processLineBuffer(lineAccumulator, pid, "strace");
309
+ });
310
+ subprocess.stderr?.on("data", (chunk) => {
311
+ stderrBuffer += chunk.toString();
312
+ const lines = stderrBuffer.split(/\r?\n/u);
313
+ stderrBuffer = lines.pop() ?? "";
314
+ for (const line of lines) if (line.length > 0) {
315
+ const event = parseStraceLine(line, pid, startedAt);
316
+ if (event) this.capturedEvents.push(event);
317
+ }
318
+ });
319
+ subprocess.on("error", (error) => {
320
+ ready.rejectReady(/* @__PURE__ */ new Error(`strace process error: ${error.message}. Is strace installed?`));
321
+ });
322
+ subprocess.on("spawn", () => {
323
+ ready.resolveReady(subprocess);
324
+ });
325
+ });
326
+ }
327
+ /**
328
+ * Spawn ETW tracing on Windows using logman.
329
+ * Parses ETW trace output into SyscallEvent objects.
330
+ */
331
+ async captureWithETW(pid, startedAt = this.activeState?.startedAt ?? Date.now()) {
332
+ const { spawn } = await import("node:child_process");
333
+ return new Promise((resolve, reject) => {
334
+ const logman = spawn("logman", [
335
+ "create",
336
+ "trace",
337
+ `JSHookETW_${pid}`,
338
+ "-p",
339
+ "NT Kernel Logger",
340
+ "0x10000",
341
+ "-o",
342
+ `jshook_etw_${pid}.etl`,
343
+ "-ets"
344
+ ], {
345
+ stdio: [
346
+ "ignore",
347
+ "pipe",
348
+ "pipe"
349
+ ],
350
+ windowsHide: true
351
+ });
352
+ const ready = createSpawnReadyGuard("ETW trace session", resolve, reject, () => logman.kill("SIGTERM"));
353
+ let outputBuffer = "";
354
+ logman.stdout?.on("data", (chunk) => {
355
+ outputBuffer += chunk.toString();
356
+ const lines = outputBuffer.split(/\r?\n/u);
357
+ outputBuffer = lines.pop() ?? "";
358
+ for (const line of lines) {
359
+ const event = parseETWLine(line, pid, startedAt);
360
+ if (event) this.capturedEvents.push(event);
361
+ }
362
+ });
363
+ logman.stderr?.on("data", (chunk) => {
364
+ const msg = chunk.toString().trim();
365
+ if (msg.length > 0 && !msg.startsWith("The command completed successfully")) {}
366
+ });
367
+ logman.on("error", (error) => {
368
+ ready.rejectReady(/* @__PURE__ */ new Error(`ETW trace error: ${error.message}. Run as Administrator.`));
369
+ });
370
+ logman.on("exit", (code) => {
371
+ if (code !== 0 && code !== void 0) ready.rejectReady(/* @__PURE__ */ new Error(`ETW trace session ended (code ${code}). Check permissions.`));
372
+ });
373
+ logman.on("spawn", () => {
374
+ ready.resolveReady(logman);
375
+ });
376
+ });
377
+ }
378
+ /**
379
+ * Spawn dtrace for syscall tracing on macOS.
380
+ * Parses dtrace output into SyscallEvent objects.
381
+ */
382
+ async captureWithDTrace(pid, startedAt = this.activeState?.startedAt ?? Date.now()) {
383
+ const { spawn } = await import("node:child_process");
384
+ return new Promise((resolve, reject) => {
385
+ const dtrace = spawn("dtrace", ["-n", `
386
+ syscall:::entry
387
+ /pid == ${pid}/
388
+ {
389
+ printf("%d %d %s:entry %s", pid, probeproc, probefunc, copyinstr(arg0));
390
+ }
391
+ `], { stdio: [
392
+ "ignore",
393
+ "pipe",
394
+ "pipe"
395
+ ] });
396
+ const ready = createSpawnReadyGuard("dtrace process", resolve, reject, () => dtrace.kill("SIGTERM"));
397
+ let outputBuffer = "";
398
+ dtrace.stdout?.on("data", (chunk) => {
399
+ outputBuffer += chunk.toString();
400
+ const lines = outputBuffer.split(/\r?\n/u);
401
+ outputBuffer = lines.pop() ?? "";
402
+ for (const line of lines) {
403
+ const event = parseDTraceLine(line, pid, startedAt);
404
+ if (event) this.capturedEvents.push(event);
405
+ }
406
+ });
407
+ dtrace.stderr?.on("data", () => {});
408
+ dtrace.on("error", (error) => {
409
+ ready.rejectReady(/* @__PURE__ */ new Error(`dtrace error: ${error.message}. Run with sudo.`));
410
+ });
411
+ dtrace.on("spawn", () => {
412
+ ready.resolveReady(dtrace);
413
+ });
414
+ });
415
+ }
416
+ generateSyntheticEvents() {
417
+ if (!this.activeState) return;
418
+ const seeds = SYNTHETIC_EVENT_SEEDS[this.activeState.backend];
419
+ if (!seeds) return;
420
+ const elapsed = Date.now() - this.activeState.startedAt;
421
+ const targetEventCount = Math.max(1, Math.min(seeds.length * 3, Math.floor(elapsed / 150) + 1));
422
+ const pid = this.activeState.pid ?? process.pid;
423
+ while (this.activeState.generatedEvents < targetEventCount) {
424
+ const seed = seeds[this.activeState.generatedEvents % seeds.length];
425
+ if (!seed) break;
426
+ const timestamp = this.activeState.generatedEvents * 75;
427
+ this.capturedEvents.push({
428
+ timestamp,
429
+ pid,
430
+ syscall: seed.syscall,
431
+ args: [...seed.args],
432
+ returnValue: seed.returnValue,
433
+ duration: seed.duration
434
+ });
435
+ this.activeState.generatedEvents += 1;
436
+ }
437
+ }
438
+ processLineBuffer(_buffer, _pid, _parser) {}
439
+ };
440
+ //#endregion
441
+ //#region src/modules/syscall-hook/SyscallToJSMapper.ts
442
+ const CORRELATION_RULES = [
443
+ {
444
+ syscallNames: [
445
+ "NtCreateFile",
446
+ "openat",
447
+ "open_nocancel"
448
+ ],
449
+ jsFunction: "fs.open",
450
+ baseConfidence: .8,
451
+ explanation: "File open syscalls commonly originate from Node.js file-system entry points."
452
+ },
453
+ {
454
+ syscallNames: [
455
+ "NtReadFile",
456
+ "read",
457
+ "read_nocancel"
458
+ ],
459
+ jsFunction: "fs.readFile",
460
+ baseConfidence: .78,
461
+ explanation: "Read-oriented syscalls usually map back to file or stream reads in JavaScript."
462
+ },
463
+ {
464
+ syscallNames: [
465
+ "NtWriteFile",
466
+ "write",
467
+ "write_nocancel"
468
+ ],
469
+ jsFunction: "fs.writeFile",
470
+ baseConfidence: .78,
471
+ explanation: "Write-oriented syscalls are strongly associated with Node.js file writes."
472
+ },
473
+ {
474
+ syscallNames: ["NtDeviceIoControlFile", "ioctl"],
475
+ jsFunction: "child_process.spawn",
476
+ baseConfidence: .55,
477
+ explanation: "Device and control syscalls are often triggered by child processes or native helpers."
478
+ },
479
+ {
480
+ syscallNames: [
481
+ "connect",
482
+ "sendto",
483
+ "recvfrom"
484
+ ],
485
+ jsFunction: "fetch",
486
+ baseConfidence: .7,
487
+ explanation: "Socket syscalls generally indicate outbound network activity from fetch-like APIs."
488
+ }
489
+ ];
490
+ function findRuleBySyscallName(syscallName) {
491
+ return CORRELATION_RULES.find((rule) => rule.syscallNames.includes(syscallName));
492
+ }
493
+ function clampConfidence(confidence) {
494
+ if (confidence < 0) return 0;
495
+ if (confidence > 1) return 1;
496
+ return confidence;
497
+ }
498
+ function hasArgContaining(args, fragments) {
499
+ return args.some((arg) => fragments.some((fragment) => arg.toLowerCase().includes(fragment)));
500
+ }
501
+ var SyscallToJSMapper = class {
502
+ map(syscall) {
503
+ const jsFunction = this.findJSFunction(syscall.syscall);
504
+ if (!jsFunction) return null;
505
+ const rule = findRuleBySyscallName(syscall.syscall);
506
+ if (!rule) return null;
507
+ let confidence = rule.baseConfidence;
508
+ if (jsFunction.startsWith("fs.") && hasArgContaining(syscall.args, [
509
+ ".js",
510
+ ".json",
511
+ ".node"
512
+ ])) confidence += .08;
513
+ if (jsFunction === "fetch" && hasArgContaining(syscall.args, [
514
+ "80",
515
+ "443",
516
+ "http",
517
+ "https"
518
+ ])) confidence += .1;
519
+ return {
520
+ syscall: {
521
+ timestamp: syscall.timestamp,
522
+ pid: syscall.pid,
523
+ syscall: syscall.syscall,
524
+ args: [...syscall.args],
525
+ returnValue: syscall.returnValue,
526
+ duration: syscall.duration
527
+ },
528
+ jsFunction,
529
+ confidence: clampConfidence(confidence),
530
+ reasoning: this.getCorrelationReason(syscall, jsFunction)
531
+ };
532
+ }
533
+ findJSFunction(syscallName) {
534
+ const rule = findRuleBySyscallName(syscallName);
535
+ if (!rule) return null;
536
+ return rule.jsFunction;
537
+ }
538
+ getCorrelationReason(syscall, jsFunc) {
539
+ const rule = findRuleBySyscallName(syscall.syscall);
540
+ const detailParts = [];
541
+ if (rule) detailParts.push(rule.explanation);
542
+ if (jsFunc.startsWith("fs.") && hasArgContaining(syscall.args, [
543
+ ".js",
544
+ ".json",
545
+ ".node"
546
+ ])) detailParts.push("The syscall arguments reference module-like file extensions, which strengthens the fs correlation.");
547
+ if (jsFunc === "fetch" && hasArgContaining(syscall.args, [
548
+ "80",
549
+ "443",
550
+ "http",
551
+ "https"
552
+ ])) detailParts.push("The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.");
553
+ if (detailParts.length === 0) detailParts.push(`Mapped ${syscall.syscall} to ${jsFunc} using the default syscall-to-JS heuristic table.`);
554
+ return detailParts.join(" ");
555
+ }
556
+ };
557
+ //#endregion
558
+ //#region src/server/domains/syscall-hook/handlers.impl.ts
559
+ function isRecord(value) {
560
+ return typeof value === "object" && value !== null;
561
+ }
562
+ function readNumber(value) {
563
+ if (typeof value === "number" && Number.isFinite(value)) return value;
564
+ }
565
+ function readBoolean(value) {
566
+ if (typeof value === "boolean") return value;
567
+ }
568
+ function readString(value) {
569
+ if (typeof value === "string") return value;
570
+ }
571
+ function readStringArray(value) {
572
+ if (!Array.isArray(value)) return;
573
+ const strings = [];
574
+ for (const item of value) {
575
+ if (typeof item !== "string") return;
576
+ strings.push(item);
577
+ }
578
+ return strings;
579
+ }
580
+ const SYSCALL_NAME_RE = /^[a-z][a-z0-9_]*$/;
581
+ function isValidSyscallName(name) {
582
+ return SYSCALL_NAME_RE.test(name) && name.length <= 64;
583
+ }
584
+ function readBackend(value) {
585
+ if (value === "etw" || value === "strace" || value === "dtrace") return value;
586
+ }
587
+ function readFilter(value) {
588
+ if (!isRecord(value)) return;
589
+ const filter = {};
590
+ const names = readStringArray(value["name"]);
591
+ const pid = readNumber(value["pid"]);
592
+ if (names) filter.name = names;
593
+ if (pid !== void 0) filter.pid = pid;
594
+ return filter;
595
+ }
596
+ function isSyscallEvent(value) {
597
+ if (!isRecord(value)) return false;
598
+ const timestamp = readNumber(value["timestamp"]);
599
+ const pid = readNumber(value["pid"]);
600
+ const syscall = readString(value["syscall"]);
601
+ const args = readStringArray(value["args"]);
602
+ const returnValue = value["returnValue"];
603
+ const duration = value["duration"];
604
+ const returnValueValid = returnValue === void 0 || readNumber(returnValue) !== void 0;
605
+ const durationValid = duration === void 0 || readNumber(duration) !== void 0;
606
+ return timestamp !== void 0 && pid !== void 0 && syscall !== void 0 && args !== void 0 && returnValueValid && durationValid;
607
+ }
608
+ function cloneSyscallEvent(event) {
609
+ return {
610
+ timestamp: event.timestamp,
611
+ pid: event.pid,
612
+ syscall: event.syscall,
613
+ args: [...event.args],
614
+ returnValue: event.returnValue,
615
+ duration: event.duration
616
+ };
617
+ }
618
+ function toErrorMessage(error) {
619
+ if (error instanceof Error) return error.message;
620
+ return "Unknown syscall-hook error";
621
+ }
622
+ var SyscallHookHandlers = class {
623
+ constructor(monitor, mapper, eventBus) {
624
+ this.monitor = monitor;
625
+ this.mapper = mapper;
626
+ this.eventBus = eventBus;
627
+ }
628
+ async handleSyscallStartMonitor(args) {
629
+ const backend = readBackend(args["backend"]);
630
+ if (!backend) return {
631
+ ok: false,
632
+ error: "backend must be one of: etw, strace, dtrace"
633
+ };
634
+ const rawMonitorPid = readNumber(args["pid"]);
635
+ const simulate = readBoolean(args["simulate"]) ?? false;
636
+ if (args["pid"] !== void 0 && args["pid"] !== null) {
637
+ if (rawMonitorPid === void 0 || !Number.isInteger(rawMonitorPid) || rawMonitorPid < 0) return {
638
+ ok: false,
639
+ error: "pid must be a non-negative integer when provided"
640
+ };
641
+ }
642
+ const pid = rawMonitorPid;
643
+ const monitor = this.ensureMonitor();
644
+ try {
645
+ await monitor.start({
646
+ backend,
647
+ pid,
648
+ simulate
649
+ });
650
+ this.eventBus?.emit("syscall:trace_started", {
651
+ backend,
652
+ pid,
653
+ simulate,
654
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
655
+ });
656
+ return {
657
+ ok: true,
658
+ started: true,
659
+ backend,
660
+ pid,
661
+ simulate,
662
+ stats: monitor.getStats()
663
+ };
664
+ } catch (error) {
665
+ return {
666
+ ok: false,
667
+ error: toErrorMessage(error),
668
+ requestedBackend: backend,
669
+ supportedBackends: monitor.getSupportedBackends()
670
+ };
671
+ }
672
+ }
673
+ async handleSyscallStopMonitor() {
674
+ const monitor = this.ensureMonitor();
675
+ try {
676
+ await monitor.stop();
677
+ return {
678
+ ok: true,
679
+ stopped: true,
680
+ stats: monitor.getStats()
681
+ };
682
+ } catch (error) {
683
+ return {
684
+ ok: false,
685
+ error: toErrorMessage(error)
686
+ };
687
+ }
688
+ }
689
+ async handleSyscallCaptureEvents(args) {
690
+ const monitor = this.ensureMonitor();
691
+ const filter = readFilter(args["filter"]);
692
+ const events = await monitor.captureEvents(filter);
693
+ return {
694
+ ok: true,
695
+ events,
696
+ count: events.length,
697
+ stats: monitor.getStats()
698
+ };
699
+ }
700
+ async handleSyscallCorrelateJs(args) {
701
+ const rawEvents = args["syscallEvents"];
702
+ if (!Array.isArray(rawEvents) || !rawEvents.every((item) => isSyscallEvent(item))) return {
703
+ ok: false,
704
+ error: "syscallEvents must be an array of valid SyscallEvent objects"
705
+ };
706
+ const mapper = this.ensureMapper();
707
+ const correlations = [];
708
+ const unmatched = [];
709
+ for (const event of rawEvents) {
710
+ const clonedEvent = cloneSyscallEvent(event);
711
+ const correlated = mapper.map(clonedEvent);
712
+ if (correlated) correlations.push(correlated);
713
+ else unmatched.push(clonedEvent);
714
+ }
715
+ return {
716
+ ok: true,
717
+ correlations,
718
+ matched: correlations.length,
719
+ unmatched
720
+ };
721
+ }
722
+ async handleSyscallFilter(args) {
723
+ const names = readStringArray(args["names"]);
724
+ if (args["names"] !== void 0 && names === void 0) return {
725
+ ok: false,
726
+ error: "names must be an array of strings when provided"
727
+ };
728
+ const events = await this.ensureMonitor().captureEvents(names && names.length > 0 ? { name: names } : void 0);
729
+ return {
730
+ ok: true,
731
+ names,
732
+ events,
733
+ count: events.length
734
+ };
735
+ }
736
+ async handleSyscallGetStats() {
737
+ const monitor = this.ensureMonitor();
738
+ return {
739
+ ok: true,
740
+ ...monitor.getStats(),
741
+ running: monitor.isRunning(),
742
+ supportedBackends: monitor.getSupportedBackends()
743
+ };
744
+ }
745
+ async handleSyscallEbpfTrace(args) {
746
+ const rawPid = readNumber(args["pid"]);
747
+ const syscalls = readStringArray(args["syscalls"]);
748
+ const durationSec = readNumber(args["durationSec"]) ?? SYSCALL_TRACE_DURATION_DEFAULT_SEC;
749
+ const simulate = readBoolean(args["simulate"]) ?? false;
750
+ if (args["pid"] !== void 0 && args["pid"] !== null) {
751
+ if (rawPid === void 0 || !Number.isInteger(rawPid) || rawPid < 0) return {
752
+ ok: false,
753
+ error: "pid must be a non-negative integer (0 for all processes)"
754
+ };
755
+ }
756
+ const pid = rawPid ?? 0;
757
+ if (durationSec < SYSCALL_TRACE_DURATION_MIN_SEC || durationSec > SYSCALL_TRACE_DURATION_MAX_SEC) return {
758
+ ok: false,
759
+ error: `durationSec must be between ${SYSCALL_TRACE_DURATION_MIN_SEC} and ${SYSCALL_TRACE_DURATION_MAX_SEC}`
760
+ };
761
+ if (syscalls?.length) {
762
+ const invalid = syscalls.filter((s) => !isValidSyscallName(s));
763
+ if (invalid.length > 0) return {
764
+ ok: false,
765
+ error: `Invalid syscall names (must be lowercase alphanumeric with underscores): ${invalid.join(", ")}`
766
+ };
767
+ }
768
+ if (simulate) {
769
+ const simulatedEvents = [];
770
+ const syscallPool = syscalls?.length ? syscalls : [
771
+ "read",
772
+ "write",
773
+ "openat",
774
+ "close",
775
+ "fstat",
776
+ "mmap",
777
+ "mprotect",
778
+ "munmap",
779
+ "brk",
780
+ "ioctl"
781
+ ];
782
+ const simulatedTimestampStepMs = durationSec * 50;
783
+ for (let i = 0; i < 20; i++) simulatedEvents.push({
784
+ timestamp: i * simulatedTimestampStepMs,
785
+ pid: pid || 1234,
786
+ syscall: syscallPool[i % syscallPool.length] ?? "read",
787
+ args: [`fd=${i % 5 + 3}`, `count=${(i + 1) * 64}`],
788
+ returnValue: i % 3 === 0 ? -1 : (i + 1) * 64,
789
+ duration: Math.random() * 2
790
+ });
791
+ return {
792
+ ok: true,
793
+ backend: "ebpf",
794
+ simulated: true,
795
+ pid,
796
+ durationSec,
797
+ events: simulatedEvents,
798
+ count: simulatedEvents.length,
799
+ syscallsTraced: syscallPool
800
+ };
801
+ }
802
+ const targetSyscalls = syscalls?.length ? syscalls : [
803
+ "read",
804
+ "write",
805
+ "openat",
806
+ "close",
807
+ "fstat",
808
+ "mmap",
809
+ "mprotect",
810
+ "munmap",
811
+ "brk",
812
+ "ioctl",
813
+ "connect",
814
+ "sendto",
815
+ "recvfrom",
816
+ "clone",
817
+ "execve"
818
+ ];
819
+ const pidFilter = pid > 0 ? `/pid == ${pid}/` : "";
820
+ const tracepoints = targetSyscalls.map((sc) => `tracepoint:syscalls:sys_enter_${sc}`).join(", ");
821
+ const exitTracepoints = targetSyscalls.map((sc) => `tracepoint:syscalls:sys_exit_${sc}`).join(", ");
822
+ const script = `#!/usr/bin/env bpftrace
823
+ // Generated by jshookmcp syscall_ebpf_trace
824
+ // Target PID: ${pid || "all"} | Duration: ${durationSec}s | Syscalls: ${targetSyscalls.join(", ")}
825
+
826
+ BEGIN {
827
+ printf("=== eBPF syscall trace started (pid=${pid || "all"}, duration=${durationSec}s) ===\\n");
828
+ }
829
+
830
+ ${tracepoints} ${pidFilter}
831
+ {
832
+ @enter_ts[tid] = nsecs;
833
+ printf("{\\"timestamp\\": %llu, \\"pid\\": %d, \\"tid\\": %d, \\"syscall\\": \\"%s\\", \\"phase\\": \\"enter\\", \\"args\\": {",
834
+ elapsed / 1000000, pid, tid, probe);
835
+ // Log key arguments based on syscall
836
+ if (probe == "tracepoint:syscalls:sys_enter_openat" || probe == "tracepoint:syscalls:sys_enter_open") {
837
+ printf("\\"pathname\\": \\"%s\\", \\"flags\\": %d, \\"mode\\": %d", args->pathname, args->flags, args->mode);
838
+ } else if (probe == "tracepoint:syscalls:sys_enter_read" || probe == "tracepoint:syscalls:sys_enter_write") {
839
+ printf("\\"fd\\": %d, \\"count\\": %d", args->fd, args->count);
840
+ } else if (probe == "tracepoint:syscalls:sys_enter_connect") {
841
+ printf("\\"fd\\": %d", args->fd);
842
+ } else if (probe == "tracepoint:syscalls:sys_enter_mmap") {
843
+ printf("\\"addr\\": %llu, \\"length\\": %llu, \\"prot\\": %d, \\"flags\\": %d, \\"fd\\": %d", args->addr, args->length, args->prot, args->flags, args->fd);
844
+ } else if (probe == "tracepoint:syscalls:sys_enter_execve") {
845
+ printf("\\"filename\\": \\"%s\\"", args->filename);
846
+ } else {
847
+ printf("\\"raw_args\\": \\"(see bpftrace -v output)\\"");
848
+ }
849
+ printf("}}\\n");
850
+ }
851
+
852
+ ${exitTracepoints} ${pidFilter}
853
+ {
854
+ $elapsed_ns = nsecs - @enter_ts[tid];
855
+ printf("{\\"timestamp\\": %llu, \\"pid\\": %d, \\"tid\\": %d, \\"syscall\\": \\"%s\\", \\"phase\\": \\"exit\\", \\"ret\\": %d, \\"duration_us\\": %llu}\\n",
856
+ elapsed / 1000000, pid, tid, probe, args->ret, $elapsed_ns / 1000);
857
+ delete(@enter_ts[tid]);
858
+ }
859
+
860
+ interval:s:${durationSec} {
861
+ printf("=== Trace duration (${durationSec}s) elapsed, exiting ===\\n");
862
+ exit();
863
+ }
864
+
865
+ END {
866
+ printf("=== eBPF syscall trace complete ===\\n");
867
+ clear(@enter_ts);
868
+ }
869
+ `;
870
+ return {
871
+ ok: true,
872
+ backend: "ebpf",
873
+ mode: "script",
874
+ pid,
875
+ durationSec,
876
+ syscallCount: targetSyscalls.length,
877
+ syscallsTraced: targetSyscalls,
878
+ script,
879
+ usage: `bpftrace -e '${script.replace(/'/g, "'\\''")}'`,
880
+ note: "Run the generated bpftrace script on a Linux system with bpftrace installed and CAP_BPF/root privileges.",
881
+ requiredCapabilities: [
882
+ "CAP_BPF",
883
+ "root",
884
+ "bpftrace"
885
+ ]
886
+ };
887
+ }
888
+ ensureMonitor() {
889
+ if (!this.monitor) this.monitor = new SyscallMonitor();
890
+ return this.monitor;
891
+ }
892
+ ensureMapper() {
893
+ if (!this.mapper) this.mapper = new SyscallToJSMapper();
894
+ return this.mapper;
895
+ }
896
+ };
897
+ //#endregion
898
+ export { SyscallHookHandlers };