@noony-serverless/core 0.1.0 → 0.1.5

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 (56) hide show
  1. package/build/middlewares/authenticationMiddleware.d.ts +379 -0
  2. package/build/middlewares/authenticationMiddleware.js +216 -0
  3. package/build/middlewares/bodyParserMiddleware.d.ts +99 -0
  4. package/build/middlewares/bodyParserMiddleware.js +99 -0
  5. package/build/middlewares/bodyValidationMiddleware.d.ts +68 -4
  6. package/build/middlewares/bodyValidationMiddleware.js +64 -0
  7. package/build/middlewares/dependencyInjectionMiddleware.d.ts +238 -0
  8. package/build/middlewares/dependencyInjectionMiddleware.js +238 -0
  9. package/build/middlewares/errorHandlerMiddleware.d.ts +94 -0
  10. package/build/middlewares/errorHandlerMiddleware.js +105 -0
  11. package/build/middlewares/guards/RouteGuards.d.ts +475 -0
  12. package/build/middlewares/guards/RouteGuards.js +604 -0
  13. package/build/middlewares/guards/cache/CacheAdapter.d.ts +473 -0
  14. package/build/middlewares/guards/cache/CacheAdapter.js +205 -0
  15. package/build/middlewares/guards/cache/ConservativeCacheInvalidation.d.ts +191 -0
  16. package/build/middlewares/guards/cache/ConservativeCacheInvalidation.js +510 -0
  17. package/build/middlewares/guards/cache/MemoryCacheAdapter.d.ts +228 -0
  18. package/build/middlewares/guards/cache/MemoryCacheAdapter.js +403 -0
  19. package/build/middlewares/guards/cache/NoopCacheAdapter.d.ts +95 -0
  20. package/build/middlewares/guards/cache/NoopCacheAdapter.js +131 -0
  21. package/build/middlewares/guards/config/GuardConfiguration.d.ts +612 -0
  22. package/build/middlewares/guards/config/GuardConfiguration.js +334 -0
  23. package/build/middlewares/guards/guards/FastAuthGuard.d.ts +201 -0
  24. package/build/middlewares/guards/guards/FastAuthGuard.js +460 -0
  25. package/build/middlewares/guards/guards/PermissionGuardFactory.d.ts +202 -0
  26. package/build/middlewares/guards/guards/PermissionGuardFactory.js +563 -0
  27. package/build/middlewares/guards/index.d.ts +67 -0
  28. package/build/middlewares/guards/index.js +192 -0
  29. package/build/middlewares/guards/registry/PermissionRegistry.d.ts +188 -0
  30. package/build/middlewares/guards/registry/PermissionRegistry.js +425 -0
  31. package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.d.ts +129 -0
  32. package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.js +451 -0
  33. package/build/middlewares/guards/resolvers/PermissionResolver.d.ts +155 -0
  34. package/build/middlewares/guards/resolvers/PermissionResolver.js +176 -0
  35. package/build/middlewares/guards/resolvers/PlainPermissionResolver.d.ts +101 -0
  36. package/build/middlewares/guards/resolvers/PlainPermissionResolver.js +248 -0
  37. package/build/middlewares/guards/resolvers/WildcardPermissionResolver.d.ts +146 -0
  38. package/build/middlewares/guards/resolvers/WildcardPermissionResolver.js +377 -0
  39. package/build/middlewares/guards/services/FastUserContextService.d.ts +216 -0
  40. package/build/middlewares/guards/services/FastUserContextService.js +435 -0
  41. package/build/middlewares/headerVariablesMiddleware.d.ts +118 -0
  42. package/build/middlewares/headerVariablesMiddleware.js +118 -0
  43. package/build/middlewares/httpAttributesMiddleware.d.ts +235 -0
  44. package/build/middlewares/httpAttributesMiddleware.js +235 -0
  45. package/build/middlewares/index.d.ts +1 -0
  46. package/build/middlewares/index.js +1 -0
  47. package/build/middlewares/queryParametersMiddleware.d.ts +105 -0
  48. package/build/middlewares/queryParametersMiddleware.js +105 -0
  49. package/build/middlewares/rateLimitingMiddleware.d.ts +109 -5
  50. package/build/middlewares/rateLimitingMiddleware.js +109 -5
  51. package/build/middlewares/responseWrapperMiddleware.d.ts +170 -1
  52. package/build/middlewares/responseWrapperMiddleware.js +170 -1
  53. package/build/middlewares/securityAuditMiddleware.js +5 -5
  54. package/build/middlewares/validationMiddleware.d.ts +145 -0
  55. package/build/middlewares/validationMiddleware.js +145 -0
  56. package/package.json +2 -2
