xypriss 1.2.4 → 1.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 (103) hide show
  1. package/README.md +51 -3
  2. package/dist/cjs/mods/security/src/components/cache/index.js +1 -1
  3. package/dist/cjs/shared/logger/Logger.js +1 -0
  4. package/dist/cjs/shared/logger/Logger.js.map +1 -1
  5. package/dist/cjs/src/cluster/bun-cluster-manager.js +1567 -0
  6. package/dist/cjs/src/cluster/bun-cluster-manager.js.map +1 -0
  7. package/dist/cjs/src/cluster/cluster-manager.js +1 -1
  8. package/dist/cjs/src/cluster/cluster-manager.js.map +1 -1
  9. package/dist/cjs/src/cluster/index.js +25 -6
  10. package/dist/cjs/src/cluster/index.js.map +1 -1
  11. package/dist/cjs/src/cluster/memory-manager.js +463 -0
  12. package/dist/cjs/src/cluster/memory-manager.js.map +1 -0
  13. package/dist/cjs/src/cluster/modules/BunIPCManager.js +603 -0
  14. package/dist/cjs/src/cluster/modules/BunIPCManager.js.map +1 -0
  15. package/dist/cjs/src/cluster/modules/ClusterFactory.js +22 -1
  16. package/dist/cjs/src/cluster/modules/ClusterFactory.js.map +1 -1
  17. package/dist/cjs/src/cluster/modules/CpuMonitor.js +658 -0
  18. package/dist/cjs/src/cluster/modules/CpuMonitor.js.map +1 -0
  19. package/dist/cjs/src/cluster/modules/ProcessMonitor.js +513 -0
  20. package/dist/cjs/src/cluster/modules/ProcessMonitor.js.map +1 -0
  21. package/dist/cjs/src/plugins/server-maintenance-plugin.js +1 -1
  22. package/dist/cjs/src/server/FastServer.js +64 -43
  23. package/dist/cjs/src/server/FastServer.js.map +1 -1
  24. package/dist/cjs/src/server/components/fastapi/ClusterManagerComponent.js +226 -10
  25. package/dist/cjs/src/server/components/fastapi/ClusterManagerComponent.js.map +1 -1
  26. package/dist/cjs/src/server/const/Cluster.config.js +174 -31
  27. package/dist/cjs/src/server/const/Cluster.config.js.map +1 -1
  28. package/dist/cjs/src/server/const/default.js +11 -2
  29. package/dist/cjs/src/server/const/default.js.map +1 -1
  30. package/dist/cjs/src/server/utils/PortManager.js +26 -15
  31. package/dist/cjs/src/server/utils/PortManager.js.map +1 -1
  32. package/dist/esm/mods/security/src/components/cache/index.js +1 -1
  33. package/dist/esm/shared/logger/Logger.js +1 -0
  34. package/dist/esm/shared/logger/Logger.js.map +1 -1
  35. package/dist/esm/src/cluster/bun-cluster-manager.js +1565 -0
  36. package/dist/esm/src/cluster/bun-cluster-manager.js.map +1 -0
  37. package/dist/esm/src/cluster/cluster-manager.js +1 -1
  38. package/dist/esm/src/cluster/cluster-manager.js.map +1 -1
  39. package/dist/esm/src/cluster/index.js +25 -6
  40. package/dist/esm/src/cluster/index.js.map +1 -1
  41. package/dist/esm/src/cluster/memory-manager.js +461 -0
  42. package/dist/esm/src/cluster/memory-manager.js.map +1 -0
  43. package/dist/esm/src/cluster/modules/BunIPCManager.js +601 -0
  44. package/dist/esm/src/cluster/modules/BunIPCManager.js.map +1 -0
  45. package/dist/esm/src/cluster/modules/ClusterFactory.js +22 -1
  46. package/dist/esm/src/cluster/modules/ClusterFactory.js.map +1 -1
  47. package/dist/esm/src/cluster/modules/CpuMonitor.js +656 -0
  48. package/dist/esm/src/cluster/modules/CpuMonitor.js.map +1 -0
  49. package/dist/esm/src/cluster/modules/ProcessMonitor.js +511 -0
  50. package/dist/esm/src/cluster/modules/ProcessMonitor.js.map +1 -0
  51. package/dist/esm/src/plugins/server-maintenance-plugin.js +1 -1
  52. package/dist/esm/src/server/FastServer.js +64 -43
  53. package/dist/esm/src/server/FastServer.js.map +1 -1
  54. package/dist/esm/src/server/components/fastapi/ClusterManagerComponent.js +226 -10
  55. package/dist/esm/src/server/components/fastapi/ClusterManagerComponent.js.map +1 -1
  56. package/dist/esm/src/server/const/Cluster.config.js +174 -31
  57. package/dist/esm/src/server/const/Cluster.config.js.map +1 -1
  58. package/dist/esm/src/server/const/default.js +11 -2
  59. package/dist/esm/src/server/const/default.js.map +1 -1
  60. package/dist/esm/src/server/utils/PortManager.js +26 -15
  61. package/dist/esm/src/server/utils/PortManager.js.map +1 -1
  62. package/dist/index.d.ts +78 -1
  63. package/package.json +3 -1
  64. package/dist/cjs/src/plugins/modules/network/index.js +0 -120
  65. package/dist/cjs/src/plugins/modules/network/index.js.map +0 -1
  66. package/dist/cjs/src/server/plugins/PluginEngine.js +0 -378
  67. package/dist/cjs/src/server/plugins/PluginEngine.js.map +0 -1
  68. package/dist/cjs/src/server/plugins/PluginRegistry.js +0 -339
  69. package/dist/cjs/src/server/plugins/PluginRegistry.js.map +0 -1
  70. package/dist/cjs/src/server/plugins/builtin/JWTAuthPlugin.js +0 -591
  71. package/dist/cjs/src/server/plugins/builtin/JWTAuthPlugin.js.map +0 -1
  72. package/dist/cjs/src/server/plugins/builtin/ResponseTimePlugin.js +0 -413
  73. package/dist/cjs/src/server/plugins/builtin/ResponseTimePlugin.js.map +0 -1
  74. package/dist/cjs/src/server/plugins/builtin/SmartCachePlugin.js +0 -843
  75. package/dist/cjs/src/server/plugins/builtin/SmartCachePlugin.js.map +0 -1
  76. package/dist/cjs/src/server/plugins/core/CachePlugin.js +0 -1975
  77. package/dist/cjs/src/server/plugins/core/CachePlugin.js.map +0 -1
  78. package/dist/cjs/src/server/plugins/core/PerformancePlugin.js +0 -894
  79. package/dist/cjs/src/server/plugins/core/PerformancePlugin.js.map +0 -1
  80. package/dist/cjs/src/server/plugins/core/SecurityPlugin.js +0 -799
  81. package/dist/cjs/src/server/plugins/core/SecurityPlugin.js.map +0 -1
  82. package/dist/cjs/src/server/plugins/types/PluginTypes.js +0 -47
  83. package/dist/cjs/src/server/plugins/types/PluginTypes.js.map +0 -1
  84. package/dist/esm/src/plugins/modules/network/index.js +0 -109
  85. package/dist/esm/src/plugins/modules/network/index.js.map +0 -1
  86. package/dist/esm/src/server/plugins/PluginEngine.js +0 -376
  87. package/dist/esm/src/server/plugins/PluginEngine.js.map +0 -1
  88. package/dist/esm/src/server/plugins/PluginRegistry.js +0 -337
  89. package/dist/esm/src/server/plugins/PluginRegistry.js.map +0 -1
  90. package/dist/esm/src/server/plugins/builtin/JWTAuthPlugin.js +0 -589
  91. package/dist/esm/src/server/plugins/builtin/JWTAuthPlugin.js.map +0 -1
  92. package/dist/esm/src/server/plugins/builtin/ResponseTimePlugin.js +0 -411
  93. package/dist/esm/src/server/plugins/builtin/ResponseTimePlugin.js.map +0 -1
  94. package/dist/esm/src/server/plugins/builtin/SmartCachePlugin.js +0 -841
  95. package/dist/esm/src/server/plugins/builtin/SmartCachePlugin.js.map +0 -1
  96. package/dist/esm/src/server/plugins/core/CachePlugin.js +0 -1973
  97. package/dist/esm/src/server/plugins/core/CachePlugin.js.map +0 -1
  98. package/dist/esm/src/server/plugins/core/PerformancePlugin.js +0 -872
  99. package/dist/esm/src/server/plugins/core/PerformancePlugin.js.map +0 -1
  100. package/dist/esm/src/server/plugins/core/SecurityPlugin.js +0 -797
  101. package/dist/esm/src/server/plugins/core/SecurityPlugin.js.map +0 -1
  102. package/dist/esm/src/server/plugins/types/PluginTypes.js +0 -47
  103. package/dist/esm/src/server/plugins/types/PluginTypes.js.map +0 -1
