@jagilber-org/index-server 1.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (360) hide show
  1. package/CHANGELOG.md +1218 -0
  2. package/CODE_OF_CONDUCT.md +49 -0
  3. package/CONTRIBUTING.md +75 -0
  4. package/LICENSE +21 -0
  5. package/README.md +523 -0
  6. package/SECURITY.md +50 -0
  7. package/dist/config/configUtils.d.ts +11 -0
  8. package/dist/config/configUtils.js +87 -0
  9. package/dist/config/dashboardConfig.d.ts +45 -0
  10. package/dist/config/dashboardConfig.js +63 -0
  11. package/dist/config/defaultValues.d.ts +61 -0
  12. package/dist/config/defaultValues.js +70 -0
  13. package/dist/config/dirConstants.d.ts +17 -0
  14. package/dist/config/dirConstants.js +28 -0
  15. package/dist/config/featureConfig.d.ts +61 -0
  16. package/dist/config/featureConfig.js +121 -0
  17. package/dist/config/runtimeConfig.d.ts +145 -0
  18. package/dist/config/runtimeConfig.js +334 -0
  19. package/dist/config/serverConfig.d.ts +90 -0
  20. package/dist/config/serverConfig.js +164 -0
  21. package/dist/dashboard/analytics/AnalyticsEngine.d.ts +142 -0
  22. package/dist/dashboard/analytics/AnalyticsEngine.js +373 -0
  23. package/dist/dashboard/analytics/BusinessIntelligence.d.ts +187 -0
  24. package/dist/dashboard/analytics/BusinessIntelligence.js +594 -0
  25. package/dist/dashboard/client/admin.html +2150 -0
  26. package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/chunk-SP2CHFBE.mjs +1 -0
  27. package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/render-T6MDALS3.mjs +27 -0
  28. package/dist/dashboard/client/css/admin.css +1466 -0
  29. package/dist/dashboard/client/js/admin.boot.js +359 -0
  30. package/dist/dashboard/client/js/admin.config.js +196 -0
  31. package/dist/dashboard/client/js/admin.embeddings.js +425 -0
  32. package/dist/dashboard/client/js/admin.graph.js +583 -0
  33. package/dist/dashboard/client/js/admin.instances.js +120 -0
  34. package/dist/dashboard/client/js/admin.instructions.js +552 -0
  35. package/dist/dashboard/client/js/admin.logs.js +113 -0
  36. package/dist/dashboard/client/js/admin.maintenance.js +354 -0
  37. package/dist/dashboard/client/js/admin.messaging.js +635 -0
  38. package/dist/dashboard/client/js/admin.monitor.js +181 -0
  39. package/dist/dashboard/client/js/admin.overview.js +221 -0
  40. package/dist/dashboard/client/js/admin.performance.js +61 -0
  41. package/dist/dashboard/client/js/admin.sessions.js +293 -0
  42. package/dist/dashboard/client/js/admin.sqlite.js +366 -0
  43. package/dist/dashboard/client/js/admin.utils.js +49 -0
  44. package/dist/dashboard/client/js/chart.umd.js +14 -0
  45. package/dist/dashboard/client/js/elk.bundled.js +6696 -0
  46. package/dist/dashboard/client/js/marked.umd.js +74 -0
  47. package/dist/dashboard/client/js/mermaid.min.js +3022 -0
  48. package/dist/dashboard/client/mermaid-layout-elk.esm.min.mjs +1 -0
  49. package/dist/dashboard/export/DataExporter.d.ts +169 -0
  50. package/dist/dashboard/export/DataExporter.js +737 -0
  51. package/dist/dashboard/export/exporters/csvExporter.d.ts +11 -0
  52. package/dist/dashboard/export/exporters/csvExporter.js +46 -0
  53. package/dist/dashboard/export/exporters/exportTypes.d.ts +89 -0
  54. package/dist/dashboard/export/exporters/exportTypes.js +5 -0
  55. package/dist/dashboard/export/exporters/jsonExporter.d.ts +7 -0
  56. package/dist/dashboard/export/exporters/jsonExporter.js +22 -0
  57. package/dist/dashboard/export/exporters/xmlExporter.d.ts +17 -0
  58. package/dist/dashboard/export/exporters/xmlExporter.js +175 -0
  59. package/dist/dashboard/integration/APIIntegration.d.ts +41 -0
  60. package/dist/dashboard/integration/APIIntegration.js +95 -0
  61. package/dist/dashboard/security/SecurityMonitor.d.ts +167 -0
  62. package/dist/dashboard/security/SecurityMonitor.js +559 -0
  63. package/dist/dashboard/server/AdminPanel.d.ts +183 -0
  64. package/dist/dashboard/server/AdminPanel.js +792 -0
  65. package/dist/dashboard/server/AdminPanelConfig.d.ts +42 -0
  66. package/dist/dashboard/server/AdminPanelConfig.js +80 -0
  67. package/dist/dashboard/server/AdminPanelState.d.ts +47 -0
  68. package/dist/dashboard/server/AdminPanelState.js +214 -0
  69. package/dist/dashboard/server/ApiRoutes.d.ts +17 -0
  70. package/dist/dashboard/server/ApiRoutes.js +149 -0
  71. package/dist/dashboard/server/DashboardServer.d.ts +49 -0
  72. package/dist/dashboard/server/DashboardServer.js +159 -0
  73. package/dist/dashboard/server/FileMetricsStorage.d.ts +49 -0
  74. package/dist/dashboard/server/FileMetricsStorage.js +195 -0
  75. package/dist/dashboard/server/HttpTransport.d.ts +23 -0
  76. package/dist/dashboard/server/HttpTransport.js +116 -0
  77. package/dist/dashboard/server/InstanceManager.d.ts +53 -0
  78. package/dist/dashboard/server/InstanceManager.js +284 -0
  79. package/dist/dashboard/server/KnowledgeStore.d.ts +35 -0
  80. package/dist/dashboard/server/KnowledgeStore.js +105 -0
  81. package/dist/dashboard/server/LeaderElection.d.ts +81 -0
  82. package/dist/dashboard/server/LeaderElection.js +268 -0
  83. package/dist/dashboard/server/MetricsCollector.d.ts +200 -0
  84. package/dist/dashboard/server/MetricsCollector.js +803 -0
  85. package/dist/dashboard/server/SessionPersistenceManager.d.ts +88 -0
  86. package/dist/dashboard/server/SessionPersistenceManager.js +457 -0
  87. package/dist/dashboard/server/ThinClient.d.ts +64 -0
  88. package/dist/dashboard/server/ThinClient.js +237 -0
  89. package/dist/dashboard/server/WebSocketManager.d.ts +161 -0
  90. package/dist/dashboard/server/WebSocketManager.js +463 -0
  91. package/dist/dashboard/server/httpLifecycle.d.ts +17 -0
  92. package/dist/dashboard/server/httpLifecycle.js +35 -0
  93. package/dist/dashboard/server/legacyDashboardHtml.d.ts +9 -0
  94. package/dist/dashboard/server/legacyDashboardHtml.js +618 -0
  95. package/dist/dashboard/server/legacyDashboardStyles.d.ts +5 -0
  96. package/dist/dashboard/server/legacyDashboardStyles.js +490 -0
  97. package/dist/dashboard/server/metricsAggregation.d.ts +252 -0
  98. package/dist/dashboard/server/metricsAggregation.js +206 -0
  99. package/dist/dashboard/server/metricsSerializer.d.ts +25 -0
  100. package/dist/dashboard/server/metricsSerializer.js +195 -0
  101. package/dist/dashboard/server/routes/admin.routes.d.ts +16 -0
  102. package/dist/dashboard/server/routes/admin.routes.js +596 -0
  103. package/dist/dashboard/server/routes/alerts.routes.d.ts +7 -0
  104. package/dist/dashboard/server/routes/alerts.routes.js +93 -0
  105. package/dist/dashboard/server/routes/api.feedback.routes.d.ts +73 -0
  106. package/dist/dashboard/server/routes/api.feedback.routes.js +171 -0
  107. package/dist/dashboard/server/routes/api.instructions.routes.d.ts +101 -0
  108. package/dist/dashboard/server/routes/api.instructions.routes.js +213 -0
  109. package/dist/dashboard/server/routes/api.usage.routes.d.ts +57 -0
  110. package/dist/dashboard/server/routes/api.usage.routes.js +374 -0
  111. package/dist/dashboard/server/routes/embeddings.routes.d.ts +6 -0
  112. package/dist/dashboard/server/routes/embeddings.routes.js +246 -0
  113. package/dist/dashboard/server/routes/graph.routes.d.ts +6 -0
  114. package/dist/dashboard/server/routes/graph.routes.js +280 -0
  115. package/dist/dashboard/server/routes/index.d.ts +38 -0
  116. package/dist/dashboard/server/routes/index.js +194 -0
  117. package/dist/dashboard/server/routes/instances.routes.d.ts +6 -0
  118. package/dist/dashboard/server/routes/instances.routes.js +35 -0
  119. package/dist/dashboard/server/routes/instructions.routes.d.ts +8 -0
  120. package/dist/dashboard/server/routes/instructions.routes.js +336 -0
  121. package/dist/dashboard/server/routes/knowledge.routes.d.ts +6 -0
  122. package/dist/dashboard/server/routes/knowledge.routes.js +82 -0
  123. package/dist/dashboard/server/routes/logs.routes.d.ts +6 -0
  124. package/dist/dashboard/server/routes/logs.routes.js +164 -0
  125. package/dist/dashboard/server/routes/messaging.routes.d.ts +16 -0
  126. package/dist/dashboard/server/routes/messaging.routes.js +293 -0
  127. package/dist/dashboard/server/routes/metrics.routes.d.ts +10 -0
  128. package/dist/dashboard/server/routes/metrics.routes.js +346 -0
  129. package/dist/dashboard/server/routes/scripts.routes.d.ts +9 -0
  130. package/dist/dashboard/server/routes/scripts.routes.js +84 -0
  131. package/dist/dashboard/server/routes/sqlite.routes.d.ts +9 -0
  132. package/dist/dashboard/server/routes/sqlite.routes.js +569 -0
  133. package/dist/dashboard/server/routes/status.routes.d.ts +7 -0
  134. package/dist/dashboard/server/routes/status.routes.js +183 -0
  135. package/dist/dashboard/server/routes/synthetic.routes.d.ts +7 -0
  136. package/dist/dashboard/server/routes/synthetic.routes.js +195 -0
  137. package/dist/dashboard/server/routes/tools.routes.d.ts +6 -0
  138. package/dist/dashboard/server/routes/tools.routes.js +46 -0
  139. package/dist/dashboard/server/routes/usage.routes.d.ts +6 -0
  140. package/dist/dashboard/server/routes/usage.routes.js +25 -0
  141. package/dist/dashboard/server/wsInit.d.ts +16 -0
  142. package/dist/dashboard/server/wsInit.js +35 -0
  143. package/dist/externalClientLib.d.ts +1 -0
  144. package/dist/externalClientLib.js +2 -0
  145. package/dist/minimal/index.d.ts +1 -0
  146. package/dist/minimal/index.js +140 -0
  147. package/dist/models/SessionPersistence.d.ts +115 -0
  148. package/dist/models/SessionPersistence.js +66 -0
  149. package/dist/models/instruction.d.ts +45 -0
  150. package/dist/models/instruction.js +2 -0
  151. package/dist/perf/benchmark.d.ts +1 -0
  152. package/dist/perf/benchmark.js +50 -0
  153. package/dist/portableClientWrapper.d.ts +1 -0
  154. package/dist/portableClientWrapper.js +2 -0
  155. package/dist/schemas/index.d.ts +128 -0
  156. package/dist/schemas/index.js +371 -0
  157. package/dist/scripts/runPerformanceBaseline.d.ts +1 -0
  158. package/dist/scripts/runPerformanceBaseline.js +17 -0
  159. package/dist/server/handshakeManager.d.ts +25 -0
  160. package/dist/server/handshakeManager.js +472 -0
  161. package/dist/server/index-server.d.ts +56 -0
  162. package/dist/server/index-server.js +822 -0
  163. package/dist/server/registry.d.ts +44 -0
  164. package/dist/server/registry.js +236 -0
  165. package/dist/server/sdkServer.d.ts +8 -0
  166. package/dist/server/sdkServer.js +299 -0
  167. package/dist/server/shutdownGuard.d.ts +41 -0
  168. package/dist/server/shutdownGuard.js +52 -0
  169. package/dist/server/thin-client.d.ts +22 -0
  170. package/dist/server/thin-client.js +111 -0
  171. package/dist/server/transport.d.ts +41 -0
  172. package/dist/server/transport.js +312 -0
  173. package/dist/server/transportFactory.d.ts +21 -0
  174. package/dist/server/transportFactory.js +429 -0
  175. package/dist/services/atomicFs.d.ts +22 -0
  176. package/dist/services/atomicFs.js +103 -0
  177. package/dist/services/auditLog.d.ts +38 -0
  178. package/dist/services/auditLog.js +142 -0
  179. package/dist/services/autoBackup.d.ts +14 -0
  180. package/dist/services/autoBackup.js +171 -0
  181. package/dist/services/autoSplit.d.ts +32 -0
  182. package/dist/services/autoSplit.js +113 -0
  183. package/dist/services/backupZip.d.ts +25 -0
  184. package/dist/services/backupZip.js +110 -0
  185. package/dist/services/bootstrapGating.d.ts +123 -0
  186. package/dist/services/bootstrapGating.js +221 -0
  187. package/dist/services/canonical.d.ts +23 -0
  188. package/dist/services/canonical.js +65 -0
  189. package/dist/services/categoryRules.d.ts +7 -0
  190. package/dist/services/categoryRules.js +37 -0
  191. package/dist/services/classificationService.d.ts +42 -0
  192. package/dist/services/classificationService.js +168 -0
  193. package/dist/services/embeddingService.d.ts +62 -0
  194. package/dist/services/embeddingService.js +259 -0
  195. package/dist/services/errors.d.ts +22 -0
  196. package/dist/services/errors.js +31 -0
  197. package/dist/services/featureFlags.d.ts +25 -0
  198. package/dist/services/featureFlags.js +89 -0
  199. package/dist/services/features.d.ts +13 -0
  200. package/dist/services/features.js +35 -0
  201. package/dist/services/handlers/instructions.add.d.ts +1 -0
  202. package/dist/services/handlers/instructions.add.js +496 -0
  203. package/dist/services/handlers/instructions.groom.d.ts +1 -0
  204. package/dist/services/handlers/instructions.groom.js +523 -0
  205. package/dist/services/handlers/instructions.import.d.ts +1 -0
  206. package/dist/services/handlers/instructions.import.js +173 -0
  207. package/dist/services/handlers/instructions.patch.d.ts +1 -0
  208. package/dist/services/handlers/instructions.patch.js +167 -0
  209. package/dist/services/handlers/instructions.query.d.ts +163 -0
  210. package/dist/services/handlers/instructions.query.js +522 -0
  211. package/dist/services/handlers/instructions.reload.d.ts +1 -0
  212. package/dist/services/handlers/instructions.reload.js +13 -0
  213. package/dist/services/handlers/instructions.remove.d.ts +1 -0
  214. package/dist/services/handlers/instructions.remove.js +118 -0
  215. package/dist/services/handlers/instructions.shared.d.ts +31 -0
  216. package/dist/services/handlers/instructions.shared.js +124 -0
  217. package/dist/services/handlers.activation.d.ts +1 -0
  218. package/dist/services/handlers.activation.js +203 -0
  219. package/dist/services/handlers.bootstrap.d.ts +1 -0
  220. package/dist/services/handlers.bootstrap.js +38 -0
  221. package/dist/services/handlers.dashboardConfig.d.ts +34 -0
  222. package/dist/services/handlers.dashboardConfig.js +108 -0
  223. package/dist/services/handlers.diagnostics.d.ts +1 -0
  224. package/dist/services/handlers.diagnostics.js +64 -0
  225. package/dist/services/handlers.feedback.d.ts +15 -0
  226. package/dist/services/handlers.feedback.js +378 -0
  227. package/dist/services/handlers.gates.d.ts +1 -0
  228. package/dist/services/handlers.gates.js +46 -0
  229. package/dist/services/handlers.graph.d.ts +53 -0
  230. package/dist/services/handlers.graph.js +231 -0
  231. package/dist/services/handlers.help.d.ts +1 -0
  232. package/dist/services/handlers.help.js +119 -0
  233. package/dist/services/handlers.instructionSchema.d.ts +1 -0
  234. package/dist/services/handlers.instructionSchema.js +227 -0
  235. package/dist/services/handlers.instructions.d.ts +8 -0
  236. package/dist/services/handlers.instructions.js +14 -0
  237. package/dist/services/handlers.instructionsDiagnostics.d.ts +1 -0
  238. package/dist/services/handlers.instructionsDiagnostics.js +14 -0
  239. package/dist/services/handlers.integrity.d.ts +1 -0
  240. package/dist/services/handlers.integrity.js +35 -0
  241. package/dist/services/handlers.manifest.d.ts +1 -0
  242. package/dist/services/handlers.manifest.js +24 -0
  243. package/dist/services/handlers.messaging.d.ts +12 -0
  244. package/dist/services/handlers.messaging.js +203 -0
  245. package/dist/services/handlers.metrics.d.ts +1 -0
  246. package/dist/services/handlers.metrics.js +43 -0
  247. package/dist/services/handlers.promote.d.ts +1 -0
  248. package/dist/services/handlers.promote.js +306 -0
  249. package/dist/services/handlers.prompt.d.ts +1 -0
  250. package/dist/services/handlers.prompt.js +7 -0
  251. package/dist/services/handlers.search.d.ts +69 -0
  252. package/dist/services/handlers.search.js +645 -0
  253. package/dist/services/handlers.testPrimitive.d.ts +1 -0
  254. package/dist/services/handlers.testPrimitive.js +5 -0
  255. package/dist/services/handlers.trace.d.ts +1 -0
  256. package/dist/services/handlers.trace.js +31 -0
  257. package/dist/services/handlers.usage.d.ts +1 -0
  258. package/dist/services/handlers.usage.js +11 -0
  259. package/dist/services/hotScore.d.ts +137 -0
  260. package/dist/services/hotScore.js +244 -0
  261. package/dist/services/indexContext.d.ts +117 -0
  262. package/dist/services/indexContext.js +968 -0
  263. package/dist/services/indexLoader.d.ts +44 -0
  264. package/dist/services/indexLoader.js +921 -0
  265. package/dist/services/indexRepository.d.ts +32 -0
  266. package/dist/services/indexRepository.js +71 -0
  267. package/dist/services/indexingService.d.ts +1 -0
  268. package/dist/services/indexingService.js +2 -0
  269. package/dist/services/instructions.dispatcher.d.ts +1 -0
  270. package/dist/services/instructions.dispatcher.js +231 -0
  271. package/dist/services/logPrefix.d.ts +1 -0
  272. package/dist/services/logPrefix.js +30 -0
  273. package/dist/services/logger.d.ts +52 -0
  274. package/dist/services/logger.js +268 -0
  275. package/dist/services/manifestManager.d.ts +82 -0
  276. package/dist/services/manifestManager.js +200 -0
  277. package/dist/services/messaging/agentMailbox.d.ts +60 -0
  278. package/dist/services/messaging/agentMailbox.js +353 -0
  279. package/dist/services/messaging/messagingPersistence.d.ts +20 -0
  280. package/dist/services/messaging/messagingPersistence.js +111 -0
  281. package/dist/services/messaging/messagingTypes.d.ts +150 -0
  282. package/dist/services/messaging/messagingTypes.js +66 -0
  283. package/dist/services/ownershipService.d.ts +1 -0
  284. package/dist/services/ownershipService.js +38 -0
  285. package/dist/services/performanceBaseline.d.ts +19 -0
  286. package/dist/services/performanceBaseline.js +210 -0
  287. package/dist/services/preflight.d.ts +12 -0
  288. package/dist/services/preflight.js +79 -0
  289. package/dist/services/promptReviewService.d.ts +44 -0
  290. package/dist/services/promptReviewService.js +101 -0
  291. package/dist/services/responseEnvelope.d.ts +6 -0
  292. package/dist/services/responseEnvelope.js +25 -0
  293. package/dist/services/seedBootstrap.d.ts +34 -0
  294. package/dist/services/seedBootstrap.js +427 -0
  295. package/dist/services/storage/factory.d.ts +17 -0
  296. package/dist/services/storage/factory.js +35 -0
  297. package/dist/services/storage/hashUtils.d.ts +11 -0
  298. package/dist/services/storage/hashUtils.js +35 -0
  299. package/dist/services/storage/index.d.ts +12 -0
  300. package/dist/services/storage/index.js +18 -0
  301. package/dist/services/storage/jsonFileStore.d.ts +32 -0
  302. package/dist/services/storage/jsonFileStore.js +241 -0
  303. package/dist/services/storage/migrationEngine.d.ts +35 -0
  304. package/dist/services/storage/migrationEngine.js +93 -0
  305. package/dist/services/storage/sqliteMessageStore.d.ts +53 -0
  306. package/dist/services/storage/sqliteMessageStore.js +146 -0
  307. package/dist/services/storage/sqliteSchema.d.ts +12 -0
  308. package/dist/services/storage/sqliteSchema.js +122 -0
  309. package/dist/services/storage/sqliteStore.d.ts +41 -0
  310. package/dist/services/storage/sqliteStore.js +339 -0
  311. package/dist/services/storage/sqliteUsageStore.d.ts +35 -0
  312. package/dist/services/storage/sqliteUsageStore.js +94 -0
  313. package/dist/services/storage/types.d.ts +171 -0
  314. package/dist/services/storage/types.js +12 -0
  315. package/dist/services/toolHandlers.d.ts +23 -0
  316. package/dist/services/toolHandlers.js +50 -0
  317. package/dist/services/toolRegistry.d.ts +20 -0
  318. package/dist/services/toolRegistry.js +490 -0
  319. package/dist/services/toolRegistry.zod.d.ts +10 -0
  320. package/dist/services/toolRegistry.zod.js +323 -0
  321. package/dist/services/tracing.d.ts +26 -0
  322. package/dist/services/tracing.js +260 -0
  323. package/dist/services/usageBuckets.d.ts +161 -0
  324. package/dist/services/usageBuckets.js +364 -0
  325. package/dist/services/validationService.d.ts +38 -0
  326. package/dist/services/validationService.js +125 -0
  327. package/dist/utils/BufferRing.d.ts +203 -0
  328. package/dist/utils/BufferRing.js +551 -0
  329. package/dist/utils/BufferRingExamples.d.ts +55 -0
  330. package/dist/utils/BufferRingExamples.js +188 -0
  331. package/dist/utils/envUtils.d.ts +42 -0
  332. package/dist/utils/envUtils.js +80 -0
  333. package/dist/utils/memoryMonitor.d.ts +83 -0
  334. package/dist/utils/memoryMonitor.js +275 -0
  335. package/dist/versioning/schemaVersion.d.ts +6 -0
  336. package/dist/versioning/schemaVersion.js +93 -0
  337. package/package.json +134 -0
  338. package/schemas/README.md +13 -0
  339. package/schemas/feedback-entry.schema.json +27 -0
  340. package/schemas/graph-export-v2.schema.json +60 -0
  341. package/schemas/index-server.code-schema.json +38477 -0
  342. package/schemas/instruction.schema.json +262 -0
  343. package/schemas/json-schema/SessionPersistence-persisted-admin-session.schema.json +54 -0
  344. package/schemas/json-schema/SessionPersistence-persisted-session-history-entry.schema.json +51 -0
  345. package/schemas/json-schema/SessionPersistence-persisted-web-socket-connection.schema.json +54 -0
  346. package/schemas/json-schema/SessionPersistence-session-persistence-config.schema.json +110 -0
  347. package/schemas/json-schema/SessionPersistence-session-persistence-data.schema.json +229 -0
  348. package/schemas/json-schema/SessionPersistence-session-persistence-manifest.schema.json +109 -0
  349. package/schemas/json-schema/SessionPersistence-session-persistence-metadata.schema.json +55 -0
  350. package/schemas/json-schema/instruction-audience-scope.schema.json +14 -0
  351. package/schemas/json-schema/instruction-content-type.schema.json +17 -0
  352. package/schemas/json-schema/instruction-instruction-entry.schema.json +206 -0
  353. package/schemas/json-schema/instruction-requirement-level.schema.json +16 -0
  354. package/schemas/manifest.json +78 -0
  355. package/schemas/manifest.schema.json +33 -0
  356. package/schemas/usage-batch.schema.json +16 -0
  357. package/schemas/usage-buckets.schema.json +30 -0
  358. package/schemas/usage-event.schema.json +17 -0
  359. package/scripts/copy-dashboard-assets.mjs +170 -0
  360. package/scripts/setup-hooks.cjs +28 -0