@@ -0,0 +1,475 @@
1
+ /**
2
+ * Route Guards Facade
3
+ *
4
+ * Main entry point for the guard system providing a clean, NestJS-inspired API
5
+ * for protecting routes with authentication and authorization. This facade
6
+ * orchestrates all guard components to provide three distinct protection methods
7
+ * optimized for different use cases.
8
+ *
9
+ * Three Protection Methods:
10
+ * 1. `requirePermissions()` - Simple permission list checks (fastest)
11
+ * 2. `requireWildcardPermissions()` - Hierarchical wildcard patterns
12
+ * 3. `requireComplexPermissions()` - Boolean expression evaluation
13
+ *
14
+ * Key Features:
15
+ * - Automatic resolver selection for optimal performance
16
+ * - Intelligent caching strategies per protection method
17
+ * - Conservative security approach with automatic cache invalidation
18
+ * - Built-in authentication with cached user context loading
19
+ * - Comprehensive monitoring and audit trails
20
+ * - Framework-agnostic middleware integration
21
+ *
22
+ * @example
23
+ * Complete guard system setup:
24
+ * ```typescript
25
+ * import { RouteGuards, GuardSetup } from '@noony-serverless/core';
26
+ *
27
+ * // Define user permission source
28
+ * const userPermissionSource = {
29
+ * async getUserPermissions(userId: string): Promise<string[]> {
30
+ * const user = await getUserFromDatabase(userId);
31
+ * return user.permissions;
32
+ * }
33
+ * };
34
+ *
35
+ * // Define token validator
36
+ * const tokenValidator = {
37
+ * async validateToken(token: string) {
38
+ * try {
39
+ * const decoded = jwt.verify(token, process.env.JWT_SECRET);
40
+ * return { valid: true, decoded };
41
+ * } catch (error) {
42
+ * return { valid: false, error: error.message };
43
+ * }
44
+ * },
45
+ * extractUserId: (decoded: any) => decoded.sub,
46
+ * isTokenExpired: (decoded: any) => decoded.exp < Date.now() / 1000
47
+ * };
48
+ *
49
+ * // Configure guard system
50
+ * await RouteGuards.configure(
51
+ * GuardSetup.production(),
52
+ * userPermissionSource,
53
+ * tokenValidator,
54
+ * {
55
+ * tokenHeader: 'authorization',
56
+ * tokenPrefix: 'Bearer ',
57
+ * requireEmailVerification: true,
58
+ * allowInactiveUsers: false
59
+ * }
60
+ * );
61
+ * ```
62
+ *
63
+ * @example
64
+ * Simple permission checks (fastest - ~0.1ms cached):
65
+ * ```typescript
66
+ * import { Handler, RouteGuards } from '@noony-serverless/core';
67
+ *
68
+ * const userManagementHandler = new Handler()
69
+ * .use(RouteGuards.requirePermissions(['user:read', 'user:update']))
70
+ * .handle(async (context) => {
71
+ * // User has either 'user:read' OR 'user:update' permission
72
+ * const users = await getUsers();
73
+ * return { success: true, users };
74
+ * });
75
+ * ```
76
+ *
77
+ * @example
78
+ * Wildcard permission patterns (hierarchical - ~0.2ms cached):
79
+ * ```typescript
80
+ * const adminHandler = new Handler()
81
+ * .use(RouteGuards.requireWildcardPermissions(['admin.*', 'org.reports.*']))
82
+ * .handle(async (context) => {
83
+ * // User has any permission starting with 'admin.' OR 'org.reports.'
84
+ * const adminData = await getAdminDashboard();
85
+ * return { success: true, data: adminData };
86
+ * });
87
+ * ```
88
+ *
89
+ * @example
90
+ * Complex boolean expressions (~0.5ms cached):
91
+ * ```typescript
92
+ * const complexAccessHandler = new Handler()
93
+ * .use(RouteGuards.requireComplexPermissions({
94
+ * or: [
95
+ * { permission: 'admin.users' },
96
+ * { and: [
97
+ * { permission: 'moderator.content' },
98
+ * { permission: 'org.reports.view' }
99
+ * ]}
100
+ * ]
101
+ * }))
102
+ * .handle(async (context) => {
103
+ * // User has 'admin.users' OR ('moderator.content' AND 'org.reports.view')
104
+ * return { success: true, accessGranted: true };
105
+ * });
106
+ * ```
107
+ *
108
+ * @example
109
+ * Authentication-only (no permissions):
110
+ * ```typescript
111
+ * const profileHandler = new Handler()
112
+ * .use(RouteGuards.requireAuth())
113
+ * .handle(async (context) => {
114
+ * // Only checks if user is authenticated
115
+ * const profile = await getUserProfile(context.user.id);
116
+ * return { success: true, profile };
117
+ * });
118
+ * ```
119
+ *
120
+ * @example
121
+ * Cache invalidation for security:
122
+ * ```typescript
123
+ * // Invalidate specific user when permissions change
124
+ * await RouteGuards.invalidateUserPermissions('user-123', 'Permission update');
125
+ *
126
+ * // System-wide invalidation for major updates
127
+ * await RouteGuards.invalidateAllPermissions('System update deployed');
128
+ *
129
+ * // Emergency invalidation for security incidents
130
+ * await RouteGuards.emergencyInvalidation('Security breach detected');
131
+ * ```
132
+ *
133
+ * @example
134
+ * Monitoring and health checks:
135
+ * ```typescript
136
+ * // Get comprehensive system statistics
137
+ * const stats = RouteGuards.getSystemStats();
138
+ * console.log('Guard system performance:', stats.systemHealth);
139
+ *
140
+ * // Perform health check
141
+ * const health = await RouteGuards.healthCheck();
142
+ * console.log('System status:', health.status);
143
+ * console.log('Recommendations:', health.details.recommendations);
144
+ * ```
145
+ *
146
+ * @author Noony Framework Team
147
+ * @version 1.0.0
148
+ */
149
+ import { BaseMiddleware } from '../../core/handler';
150
+ import { GuardConfiguration, GuardEnvironmentProfile } from './config/GuardConfiguration';
151
+ import { CacheAdapter } from './cache/CacheAdapter';
152
+ import { FastUserContextService, UserPermissionSource } from './services/FastUserContextService';
153
+ import { ConservativeCacheInvalidation } from './cache/ConservativeCacheInvalidation';
154
+ import { FastAuthGuard, AuthGuardConfig, TokenValidator } from './guards/FastAuthGuard';
155
+ import { PermissionGuardFactory } from './guards/PermissionGuardFactory';
156
+ import { PermissionRegistry } from './registry/PermissionRegistry';
157
+ import { PermissionExpression } from './resolvers/PermissionResolver';
158
+ /**
159
+ * Route guard configuration for the facade.
160
+ * Provides fine-grained control over guard behavior for specific endpoints.
161
+ *
162
+ * @example
163
+ * Basic guard options:
164
+ * ```typescript
165
+ * const options: RouteGuardOptions = {
166
+ * requireAuth: true,
167
+ * cacheResults: true,
168
+ * auditTrail: false,
169
+ * errorMessage: 'Access denied to this resource'
170
+ * };
171
+ *
172
+ * const handler = new Handler()
173
+ * .use(RouteGuards.requirePermissions(['admin:read'], options))
174
+ * .handle(async (context) => {
175
+ * return { success: true, data: 'admin data' };
176
+ * });
177
+ * ```
178
+ *
179
+ * @example
180
+ * High-security endpoint with audit trail:
181
+ * ```typescript
182
+ * const secureOptions: RouteGuardOptions = {
183
+ * requireAuth: true,
184
+ * cacheResults: false, // Always check fresh permissions
185
+ * auditTrail: true, // Enable detailed logging
186
+ * errorMessage: 'Unauthorized access to sensitive data',
187
+ * cacheTtlMs: 30000 // Short cache TTL for security
188
+ * };
189
+ *
190
+ * const sensitiveHandler = new Handler()
191
+ * .use(RouteGuards.requirePermissions(['sensitive:access'], secureOptions))
192
+ * .handle(async (context) => {
193
+ * return { success: true, data: 'sensitive information' };
194
+ * });
195
+ * ```
196
+ *
197
+ * @example
198
+ * Public endpoint with authentication check only:
199
+ * ```typescript
200
+ * const publicOptions: RouteGuardOptions = {
201
+ * requireAuth: false, // Allow unauthenticated access
202
+ * cacheResults: true,
203
+ * auditTrail: false
204
+ * };
205
+ *
206
+ * const publicHandler = new Handler()
207
+ * .use(RouteGuards.requirePermissions(['public:read'], publicOptions))
208
+ * .handle(async (context) => {
209
+ * return { success: true, data: 'public data' };
210
+ * });
211
+ * ```
212
+ */
213
+ export interface RouteGuardOptions {
214
+ /** Enable authentication requirement (default: true) */
215
+ requireAuth?: boolean;
216
+ /** Enable permission result caching (default: true) */
217
+ cacheResults?: boolean;
218
+ /** Enable detailed audit logging (default: false) */
219
+ auditTrail?: boolean;
220
+ /** Custom error message for access denials */
221
+ errorMessage?: string;
222
+ /** Cache TTL in milliseconds (overrides global config) */
223
+ cacheTtlMs?: number;
224
+ }
225
+ /**
226
+ * Guard system statistics for monitoring and performance analysis.
227
+ * Provides comprehensive metrics about all guard system components.
228
+ *
229
+ * @example
230
+ * Monitoring guard system performance:
231
+ * ```typescript
232
+ * const stats = RouteGuards.getSystemStats();
233
+ *
234
+ * console.log('System Health:', {
235
+ * totalChecks: stats.systemHealth.totalGuardChecks,
236
+ * avgResponseTime: stats.systemHealth.averageResponseTime,
237
+ * errorRate: stats.systemHealth.errorRate,
238
+ * cacheEfficiency: stats.systemHealth.cacheEfficiency,
239
+ * uptime: Math.round(stats.systemHealth.uptime / 1000) + 's'
240
+ * });
241
+ *
242
+ * console.log('Cache Performance:', {
243
+ * adapter: stats.cacheAdapter.name,
244
+ * stats: stats.cacheAdapter.stats
245
+ * });
246
+ * ```
247
+ *
248
+ * @example
249
+ * Setting up monitoring alerts:
250
+ * ```typescript
251
+ * setInterval(async () => {
252
+ * const stats = RouteGuards.getSystemStats();
253
+ * const health = await RouteGuards.healthCheck();
254
+ *
255
+ * if (health.status === 'unhealthy') {
256
+ * await sendAlert('Guard system unhealthy', {
257
+ * status: health.status,
258
+ * errorRate: stats.systemHealth.errorRate,
259
+ * avgResponseTime: stats.systemHealth.averageResponseTime,
260
+ * recommendations: health.details.recommendations
261
+ * });
262
+ * }
263
+ *
264
+ * if (stats.systemHealth.cacheEfficiency < 50) {
265
+ * await sendAlert('Low cache efficiency detected', {
266
+ * efficiency: stats.systemHealth.cacheEfficiency,
267
+ * totalChecks: stats.systemHealth.totalGuardChecks
268
+ * });
269
+ * }
270
+ * }, 60000); // Check every minute
271
+ * ```
272
+ *
273
+ * @example
274
+ * Performance optimization based on stats:
275
+ * ```typescript
276
+ * const stats = RouteGuards.getSystemStats();
277
+ *
278
+ * if (stats.systemHealth.averageResponseTime > 10) {
279
+ * console.warn('Slow guard performance detected');
280
+ * console.log('Consider:');
281
+ * console.log('- Increasing cache TTL values');
282
+ * console.log('- Optimizing permission source queries');
283
+ * console.log('- Using simpler permission patterns');
284
+ * }
285
+ *
286
+ * if (stats.systemHealth.errorRate > 2) {
287
+ * console.error('High error rate in guard system');
288
+ * console.log('Check authentication service health');
289
+ * }
290
+ * ```
291
+ */
292
+ export interface GuardSystemStats {
293
+ authentication: Record<string, unknown>;
294
+ userContextService: Record<string, unknown>;
295
+ permissionGuardFactory: Record<string, unknown>;
296
+ cacheInvalidation: Record<string, unknown>;
297
+ cacheAdapter: Record<string, unknown>;
298
+ systemHealth: {
299
+ totalGuardChecks: number;
300
+ averageResponseTime: number;
301
+ errorRate: number;
302
+ cacheEfficiency: number;
303
+ uptime: number;
304
+ };
305
+ }
306
+ /**
307
+ * Route Guards Facade Implementation
308
+ *
309
+ * This class provides the main API for the guard system and handles
310
+ * the orchestration of all guard components. It follows the facade pattern
311
+ * to simplify the complex underlying guard architecture.
312
+ */
313
+ export declare class RouteGuards {
314
+ private static instance;
315
+ private static isConfigured;
316
+ private readonly _config;
317
+ private readonly cache;
318
+ private readonly userContextService;
319
+ private readonly cacheInvalidation;
320
+ private readonly authGuard;
321
+ private readonly guardFactory;
322
+ private readonly _permissionRegistry;
323
+ private systemStartTime;
324
+ private totalGuardChecks;
325
+ private totalErrors;
326
+ private totalResponseTime;
327
+ constructor(config: GuardConfiguration, cache: CacheAdapter, userContextService: FastUserContextService, cacheInvalidation: ConservativeCacheInvalidation, authGuard: FastAuthGuard, guardFactory: PermissionGuardFactory, permissionRegistry: PermissionRegistry);
328
+ /**
329
+ * Configure the guard system with environment-specific settings
330
+ *
331
+ * This method must be called once before using any guard methods.
332
+ * It sets up all guard components with optimal configurations for
333
+ * the target environment (development, production, serverless).
334
+ *
335
+ * @param profile - Environment profile with guard configurations
336
+ * @param permissionSource - User permission data source
337
+ * @param tokenValidator - JWT token validation service
338
+ * @param authConfig - Authentication guard configuration
339
+ * @returns Promise resolving when configuration is complete
340
+ */
341
+ static configure(profile: GuardEnvironmentProfile, permissionSource: UserPermissionSource, tokenValidator: TokenValidator, authConfig: AuthGuardConfig): Promise<void>;
342
+ /**
343
+ * Get the configured RouteGuards instance
344
+ *
345
+ * @returns Configured RouteGuards instance
346
+ * @throws Error if not configured
347
+ */
348
+ static getInstance(): RouteGuards;
349
+ /**
350
+ * Create middleware for simple permission list checks
351
+ *
352
+ * This is the fastest protection method using direct O(1) set membership
353
+ * checks. Ideal for high-traffic endpoints with straightforward permission
354
+ * requirements.
355
+ *
356
+ * Performance: ~0.1ms cached, ~1-2ms uncached
357
+ *
358
+ * @param permissions - Array of required permissions (OR logic)
359
+ * @param options - Optional guard configuration
360
+ * @returns Middleware instance for permission checking
361
+ */
362
+ static requirePermissions(permissions: string[], options?: RouteGuardOptions): BaseMiddleware;
363
+ /**
364
+ * Create middleware for wildcard permission pattern checks
365
+ *
366
+ * Supports hierarchical permission patterns with wildcards for flexible
367
+ * permission management. Uses configurable pre-expansion or on-demand
368
+ * matching strategies.
369
+ *
370
+ * Performance: ~0.2ms cached (pre-expansion), ~2-5ms cached (on-demand)
371
+ *
372
+ * @param wildcardPatterns - Array of wildcard patterns
373
+ * @param options - Optional guard configuration
374
+ * @returns Middleware instance for wildcard permission checking
375
+ */
376
+ static requireWildcardPermissions(wildcardPatterns: string[], options?: RouteGuardOptions): BaseMiddleware;
377
+ /**
378
+ * Create middleware for complex boolean expression checks
379
+ *
380
+ * Supports advanced permission logic with AND, OR, and NOT operations.
381
+ * Includes expression caching and complexity tracking for performance
382
+ * optimization.
383
+ *
384
+ * Performance: ~0.5ms cached, ~5-15ms uncached (depends on complexity)
385
+ *
386
+ * @param expression - Permission expression with boolean logic
387
+ * @param options - Optional guard configuration
388
+ * @returns Middleware instance for expression permission checking
389
+ */
390
+ static requireComplexPermissions(expression: PermissionExpression, options?: RouteGuardOptions): BaseMiddleware;
391
+ /**
392
+ * Create middleware with automatic resolver selection
393
+ *
394
+ * Analyzes permission requirements and automatically selects the optimal
395
+ * resolution strategy for best performance. Useful when you want the
396
+ * system to choose the best approach.
397
+ *
398
+ * @param permissions - Any type of permission requirement
399
+ * @param options - Optional guard configuration
400
+ * @returns Optimally configured middleware instance
401
+ */
402
+ static requireAny(permissions: string[] | PermissionExpression, options?: RouteGuardOptions): BaseMiddleware;
403
+ /**
404
+ * Get authentication-only middleware
405
+ *
406
+ * Provides user authentication without permission checking.
407
+ * Useful for endpoints that only need to verify user identity.
408
+ *
409
+ * @param options - Optional guard configuration
410
+ * @returns Authentication-only middleware
411
+ */
412
+ static requireAuth(_options?: RouteGuardOptions): BaseMiddleware;
413
+ /**
414
+ * Invalidate user permissions cache
415
+ *
416
+ * Use when user permissions change to ensure fresh permission checks.
417
+ * Implements conservative invalidation strategy for security.
418
+ *
419
+ * @param userId - User ID to invalidate
420
+ * @param reason - Reason for invalidation (for audit)
421
+ * @returns Promise resolving when invalidation is complete
422
+ */
423
+ static invalidateUserPermissions(userId: string, reason: string): Promise<void>;
424
+ /**
425
+ * System-wide cache invalidation
426
+ *
427
+ * Nuclear option for clearing all permission-related caches.
428
+ * Use for major system updates or security incidents.
429
+ *
430
+ * @param reason - Reason for system-wide invalidation
431
+ * @returns Promise resolving when invalidation is complete
432
+ */
433
+ static invalidateAllPermissions(reason: string): Promise<void>;
434
+ /**
435
+ * Emergency security invalidation
436
+ *
437
+ * Immediate cache clearing for security incidents.
438
+ * Bypasses backup creation for maximum speed.
439
+ *
440
+ * @param reason - Security incident description
441
+ * @returns Promise resolving when emergency invalidation is complete
442
+ */
443
+ static emergencyInvalidation(reason: string): Promise<void>;
444
+ /**
445
+ * Get comprehensive system statistics
446
+ *
447
+ * @returns Complete guard system performance and health metrics
448
+ */
449
+ static getSystemStats(): GuardSystemStats;
450
+ /**
451
+ * Reset all system statistics
452
+ */
453
+ static resetSystemStats(): void;
454
+ /**
455
+ * Health check for the guard system
456
+ *
457
+ * @returns Health status with key metrics
458
+ */
459
+ static healthCheck(): Promise<{
460
+ status: 'healthy' | 'degraded' | 'unhealthy';
461
+ details: Record<string, unknown>;
462
+ timestamp: string;
463
+ }>;
464
+ private createPlainPermissionGuard;
465
+ private createWildcardPermissionGuard;
466
+ private createExpressionPermissionGuard;
467
+ private createAutoPermissionGuard;
468
+ private wrapGuardWithStats;
469
+ private trackGuardCreation;
470
+ private getSystemStats;
471
+ private resetSystemStats;
472
+ private performHealthCheck;
473
+ private getHealthRecommendations;
474
+ }
475
+ //# sourceMappingURL=RouteGuards.d.ts.map