@@ -1,799 +0,0 @@
1
- 'use strict';
2
-
3
- var index$1 = require('../../../../mods/security/src/components/fortified-function/index.js');
4
- var hashCore = require('../../../../mods/security/src/core/hash/hash-core.js');
5
- require('../../../../mods/security/src/core/hash/hash-types.js');
6
- require('crypto');
7
- require('../../../../mods/security/src/core/hash/hash-security.js');
8
- require('../../../../mods/security/src/core/hash/hash-advanced.js');
9
- require('../../../../mods/security/src/algorithms/hash-algorithms.js');
10
- var PluginTypes = require('../types/PluginTypes.js');
11
- var index = require('../../../../mods/security/src/index.js');
12
-
13
- /**
14
- * Security Plugin Base Class - Ultra-Fast Security Framework
15
- *
16
- * Lean, ultra-fast security plugin framework providing essential security infrastructure
17
- * while allowing users to plug in their own authentication/authorization systems.
18
- *
19
- * Performance Target: <2ms execution time for security operations
20
- * Focus: Framework-level security that integrates with any authentication system
21
- */
22
- // import { sqlPatterns, xssPatterns } from "../../../../mods/security/src/utils/patterns";
23
- // import { SecurityRateLimiter } from "../../../../mods/security/src/utils/securityUtils";
24
- // import { TamperEvidentLogger, LogLevel } from "../../../../mods/security/src/components/tamper-evident-logging";
25
- // Fallback implementations for missing imports
26
- const sqlPatterns = [/union.*select/i, /drop.*table/i, /insert.*into/i];
27
- const xssPatterns = [/<script/i, /javascript:/i, /on\w+\s*=/i];
28
- var LogLevel;
29
- (function (LogLevel) {
30
- LogLevel["INFO"] = "info";
31
- LogLevel["WARN"] = "warn";
32
- LogLevel["ERROR"] = "error";
33
- })(LogLevel || (LogLevel = {}));
34
- /**
35
- * Abstract base class for security plugins
36
- */
37
- class SecurityPlugin {
38
- constructor() {
39
- this.type = PluginTypes.PluginType.SECURITY;
40
- this.priority = PluginTypes.PluginPriority.HIGH;
41
- this.isAsync = true;
42
- this.isCacheable = false; // Security operations should not be cached
43
- this.maxExecutionTime = 2000; // 2ms max for security operations
44
- // Security configuration
45
- this.securityLevel = "enhanced";
46
- this.encryptionRequired = true;
47
- this.auditLogging = true;
48
- }
49
- /**
50
- * Initialize security plugin with XyPrissJS utilities
51
- */
52
- async initialize(context) {
53
- // Initialize XyPrissJS security utilities
54
- this.hashUtil = hashCore.Hash;
55
- this.secureObjectUtil = index.fObject;
56
- // Initialize audit logging with fallback implementation
57
- this.auditLogger = {
58
- log: (level, message, data) => {
59
- console.log(`[${level}] ${message}`, data);
60
- },
61
- };
62
- // Initialize rate limiting with fallback implementation
63
- this.rateLimiter = {
64
- isAllowed: (key) => true, // Fallback always allows
65
- recordAttempt: (key) => { },
66
- reset: (key) => { },
67
- };
68
- this.slidingWindowLimiter = new Map();
69
- // Create fortified execution wrapper for ultra-fast security operations
70
- this.fortifiedExecute = index$1.func(async (operation) => {
71
- return await operation();
72
- }, {
73
- ultraFast: "maximum",
74
- autoEncrypt: this.encryptionRequired,
75
- auditLog: this.auditLogging,
76
- timeout: this.maxExecutionTime,
77
- errorHandling: "graceful",
78
- });
79
- // Perform plugin-specific initialization
80
- await this.initializeSecurityPlugin(context);
81
- }
82
- /**
83
- * Execute security plugin with comprehensive protection
84
- */
85
- async execute(context) {
86
- const startTime = performance.now();
87
- try {
88
- // Pre-execution security checks
89
- const preCheckResult = await this.preExecutionSecurityCheck(context);
90
- if (!preCheckResult.success) {
91
- return preCheckResult;
92
- }
93
- // Execute main security logic
94
- const result = await this.fortifiedExecute(async () => {
95
- return await this.executeSecurityLogic(context);
96
- });
97
- const executionTime = performance.now() - startTime;
98
- // Post-execution security validation
99
- const validationResult = await this.postExecutionValidation(context, result);
100
- if (!validationResult.success) {
101
- return validationResult;
102
- }
103
- // Log security event if audit logging is enabled
104
- if (this.auditLogging) {
105
- await this.logSecurityEvent(context, result, executionTime);
106
- }
107
- return {
108
- success: true,
109
- executionTime,
110
- data: result,
111
- shouldContinue: true,
112
- };
113
- }
114
- catch (error) {
115
- const executionTime = performance.now() - startTime;
116
- // Log security error
117
- await this.logSecurityError(context, error, executionTime);
118
- return {
119
- success: false,
120
- executionTime,
121
- error,
122
- shouldContinue: this.shouldContinueOnError(error),
123
- };
124
- }
125
- }
126
- /**
127
- * Validate input data for security threats
128
- */
129
- async validateInput(context) {
130
- try {
131
- // Validate request body
132
- if (context.req.body &&
133
- !this.validateRequestBody(context.req.body)) {
134
- return false;
135
- }
136
- // Validate query parameters
137
- if (context.req.query &&
138
- !this.validateQueryParameters(context.req.query)) {
139
- return false;
140
- }
141
- // Validate headers
142
- if (!this.validateHeaders(context.req.headers)) {
143
- return false;
144
- }
145
- return true;
146
- }
147
- catch (error) {
148
- console.error(`Input validation error in plugin ${this.id}:`, error);
149
- return false;
150
- }
151
- }
152
- /**
153
- * Sanitize data to prevent security vulnerabilities
154
- */
155
- sanitizeData(data) {
156
- if (!data)
157
- return data;
158
- try {
159
- // Use fObject for secure data handling
160
- const secureData = this.secureObjectUtil(data);
161
- // Apply sanitization rules
162
- return this.applySanitizationRules(secureData.getAll());
163
- }
164
- catch (error) {
165
- console.error(`Data sanitization error in plugin ${this.id}:`, error);
166
- return data; // Return original data if sanitization fails
167
- }
168
- }
169
- // ===== SECURITY IMPLEMENTATIONS =====
170
- /**
171
- * Initialize plugin-specific security features
172
- * implementation with comprehensive security setup
173
- */
174
- async initializeSecurityPlugin(context) {
175
- try {
176
- // Initialize security patterns from configuration
177
- if (context.config.customSettings.securityPatterns) {
178
- this.initializeSecurityPatterns(context.config.customSettings.securityPatterns);
179
- }
180
- // Setup rate limiting thresholds
181
- if (context.config.customSettings.rateLimiting) {
182
- this.setupRateLimitingConfig(context.config.customSettings.rateLimiting);
183
- }
184
- // Note: Authentication providers should be implemented by users
185
- // This framework provides only the security infrastructure
186
- // Setup security monitoring
187
- if (context.config.enableAuditLogging) {
188
- this.setupSecurityMonitoring(context);
189
- }
190
- context.logger.info(`Security plugin ${this.constructor.name} initialized successfully`);
191
- }
192
- catch (error) {
193
- context.logger.error(`Error initializing security plugin: ${error.message}`, error);
194
- throw error;
195
- }
196
- }
197
- /**
198
- * Execute main security logic
199
- * implementation with comprehensive security checks
200
- */
201
- async executeSecurityLogic(context) {
202
- try {
203
- const securityResults = {
204
- inputValidation: false,
205
- rateLimitCheck: false,
206
- threatDetection: false,
207
- authenticationStatus: context.security.isAuthenticated,
208
- securityScore: 0,
209
- threats: [],
210
- recommendations: [],
211
- };
212
- // Perform input validation
213
- securityResults.inputValidation = await this.validateInput(context);
214
- if (!securityResults.inputValidation) {
215
- securityResults.threats.push("Invalid input detected");
216
- }
217
- // Perform threat detection
218
- securityResults.threatDetection =
219
- !this.detectSuspiciousActivity(context);
220
- if (!securityResults.threatDetection) {
221
- securityResults.threats.push("Suspicious activity detected");
222
- }
223
- // Calculate security score
224
- securityResults.securityScore =
225
- this.calculateSecurityScore(securityResults);
226
- // Generate security recommendations
227
- securityResults.recommendations =
228
- this.generateSecurityRecommendations(securityResults);
229
- return securityResults;
230
- }
231
- catch (error) {
232
- console.error(`Error executing security logic: ${error.message}`);
233
- return {
234
- error: error.message,
235
- securityScore: 0,
236
- threats: ["Security check failed"],
237
- };
238
- }
239
- }
240
- /**
241
- * Framework-level authentication validation
242
- * Note: Users should implement their own authentication logic
243
- */
244
- async performAuthentication(authData, context) {
245
- try {
246
- if (!authData) {
247
- return false;
248
- }
249
- // Framework-level validation only
250
- // Users should override this method with their own authentication logic
251
- console.warn(`SecurityPlugin.performAuthentication called but not implemented. ` +
252
- `Users should implement their own authentication logic for type: ${authData.type}`);
253
- return false; // Default to deny access
254
- }
255
- catch (error) {
256
- console.error(`Authentication framework error: ${error.message}`);
257
- return false;
258
- }
259
- }
260
- /**
261
- * Framework-level authorization validation
262
- * Note: Users should implement their own authorization logic
263
- */
264
- async performAuthorization(context, resource) {
265
- try {
266
- // Check if user is authenticated
267
- if (!context.security.isAuthenticated) {
268
- return false;
269
- }
270
- // Framework-level validation only
271
- // Users should override this method with their own authorization logic
272
- console.warn(`SecurityPlugin.performAuthorization called but not implemented. ` +
273
- `Users should implement their own authorization logic for resource: ${resource}`);
274
- return false; // Default to deny access
275
- }
276
- catch (error) {
277
- console.error(`Authorization framework error: ${error.message}`);
278
- return false;
279
- }
280
- }
281
- // ===== PROTECTED HELPER METHODS =====
282
- /**
283
- * Pre-execution security check
284
- */
285
- async preExecutionSecurityCheck(context) {
286
- // Check for common security threats
287
- if (this.detectSuspiciousActivity(context)) {
288
- return {
289
- success: false,
290
- executionTime: 0,
291
- error: new Error("Suspicious activity detected"),
292
- shouldContinue: false,
293
- };
294
- }
295
- return { success: true, executionTime: 0, shouldContinue: true };
296
- }
297
- /**
298
- * Post-execution validation
299
- */
300
- async postExecutionValidation(_context, result) {
301
- // Validate result data
302
- if (result && typeof result === "object") {
303
- const sanitizedResult = this.sanitizeData(result);
304
- if (sanitizedResult !== result) {
305
- console.warn(`Plugin ${this.id} result was sanitized`);
306
- }
307
- }
308
- return { success: true, executionTime: 0, shouldContinue: true };
309
- }
310
- /**
311
- * Extract authentication data from request
312
- */
313
- extractAuthenticationData(context) {
314
- const { req } = context;
315
- // Extract from Authorization header
316
- const authHeader = req.headers.authorization;
317
- if (authHeader) {
318
- return this.parseAuthorizationHeader(authHeader);
319
- }
320
- // Extract from cookies
321
- if (req.cookies) {
322
- return this.parseAuthenticationCookies(req.cookies);
323
- }
324
- // Extract from session
325
- if (req.session) {
326
- return this.parseSessionData(req.session);
327
- }
328
- return null;
329
- }
330
- /**
331
- * Detect suspicious activity patterns
332
- */
333
- detectSuspiciousActivity(context) {
334
- const { req } = context;
335
- // Check for SQL injection patterns
336
- if (this.containsSqlInjectionPatterns(req)) {
337
- return true;
338
- }
339
- // Check for XSS patterns
340
- if (this.containsXssPatterns(req)) {
341
- return true;
342
- }
343
- return false;
344
- }
345
- /**
346
- * Log security event for audit trail
347
- * implementation using TamperEvidentLogger
348
- */
349
- async logSecurityEvent(context, result, executionTime) {
350
- const logData = {
351
- pluginId: this.id,
352
- executionId: context.executionId,
353
- userId: context.security.userId,
354
- action: "security_check",
355
- result: result ? "success" : "failure",
356
- executionTime,
357
- ipAddress: context.req.ip,
358
- userAgent: context.req.headers["user-agent"],
359
- path: context.req.path,
360
- method: context.req.method,
361
- securityScore: result?.securityScore || 0,
362
- threats: result?.threats || [],
363
- timestamp: Date.now(),
364
- };
365
- // Use tamper-evident audit logging
366
- this.auditLogger.info(`Security check completed for plugin ${this.id}`, logData);
367
- }
368
- /**
369
- * Log security error
370
- * implementation using TamperEvidentLogger
371
- */
372
- async logSecurityError(context, error, executionTime) {
373
- const logData = {
374
- pluginId: this.id,
375
- executionId: context.executionId,
376
- error: error.message,
377
- stack: error.stack,
378
- executionTime,
379
- ipAddress: context.req.ip,
380
- userAgent: context.req.headers["user-agent"],
381
- path: context.req.path,
382
- method: context.req.method,
383
- timestamp: Date.now(),
384
- };
385
- // Use tamper-evident audit logging for security errors
386
- this.auditLogger.error(`Security error in plugin ${this.id}`, logData);
387
- }
388
- /**
389
- * Determine if execution should continue after error
390
- */
391
- shouldContinueOnError(_error) {
392
- // Security errors should generally stop execution
393
- return false;
394
- }
395
- // ===== VALIDATION HELPER METHODS =====
396
- validateRequestBody(body) {
397
- if (!body || typeof body !== "object") {
398
- return true; // No body to validate
399
- }
400
- try {
401
- // Check for suspicious patterns in body
402
- const bodyString = JSON.stringify(body);
403
- for (const pattern of sqlPatterns) {
404
- if (pattern.test(bodyString)) {
405
- console.warn(`SQL injection pattern detected in request body: ${this.id}`);
406
- return false;
407
- }
408
- }
409
- for (const pattern of xssPatterns) {
410
- if (pattern.test(bodyString)) {
411
- console.warn(`XSS pattern detected in request body: ${this.id}`);
412
- return false;
413
- }
414
- }
415
- return true;
416
- }
417
- catch (error) {
418
- console.error(`Error validating request body: ${error}`);
419
- return false;
420
- }
421
- }
422
- validateQueryParameters(query) {
423
- if (!query || typeof query !== "object") {
424
- return true; // No query params to validate
425
- }
426
- try {
427
- for (const [key, value] of Object.entries(query)) {
428
- if (typeof value === "string") {
429
- // Check for path traversal
430
- if (value.includes("../") || value.includes("..\\")) {
431
- console.warn(`Path traversal detected in query param ${key}: ${this.id}`);
432
- return false;
433
- }
434
- // Check for command injection
435
- const cmdPatterns = [
436
- /[;&|`$()]/,
437
- /\b(cat|ls|pwd|whoami|id|uname|ps|netstat|ifconfig)\b/i,
438
- ];
439
- for (const pattern of cmdPatterns) {
440
- if (pattern.test(value)) {
441
- console.warn(`Command injection pattern detected in query param ${key}: ${this.id}`);
442
- return false;
443
- }
444
- }
445
- }
446
- }
447
- return true;
448
- }
449
- catch (error) {
450
- console.error(`Error validating query parameters: ${error}`);
451
- return false;
452
- }
453
- }
454
- validateHeaders(headers) {
455
- if (!headers || typeof headers !== "object") {
456
- return true; // No headers to validate
457
- }
458
- try {
459
- // Check for suspicious user agents
460
- const userAgent = headers["user-agent"];
461
- if (userAgent) {
462
- const suspiciousPatterns = [
463
- /sqlmap/i,
464
- /nikto/i,
465
- /nessus/i,
466
- /burp/i,
467
- /scanner/i,
468
- ];
469
- for (const pattern of suspiciousPatterns) {
470
- if (pattern.test(userAgent)) {
471
- console.warn(`Suspicious user agent detected: ${this.id}`);
472
- return false;
473
- }
474
- }
475
- }
476
- // Check for header injection
477
- for (const [key, value] of Object.entries(headers)) {
478
- if (typeof value === "string") {
479
- if (value.includes("\r") || value.includes("\n")) {
480
- console.warn(`Header injection detected in ${key}: ${this.id}`);
481
- return false;
482
- }
483
- }
484
- }
485
- return true;
486
- }
487
- catch (error) {
488
- console.error(`Error validating headers: ${error}`);
489
- return false;
490
- }
491
- }
492
- applySanitizationRules(data) {
493
- if (!data || typeof data !== "object") {
494
- return data;
495
- }
496
- try {
497
- // Use fObject for secure data handling
498
- const secureData = this.secureObjectUtil(data);
499
- // Get sanitized data
500
- const sanitized = secureData.getAll();
501
- // Additional sanitization for common security issues
502
- if (sanitized.password) {
503
- // Never return passwords in sanitized data
504
- delete sanitized.password;
505
- }
506
- if (sanitized.token && typeof sanitized.token === "string") {
507
- // Sanitize tokens to alphanumeric and common token characters only
508
- sanitized.token = sanitized.token.replace(/[^A-Za-z0-9._-]/g, "");
509
- }
510
- return sanitized;
511
- }
512
- catch (error) {
513
- console.error(`Error applying sanitization rules: ${error}`);
514
- return data; // Return original data if sanitization fails
515
- }
516
- }
517
- parseAuthorizationHeader(header) {
518
- try {
519
- if (header.startsWith("Bearer ")) {
520
- const token = header.substring(7);
521
- return {
522
- type: "bearer",
523
- token: token,
524
- userId: null, // Will be extracted from token
525
- };
526
- }
527
- if (header.startsWith("Basic ")) {
528
- const credentials = Buffer.from(header.substring(6), "base64").toString("utf8");
529
- const [username, password] = credentials.split(":");
530
- return {
531
- type: "basic",
532
- username,
533
- password,
534
- userId: username,
535
- };
536
- }
537
- return null;
538
- }
539
- catch (error) {
540
- console.error(`Error parsing authorization header: ${error}`);
541
- return null;
542
- }
543
- }
544
- parseAuthenticationCookies(cookies) {
545
- try {
546
- if (cookies.token) {
547
- return {
548
- type: "cookie",
549
- token: cookies.token,
550
- userId: null, // Will be extracted from token
551
- };
552
- }
553
- if (cookies.sessionId) {
554
- return {
555
- type: "session",
556
- sessionId: cookies.sessionId,
557
- userId: null, // Will be extracted from session
558
- };
559
- }
560
- return null;
561
- }
562
- catch (error) {
563
- console.error(`Error parsing authentication cookies: ${error}`);
564
- return null;
565
- }
566
- }
567
- parseSessionData(session) {
568
- try {
569
- if (session.userId) {
570
- return {
571
- type: "session",
572
- userId: session.userId,
573
- roles: session.roles || [],
574
- permissions: session.permissions || [],
575
- };
576
- }
577
- return null;
578
- }
579
- catch (error) {
580
- console.error(`Error parsing session data: ${error}`);
581
- return null;
582
- }
583
- }
584
- containsSqlInjectionPatterns(req) {
585
- try {
586
- // Check URL path
587
- const path = req.path || "";
588
- const query = req.query || {};
589
- const body = req.body || {};
590
- // Combine all input sources
591
- const inputs = [
592
- path,
593
- JSON.stringify(query),
594
- JSON.stringify(body),
595
- ].join(" ");
596
- return sqlPatterns.some((pattern) => pattern.test(inputs));
597
- }
598
- catch (error) {
599
- console.error(`Error checking SQL injection patterns: ${error}`);
600
- return false;
601
- }
602
- }
603
- containsXssPatterns(req) {
604
- try {
605
- // Check URL path, query, and body
606
- const path = req.path || "";
607
- const query = req.query || {};
608
- const body = req.body || {};
609
- // Combine all input sources
610
- const inputs = [
611
- path,
612
- JSON.stringify(query),
613
- JSON.stringify(body),
614
- ].join(" ");
615
- return xssPatterns.some((pattern) => pattern.test(inputs));
616
- }
617
- catch (error) {
618
- console.error(`Error checking XSS patterns: ${error}`);
619
- return false;
620
- }
621
- }
622
- /**
623
- * Clean up expired rate limiting data (call periodically)
624
- */
625
- cleanupRateLimitingData() {
626
- if (!this.slidingWindowLimiter) {
627
- return;
628
- }
629
- const now = Date.now();
630
- const windowMs = 60000; // 1 minute
631
- for (const [clientIp, clientData,] of this.slidingWindowLimiter.entries()) {
632
- // Remove expired requests
633
- clientData.requests = clientData.requests.filter((timestamp) => now - timestamp < windowMs);
634
- // Remove expired blocks
635
- if (clientData.blocked &&
636
- clientData.blockExpiry &&
637
- now >= clientData.blockExpiry) {
638
- clientData.blocked = false;
639
- delete clientData.blockExpiry;
640
- }
641
- // Remove empty entries
642
- if (clientData.requests.length === 0 && !clientData.blocked) {
643
- this.slidingWindowLimiter.delete(clientIp);
644
- }
645
- }
646
- }
647
- /**
648
- * Get rate limiting statistics
649
- */
650
- getRateLimitingStats() {
651
- if (!this.slidingWindowLimiter) {
652
- return { totalClients: 0, blockedClients: 0, totalRequests: 0 };
653
- }
654
- let blockedClients = 0;
655
- let totalRequests = 0;
656
- for (const clientData of this.slidingWindowLimiter.values()) {
657
- if (clientData.blocked) {
658
- blockedClients++;
659
- }
660
- totalRequests += clientData.requests.length;
661
- }
662
- return {
663
- totalClients: this.slidingWindowLimiter.size,
664
- blockedClients,
665
- totalRequests,
666
- };
667
- }
668
- // ===== SECURITY HELPER METHODS =====
669
- /**
670
- * Initialize security patterns from configuration
671
- */
672
- initializeSecurityPatterns(patterns) {
673
- try {
674
- // Initialize custom SQL injection patterns
675
- if (patterns.sqlInjection) {
676
- sqlPatterns.push(...patterns.sqlInjection.map((p) => new RegExp(p, "i")));
677
- }
678
- // Initialize custom XSS patterns
679
- if (patterns.xss) {
680
- xssPatterns.push(...patterns.xss.map((p) => new RegExp(p, "i")));
681
- }
682
- console.debug("Security patterns initialized successfully");
683
- }
684
- catch (error) {
685
- console.error("Error initializing security patterns:", error);
686
- }
687
- }
688
- /**
689
- * Setup rate limiting configuration
690
- */
691
- setupRateLimitingConfig(config) {
692
- try {
693
- if (config.maxAttempts && config.windowMs) {
694
- this.rateLimiter = {
695
- isAllowed: (key) => true, // Fallback always allows
696
- recordAttempt: (key) => { },
697
- reset: (key) => { },
698
- };
699
- }
700
- console.debug("Rate limiting configuration setup completed");
701
- }
702
- catch (error) {
703
- console.error("Error setting up rate limiting config:", error);
704
- }
705
- }
706
- /**
707
- * Framework-level authentication provider initialization
708
- * Note: Users should implement their own authentication providers
709
- */
710
- async initializeAuthProviders(providers) {
711
- try {
712
- // Framework-level initialization only
713
- // Users should override this method to implement their own authentication providers
714
- console.warn(`SecurityPlugin.initializeAuthProviders called but not implemented. ` +
715
- `Users should implement their own authentication providers for: ${Object.keys(providers).join(", ")}`);
716
- console.debug("Authentication provider framework initialized");
717
- }
718
- catch (error) {
719
- console.error("Error initializing auth provider framework:", error);
720
- }
721
- }
722
- /**
723
- * Setup security monitoring
724
- */
725
- setupSecurityMonitoring(context) {
726
- try {
727
- // Setup audit logging
728
- if (context.config.enableAuditLogging) {
729
- console.debug("Security monitoring and audit logging enabled");
730
- }
731
- // Setup threat detection monitoring
732
- console.debug("Security monitoring setup completed");
733
- }
734
- catch (error) {
735
- console.error("Error setting up security monitoring:", error);
736
- }
737
- }
738
- /**
739
- * Calculate security score based on security results
740
- */
741
- calculateSecurityScore(results) {
742
- try {
743
- let score = 100;
744
- // Deduct points for each threat
745
- score -= results.threats.length * 20;
746
- // Deduct points for failed checks
747
- if (!results.inputValidation)
748
- score -= 15;
749
- if (!results.rateLimitCheck)
750
- score -= 25;
751
- if (!results.threatDetection)
752
- score -= 30;
753
- // Bonus points for authentication
754
- if (results.authenticationStatus)
755
- score += 10;
756
- return Math.max(0, Math.min(100, score));
757
- }
758
- catch (error) {
759
- console.error("Error calculating security score:", error);
760
- return 0;
761
- }
762
- }
763
- /**
764
- * Generate security recommendations
765
- */
766
- generateSecurityRecommendations(results) {
767
- const recommendations = [];
768
- try {
769
- if (!results.inputValidation) {
770
- recommendations.push("Implement stricter input validation");
771
- recommendations.push("Consider using input sanitization libraries");
772
- }
773
- if (!results.rateLimitCheck) {
774
- recommendations.push("Review and adjust rate limiting thresholds");
775
- recommendations.push("Consider implementing progressive rate limiting");
776
- }
777
- if (!results.threatDetection) {
778
- recommendations.push("Enhance threat detection patterns");
779
- recommendations.push("Consider implementing behavioral analysis");
780
- }
781
- if (!results.authenticationStatus) {
782
- recommendations.push("Implement proper authentication mechanisms");
783
- recommendations.push("Consider multi-factor authentication");
784
- }
785
- if (results.securityScore < 70) {
786
- recommendations.push("Overall security posture needs improvement");
787
- recommendations.push("Consider security audit and penetration testing");
788
- }
789
- return recommendations;
790
- }
791
- catch (error) {
792
- console.error("Error generating security recommendations:", error);
793
- return ["Error generating recommendations"];
794
- }
795
- }
796
- }
797
-
798
- exports.SecurityPlugin = SecurityPlugin;
799
- //# sourceMappingURL=SecurityPlugin.js.map