@@ -0,0 +1,559 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SecurityMonitor = void 0;
7
+ exports.getSecurityMonitor = getSecurityMonitor;
8
+ /**
9
+ * SecurityMonitor - Phase 4 Security & Performance Monitoring
10
+ *
11
+ * Advanced security monitoring and performance analytics:
12
+ * - Real-time threat detection and alerting
13
+ * - Performance bottleneck identification
14
+ * - Resource usage monitoring
15
+ * - Security audit logging
16
+ * - Automated response mechanisms
17
+ *
18
+ * PH-3 compliance: All real user identifiers (IPs, usernames) are anonymized
19
+ * (SHA-256 hashed, first 16 hex chars) before storage or logging.
20
+ */
21
+ const crypto_1 = __importDefault(require("crypto"));
22
+ class SecurityMonitor {
23
+ threats = new Map();
24
+ performanceMetrics = new Map();
25
+ securityRules = new Map();
26
+ monitoringInterval = null;
27
+ alertCallbacks = [];
28
+ constructor() {
29
+ this.initializeSecurityRules();
30
+ this.startMonitoring();
31
+ }
32
+ /**
33
+ * Anonymize a real user identifier (IP, username, etc.) for PH-3 compliance.
34
+ * Returns the first 16 hex characters of the SHA-256 hash of the identifier.
35
+ * @param identifier - Raw user identifier to anonymize
36
+ * @returns Anonymized identifier string (not reversible)
37
+ */
38
+ anonymize(identifier) {
39
+ return crypto_1.default.createHash('sha256').update(identifier, 'utf8').digest('hex').slice(0, 16);
40
+ }
41
+ /**
42
+ * Initialize default security rules
43
+ */
44
+ initializeSecurityRules() {
45
+ const defaultRules = [
46
+ {
47
+ id: 'rate_limit_api',
48
+ name: 'API Rate Limiting',
49
+ type: 'rate_limit',
50
+ enabled: true,
51
+ config: {
52
+ maxRequests: 100,
53
+ windowMs: 60000, // 1 minute
54
+ blacklistDuration: 300000 // 5 minutes
55
+ },
56
+ triggerCount: 0
57
+ },
58
+ {
59
+ id: 'suspicious_patterns',
60
+ name: 'Suspicious Activity Detection',
61
+ type: 'pattern_detection',
62
+ enabled: true,
63
+ config: {
64
+ patterns: [
65
+ 'SELECT.*FROM.*WHERE.*1=1',
66
+ '<script>.*</script>',
67
+ '../../../etc/passwd',
68
+ 'UNION.*SELECT.*FROM'
69
+ ],
70
+ caseSensitive: false
71
+ },
72
+ triggerCount: 0
73
+ },
74
+ {
75
+ id: 'authentication_anomaly',
76
+ name: 'Authentication Anomaly Detection',
77
+ type: 'anomaly_detection',
78
+ enabled: true,
79
+ config: {
80
+ maxFailedAttempts: 5,
81
+ timeWindow: 300000, // 5 minutes
82
+ lockoutDuration: 900000 // 15 minutes
83
+ },
84
+ triggerCount: 0
85
+ }
86
+ ];
87
+ defaultRules.forEach(rule => {
88
+ this.securityRules.set(rule.id, rule);
89
+ });
90
+ }
91
+ /**
92
+ * Start continuous monitoring
93
+ */
94
+ startMonitoring() {
95
+ this.monitoringInterval = setInterval(() => {
96
+ this.collectPerformanceMetrics();
97
+ this.analyzeSecurityThreats();
98
+ this.cleanupOldData();
99
+ }, 5000); // Monitor every 5 seconds
100
+ }
101
+ /**
102
+ * Stop monitoring
103
+ */
104
+ stopMonitoring() {
105
+ if (this.monitoringInterval) {
106
+ clearInterval(this.monitoringInterval);
107
+ this.monitoringInterval = null;
108
+ }
109
+ }
110
+ /**
111
+ * Collect system performance metrics
112
+ */
113
+ collectPerformanceMetrics() {
114
+ const timestamp = Date.now();
115
+ // CPU Usage
116
+ this.addPerformanceMetric({
117
+ id: `cpu_${timestamp}`,
118
+ type: 'cpu',
119
+ value: this.getCPUUsage(),
120
+ unit: 'percentage',
121
+ timestamp,
122
+ threshold: { warning: 70, critical: 90 },
123
+ trend: 'stable'
124
+ });
125
+ // Memory Usage
126
+ const memoryUsage = process.memoryUsage();
127
+ this.addPerformanceMetric({
128
+ id: `memory_${timestamp}`,
129
+ type: 'memory',
130
+ value: (memoryUsage.heapUsed / memoryUsage.heapTotal) * 100,
131
+ unit: 'percentage',
132
+ timestamp,
133
+ threshold: { warning: 80, critical: 95 },
134
+ trend: 'stable'
135
+ });
136
+ // API Latency (simulated)
137
+ this.addPerformanceMetric({
138
+ id: `api_latency_${timestamp}`,
139
+ type: 'api_latency',
140
+ value: this.getAverageAPILatency(),
141
+ unit: 'milliseconds',
142
+ timestamp,
143
+ threshold: { warning: 500, critical: 1000 },
144
+ trend: 'stable'
145
+ });
146
+ }
147
+ /**
148
+ * Add performance metric and analyze trends
149
+ */
150
+ addPerformanceMetric(metric) {
151
+ const metricType = metric.type;
152
+ if (!this.performanceMetrics.has(metricType)) {
153
+ this.performanceMetrics.set(metricType, []);
154
+ }
155
+ const metrics = this.performanceMetrics.get(metricType);
156
+ metrics.push(metric);
157
+ // Keep only last 100 metrics per type
158
+ if (metrics.length > 100) {
159
+ metrics.splice(0, metrics.length - 100);
160
+ }
161
+ // Analyze trend
162
+ if (metrics.length >= 3) {
163
+ const recent = metrics.slice(-3);
164
+ const values = recent.map(m => m.value);
165
+ metric.trend = this.calculateTrend(values);
166
+ }
167
+ // Check thresholds and create alerts
168
+ this.checkPerformanceThresholds(metric);
169
+ }
170
+ /**
171
+ * Calculate trend from values
172
+ */
173
+ calculateTrend(values) {
174
+ if (values.length < 2)
175
+ return 'stable';
176
+ const first = values[0];
177
+ const last = values[values.length - 1];
178
+ const change = Math.abs(last - first) / first;
179
+ if (change < 0.05)
180
+ return 'stable'; // Less than 5% change
181
+ return last > first ? 'increasing' : 'decreasing';
182
+ }
183
+ /**
184
+ * Check performance thresholds and create alerts
185
+ */
186
+ checkPerformanceThresholds(metric) {
187
+ let severity = null;
188
+ if (metric.value >= metric.threshold.critical) {
189
+ severity = 'critical';
190
+ }
191
+ else if (metric.value >= metric.threshold.warning) {
192
+ severity = 'high';
193
+ }
194
+ if (severity) {
195
+ const threat = {
196
+ id: `perf_${metric.type}_${Date.now()}`,
197
+ type: 'suspicious_activity',
198
+ severity,
199
+ source: 'performance_monitor',
200
+ timestamp: metric.timestamp,
201
+ details: {
202
+ metricType: metric.type,
203
+ value: metric.value,
204
+ unit: metric.unit,
205
+ threshold: metric.threshold,
206
+ trend: metric.trend
207
+ },
208
+ status: 'active'
209
+ };
210
+ this.reportThreat(threat);
211
+ }
212
+ }
213
+ /**
214
+ * Analyze current security threats
215
+ */
216
+ analyzeSecurityThreats() {
217
+ // Check for patterns in recent activity
218
+ this.detectAnomalousPatterns();
219
+ // Check rate limiting violations
220
+ this.checkRateLimits();
221
+ // Validate authentication attempts
222
+ this.validateAuthenticationAttempts();
223
+ }
224
+ /**
225
+ * Detect anomalous patterns in system activity
226
+ */
227
+ detectAnomalousPatterns() {
228
+ const rule = this.securityRules.get('suspicious_patterns');
229
+ if (!rule || !rule.enabled)
230
+ return;
231
+ const patterns = rule.config.patterns;
232
+ const caseSensitive = rule.config.caseSensitive;
233
+ // Simulate pattern detection in request logs
234
+ const suspiciousRequest = this.checkForSuspiciousPatterns(patterns, caseSensitive);
235
+ if (suspiciousRequest) {
236
+ const threat = {
237
+ id: `pattern_${Date.now()}`,
238
+ type: 'injection_attack',
239
+ severity: 'high',
240
+ source: this.anonymize(suspiciousRequest.source),
241
+ timestamp: Date.now(),
242
+ details: {
243
+ pattern: suspiciousRequest.pattern,
244
+ userAgent: suspiciousRequest.userAgent
245
+ },
246
+ status: 'active'
247
+ };
248
+ this.reportThreat(threat);
249
+ rule.triggerCount++;
250
+ rule.lastTriggered = Date.now();
251
+ }
252
+ }
253
+ /**
254
+ * Check rate limiting violations
255
+ */
256
+ checkRateLimits() {
257
+ const rule = this.securityRules.get('rate_limit_api');
258
+ if (!rule || !rule.enabled)
259
+ return;
260
+ const config = rule.config;
261
+ // Simulate rate limit checking
262
+ const violation = this.checkRateLimitViolation(config);
263
+ if (violation) {
264
+ const anonSource = this.anonymize(violation.ip);
265
+ const threat = {
266
+ id: `rate_limit_${Date.now()}`,
267
+ type: 'rate_limit_exceeded',
268
+ severity: 'medium',
269
+ source: anonSource,
270
+ timestamp: Date.now(),
271
+ details: {
272
+ requestCount: violation.requestCount,
273
+ maxRequests: config.maxRequests,
274
+ timeWindow: config.windowMs
275
+ },
276
+ status: 'active',
277
+ actionTaken: `Source [${anonSource}] blacklisted for ${config.blacklistDuration}ms`
278
+ };
279
+ this.reportThreat(threat);
280
+ rule.triggerCount++;
281
+ rule.lastTriggered = Date.now();
282
+ }
283
+ }
284
+ /**
285
+ * Validate authentication attempts
286
+ */
287
+ validateAuthenticationAttempts() {
288
+ const rule = this.securityRules.get('authentication_anomaly');
289
+ if (!rule || !rule.enabled)
290
+ return;
291
+ const config = rule.config;
292
+ // Simulate authentication monitoring
293
+ const anomaly = this.checkAuthenticationAnomaly(config);
294
+ if (anomaly) {
295
+ const anonSource = this.anonymize(anomaly.source);
296
+ const threat = {
297
+ id: `auth_anomaly_${Date.now()}`,
298
+ type: 'authentication_failure',
299
+ severity: 'high',
300
+ source: anonSource,
301
+ timestamp: Date.now(),
302
+ details: {
303
+ failedAttempts: anomaly.attempts,
304
+ maxAllowed: config.maxFailedAttempts,
305
+ timeWindow: config.timeWindow,
306
+ accounts: anomaly.accounts.map(a => this.anonymize(a))
307
+ },
308
+ status: 'active',
309
+ actionTaken: `Source [${anonSource}] locked out for ${config.lockoutDuration}ms`
310
+ };
311
+ this.reportThreat(threat);
312
+ rule.triggerCount++;
313
+ rule.lastTriggered = Date.now();
314
+ }
315
+ }
316
+ /**
317
+ * Report a security threat
318
+ */
319
+ reportThreat(threat) {
320
+ this.threats.set(threat.id, threat);
321
+ // Notify all registered callbacks
322
+ this.alertCallbacks.forEach(callback => {
323
+ try {
324
+ callback(threat);
325
+ }
326
+ catch (error) {
327
+ console.error('Error in security alert callback:', error);
328
+ }
329
+ });
330
+ // Log to security audit trail
331
+ this.logSecurityEvent(threat);
332
+ }
333
+ /**
334
+ * Log security event to audit trail
335
+ */
336
+ logSecurityEvent(threat) {
337
+ const logEntry = {
338
+ timestamp: new Date(threat.timestamp).toISOString(),
339
+ threatId: threat.id,
340
+ type: threat.type,
341
+ severity: threat.severity,
342
+ source: threat.source,
343
+ details: threat.details,
344
+ actionTaken: threat.actionTaken
345
+ };
346
+ console.log('[SECURITY-AUDIT]', JSON.stringify(logEntry));
347
+ }
348
+ /**
349
+ * Get current system health status
350
+ */
351
+ getSystemHealth() {
352
+ const now = Date.now();
353
+ const recentThreats = Array.from(this.threats.values())
354
+ .filter(threat => threat.status === 'active' && (now - threat.timestamp) < 300000); // Last 5 minutes
355
+ // Determine overall health
356
+ let overall = 'healthy';
357
+ const criticalThreats = recentThreats.filter(t => t.severity === 'critical');
358
+ const highThreats = recentThreats.filter(t => t.severity === 'high');
359
+ if (criticalThreats.length > 0) {
360
+ overall = 'critical';
361
+ }
362
+ else if (highThreats.length > 0 || recentThreats.length > 5) {
363
+ overall = 'warning';
364
+ }
365
+ return {
366
+ overall,
367
+ services: this.getServiceStatuses(),
368
+ alerts: recentThreats,
369
+ performance: this.getRecentPerformanceMetrics()
370
+ };
371
+ }
372
+ /**
373
+ * Get service statuses
374
+ */
375
+ getServiceStatuses() {
376
+ return [
377
+ {
378
+ name: 'MCP Server',
379
+ status: 'up',
380
+ latency: this.getAverageAPILatency(),
381
+ uptime: process.uptime() * 1000,
382
+ lastCheck: Date.now()
383
+ },
384
+ {
385
+ name: 'Dashboard',
386
+ status: 'up',
387
+ latency: 50,
388
+ uptime: process.uptime() * 1000,
389
+ lastCheck: Date.now()
390
+ },
391
+ {
392
+ name: 'Analytics Engine',
393
+ status: 'up',
394
+ latency: 25,
395
+ uptime: process.uptime() * 1000,
396
+ lastCheck: Date.now()
397
+ }
398
+ ];
399
+ }
400
+ /**
401
+ * Get recent performance metrics
402
+ */
403
+ getRecentPerformanceMetrics() {
404
+ const recent = [];
405
+ const cutoff = Date.now() - 300000; // Last 5 minutes
406
+ this.performanceMetrics.forEach(metrics => {
407
+ const recentMetrics = metrics.filter(m => m.timestamp > cutoff);
408
+ recent.push(...recentMetrics);
409
+ });
410
+ return recent.sort((a, b) => b.timestamp - a.timestamp).slice(0, 20);
411
+ }
412
+ /**
413
+ * Register alert callback
414
+ */
415
+ onThreatDetected(callback) {
416
+ this.alertCallbacks.push(callback);
417
+ }
418
+ /**
419
+ * Mitigate a threat
420
+ */
421
+ mitigateThreat(threatId, action) {
422
+ const threat = this.threats.get(threatId);
423
+ if (!threat)
424
+ return false;
425
+ threat.status = 'mitigated';
426
+ threat.actionTaken = action;
427
+ this.logSecurityEvent(threat);
428
+ return true;
429
+ }
430
+ /**
431
+ * Resolve a threat
432
+ */
433
+ resolveThreat(threatId) {
434
+ const threat = this.threats.get(threatId);
435
+ if (!threat)
436
+ return false;
437
+ threat.status = 'resolved';
438
+ this.logSecurityEvent(threat);
439
+ return true;
440
+ }
441
+ /**
442
+ * Get list of active threats
443
+ */
444
+ getActiveThreats() {
445
+ const activeThreats = [];
446
+ const threatValues = Array.from(this.threats.values());
447
+ for (const threat of threatValues) {
448
+ if (threat.status === 'active') {
449
+ activeThreats.push(threat);
450
+ }
451
+ }
452
+ return activeThreats;
453
+ }
454
+ /**
455
+ * Clean up old data
456
+ */
457
+ cleanupOldData() {
458
+ const cutoff = Date.now() - 86400000; // 24 hours
459
+ // Clean old threats
460
+ const threatEntries = Array.from(this.threats.entries());
461
+ for (const [id, threat] of threatEntries) {
462
+ if (threat.timestamp < cutoff) {
463
+ this.threats.delete(id);
464
+ }
465
+ }
466
+ // Clean old performance metrics
467
+ this.performanceMetrics.forEach(metrics => {
468
+ const filtered = metrics.filter(m => m.timestamp > cutoff);
469
+ metrics.splice(0, metrics.length, ...filtered);
470
+ });
471
+ }
472
+ // Utility methods for simulated monitoring
473
+ getCPUUsage() {
474
+ // Simulate CPU usage between 10-80%
475
+ return Math.random() * 70 + 10;
476
+ }
477
+ getAverageAPILatency() {
478
+ // Simulate API latency between 50-300ms
479
+ return Math.random() * 250 + 50;
480
+ }
481
+ checkForSuspiciousPatterns(patterns, _caseSensitive) {
482
+ // Simulate 1% chance of detecting suspicious pattern
483
+ if (Math.random() < 0.01) {
484
+ const pattern = patterns[Math.floor(Math.random() * patterns.length)];
485
+ return {
486
+ pattern,
487
+ request: `/api/search?q=${pattern}`,
488
+ source: `192.168.1.${Math.floor(Math.random() * 255)}`,
489
+ userAgent: 'Mozilla/5.0 (compatible; SecurityScanner/1.0)'
490
+ };
491
+ }
492
+ return null;
493
+ }
494
+ checkRateLimitViolation(config) {
495
+ // Simulate 0.5% chance of rate limit violation
496
+ if (Math.random() < 0.005) {
497
+ return {
498
+ ip: `192.168.1.${Math.floor(Math.random() * 255)}`,
499
+ requestCount: config.maxRequests + Math.floor(Math.random() * 50),
500
+ userAgent: 'Mozilla/5.0 (compatible; BotScanner/1.0)'
501
+ };
502
+ }
503
+ return null;
504
+ }
505
+ checkAuthenticationAnomaly(config) {
506
+ // Simulate 0.2% chance of authentication anomaly
507
+ if (Math.random() < 0.002) {
508
+ return {
509
+ source: `192.168.1.${Math.floor(Math.random() * 255)}`,
510
+ attempts: config.maxFailedAttempts + Math.floor(Math.random() * 10),
511
+ accounts: ['admin', 'root', 'user', 'test'].slice(0, Math.floor(Math.random() * 4) + 1)
512
+ };
513
+ }
514
+ return null;
515
+ }
516
+ /**
517
+ * Get security rules configuration
518
+ */
519
+ getSecurityRules() {
520
+ return Array.from(this.securityRules.values());
521
+ }
522
+ /**
523
+ * Update security rule
524
+ */
525
+ updateSecurityRule(ruleId, updates) {
526
+ const rule = this.securityRules.get(ruleId);
527
+ if (!rule)
528
+ return false;
529
+ Object.assign(rule, updates);
530
+ return true;
531
+ }
532
+ /**
533
+ * Get threat statistics
534
+ */
535
+ getThreatStatistics() {
536
+ const threats = Array.from(this.threats.values());
537
+ const stats = {
538
+ total: threats.length,
539
+ active: threats.filter(t => t.status === 'active').length,
540
+ resolved: threats.filter(t => t.status === 'resolved').length,
541
+ byType: {},
542
+ bySeverity: {}
543
+ };
544
+ threats.forEach(threat => {
545
+ stats.byType[threat.type] = (stats.byType[threat.type] || 0) + 1;
546
+ stats.bySeverity[threat.severity] = (stats.bySeverity[threat.severity] || 0) + 1;
547
+ });
548
+ return stats;
549
+ }
550
+ }
551
+ exports.SecurityMonitor = SecurityMonitor;
552
+ // Singleton instance
553
+ let securityMonitor = null;
554
+ function getSecurityMonitor() {
555
+ if (!securityMonitor) {
556
+ securityMonitor = new SecurityMonitor();
557
+ }
558
+ return securityMonitor;
559
+ }