@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.
- package/build/middlewares/authenticationMiddleware.d.ts +379 -0
- package/build/middlewares/authenticationMiddleware.js +216 -0
- package/build/middlewares/bodyParserMiddleware.d.ts +99 -0
- package/build/middlewares/bodyParserMiddleware.js +99 -0
- package/build/middlewares/bodyValidationMiddleware.d.ts +68 -4
- package/build/middlewares/bodyValidationMiddleware.js +64 -0
- package/build/middlewares/dependencyInjectionMiddleware.d.ts +238 -0
- package/build/middlewares/dependencyInjectionMiddleware.js +238 -0
- package/build/middlewares/errorHandlerMiddleware.d.ts +94 -0
- package/build/middlewares/errorHandlerMiddleware.js +105 -0
- package/build/middlewares/guards/RouteGuards.d.ts +475 -0
- package/build/middlewares/guards/RouteGuards.js +604 -0
- package/build/middlewares/guards/cache/CacheAdapter.d.ts +473 -0
- package/build/middlewares/guards/cache/CacheAdapter.js +205 -0
- package/build/middlewares/guards/cache/ConservativeCacheInvalidation.d.ts +191 -0
- package/build/middlewares/guards/cache/ConservativeCacheInvalidation.js +510 -0
- package/build/middlewares/guards/cache/MemoryCacheAdapter.d.ts +228 -0
- package/build/middlewares/guards/cache/MemoryCacheAdapter.js +403 -0
- package/build/middlewares/guards/cache/NoopCacheAdapter.d.ts +95 -0
- package/build/middlewares/guards/cache/NoopCacheAdapter.js +131 -0
- package/build/middlewares/guards/config/GuardConfiguration.d.ts +612 -0
- package/build/middlewares/guards/config/GuardConfiguration.js +334 -0
- package/build/middlewares/guards/guards/FastAuthGuard.d.ts +201 -0
- package/build/middlewares/guards/guards/FastAuthGuard.js +460 -0
- package/build/middlewares/guards/guards/PermissionGuardFactory.d.ts +202 -0
- package/build/middlewares/guards/guards/PermissionGuardFactory.js +563 -0
- package/build/middlewares/guards/index.d.ts +67 -0
- package/build/middlewares/guards/index.js +192 -0
- package/build/middlewares/guards/registry/PermissionRegistry.d.ts +188 -0
- package/build/middlewares/guards/registry/PermissionRegistry.js +425 -0
- package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.d.ts +129 -0
- package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.js +451 -0
- package/build/middlewares/guards/resolvers/PermissionResolver.d.ts +155 -0
- package/build/middlewares/guards/resolvers/PermissionResolver.js +176 -0
- package/build/middlewares/guards/resolvers/PlainPermissionResolver.d.ts +101 -0
- package/build/middlewares/guards/resolvers/PlainPermissionResolver.js +248 -0
- package/build/middlewares/guards/resolvers/WildcardPermissionResolver.d.ts +146 -0
- package/build/middlewares/guards/resolvers/WildcardPermissionResolver.js +377 -0
- package/build/middlewares/guards/services/FastUserContextService.d.ts +216 -0
- package/build/middlewares/guards/services/FastUserContextService.js +435 -0
- package/build/middlewares/headerVariablesMiddleware.d.ts +118 -0
- package/build/middlewares/headerVariablesMiddleware.js +118 -0
- package/build/middlewares/httpAttributesMiddleware.d.ts +235 -0
- package/build/middlewares/httpAttributesMiddleware.js +235 -0
- package/build/middlewares/index.d.ts +1 -0
- package/build/middlewares/index.js +1 -0
- package/build/middlewares/queryParametersMiddleware.d.ts +105 -0
- package/build/middlewares/queryParametersMiddleware.js +105 -0
- package/build/middlewares/rateLimitingMiddleware.d.ts +109 -5
- package/build/middlewares/rateLimitingMiddleware.js +109 -5
- package/build/middlewares/responseWrapperMiddleware.d.ts +170 -1
- package/build/middlewares/responseWrapperMiddleware.js +170 -1
- package/build/middlewares/securityAuditMiddleware.js +5 -5
- package/build/middlewares/validationMiddleware.d.ts +145 -0
- package/build/middlewares/validationMiddleware.js +145 -0
- package/package.json +2 -2
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Guard System Configuration
|
|
4
|
+
*
|
|
5
|
+
* Comprehensive configuration system for the high-performance guard system.
|
|
6
|
+
* Provides type-safe configuration for different deployment environments with
|
|
7
|
+
* configurable performance strategies and security policies.
|
|
8
|
+
*
|
|
9
|
+
* Key Features:
|
|
10
|
+
* - Permission resolution strategy configuration (pre-expansion vs on-demand)
|
|
11
|
+
* - Cache adapter injection for different environments
|
|
12
|
+
* - Performance profiles for development, staging, and production
|
|
13
|
+
* - Security policies with conservative cache invalidation
|
|
14
|
+
* - Bounded complexity limits for patterns and expressions
|
|
15
|
+
*
|
|
16
|
+
* @author Noony Framework Team
|
|
17
|
+
* @version 1.0.0
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.GuardConfiguration = exports.MonitoringLevel = exports.CacheInvalidationStrategy = exports.PermissionResolutionStrategy = void 0;
|
|
21
|
+
/**
|
|
22
|
+
* Permission resolution strategies for wildcard permissions.
|
|
23
|
+
* Determines how wildcard patterns are processed for optimal performance.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* Pre-expansion strategy (production recommended):
|
|
27
|
+
* ```typescript
|
|
28
|
+
* const productionConfig = {
|
|
29
|
+
* permissionResolutionStrategy: PermissionResolutionStrategy.PRE_EXPANSION,
|
|
30
|
+
* // Expands "admin.*" to ["admin.users", "admin.reports", "admin.settings"]
|
|
31
|
+
* // at user context load time for O(1) runtime checks
|
|
32
|
+
* };
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* On-demand strategy (memory efficient):
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const memoryEfficientConfig = {
|
|
39
|
+
* permissionResolutionStrategy: PermissionResolutionStrategy.ON_DEMAND,
|
|
40
|
+
* // Matches "admin.*" pattern against user permissions at runtime
|
|
41
|
+
* // Lower memory usage but requires pattern matching overhead
|
|
42
|
+
* };
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* PRE_EXPANSION: Expand wildcards at user context load time
|
|
46
|
+
* - Pros: Faster runtime permission checks (O(1) set lookups)
|
|
47
|
+
* - Cons: Higher memory usage, requires permission registry
|
|
48
|
+
*
|
|
49
|
+
* ON_DEMAND: Match wildcards at permission check time
|
|
50
|
+
* - Pros: Lower memory usage, supports dynamic permissions
|
|
51
|
+
* - Cons: Pattern matching overhead per request
|
|
52
|
+
*/
|
|
53
|
+
var PermissionResolutionStrategy;
|
|
54
|
+
(function (PermissionResolutionStrategy) {
|
|
55
|
+
PermissionResolutionStrategy["PRE_EXPANSION"] = "pre-expansion";
|
|
56
|
+
PermissionResolutionStrategy["ON_DEMAND"] = "on-demand";
|
|
57
|
+
})(PermissionResolutionStrategy || (exports.PermissionResolutionStrategy = PermissionResolutionStrategy = {}));
|
|
58
|
+
/**
|
|
59
|
+
* Cache invalidation strategies for security
|
|
60
|
+
*/
|
|
61
|
+
var CacheInvalidationStrategy;
|
|
62
|
+
(function (CacheInvalidationStrategy) {
|
|
63
|
+
CacheInvalidationStrategy["FLUSH_ALL"] = "flush-all";
|
|
64
|
+
CacheInvalidationStrategy["USER_SPECIFIC"] = "user-specific";
|
|
65
|
+
})(CacheInvalidationStrategy || (exports.CacheInvalidationStrategy = CacheInvalidationStrategy = {}));
|
|
66
|
+
/**
|
|
67
|
+
* Performance monitoring levels
|
|
68
|
+
*/
|
|
69
|
+
var MonitoringLevel;
|
|
70
|
+
(function (MonitoringLevel) {
|
|
71
|
+
MonitoringLevel["NONE"] = "none";
|
|
72
|
+
MonitoringLevel["BASIC"] = "basic";
|
|
73
|
+
MonitoringLevel["DETAILED"] = "detailed";
|
|
74
|
+
MonitoringLevel["VERBOSE"] = "verbose";
|
|
75
|
+
})(MonitoringLevel || (exports.MonitoringLevel = MonitoringLevel = {}));
|
|
76
|
+
/**
|
|
77
|
+
* GuardConfiguration class implementation.
|
|
78
|
+
* Immutable configuration object for the Noony guard system with factory methods
|
|
79
|
+
* for creating configurations from environment profiles or predefined templates.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* Create from environment profile:
|
|
83
|
+
* ```typescript
|
|
84
|
+
* import { GuardConfiguration } from '@noony/core';
|
|
85
|
+
*
|
|
86
|
+
* const config = GuardConfiguration.fromEnvironmentProfile({
|
|
87
|
+
* environment: 'production',
|
|
88
|
+
* cacheType: 'redis',
|
|
89
|
+
* security: { ... },
|
|
90
|
+
* cache: { ... },
|
|
91
|
+
* monitoring: { ... }
|
|
92
|
+
* });
|
|
93
|
+
* ```
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* Use predefined configurations:
|
|
97
|
+
* ```typescript
|
|
98
|
+
* // Development configuration
|
|
99
|
+
* const devConfig = GuardConfiguration.development();
|
|
100
|
+
*
|
|
101
|
+
* // Production configuration
|
|
102
|
+
* const prodConfig = GuardConfiguration.production();
|
|
103
|
+
*
|
|
104
|
+
* // Testing configuration
|
|
105
|
+
* const testConfig = GuardConfiguration.testing();
|
|
106
|
+
* ```
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* Manual configuration:
|
|
110
|
+
* ```typescript
|
|
111
|
+
* const customConfig = new GuardConfiguration(
|
|
112
|
+
* { permissionResolutionStrategy: PermissionResolutionStrategy.PRE_EXPANSION },
|
|
113
|
+
* { maxEntries: 10000, defaultTtlMs: 300000 },
|
|
114
|
+
* { enablePerformanceTracking: true, logLevel: 'info' }
|
|
115
|
+
* );
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
class GuardConfiguration {
|
|
119
|
+
/**
|
|
120
|
+
* Security configuration settings.
|
|
121
|
+
* Contains permission resolution strategies and security limits.
|
|
122
|
+
*/
|
|
123
|
+
security;
|
|
124
|
+
/**
|
|
125
|
+
* Cache configuration settings.
|
|
126
|
+
* Contains cache size limits and TTL values.
|
|
127
|
+
*/
|
|
128
|
+
cache;
|
|
129
|
+
/**
|
|
130
|
+
* Monitoring configuration settings.
|
|
131
|
+
* Contains logging and metrics collection settings.
|
|
132
|
+
*/
|
|
133
|
+
monitoring;
|
|
134
|
+
/**
|
|
135
|
+
* Creates a new GuardConfiguration instance.
|
|
136
|
+
*
|
|
137
|
+
* @param security - Security configuration settings
|
|
138
|
+
* @param cache - Cache configuration settings
|
|
139
|
+
* @param monitoring - Monitoring configuration settings
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```typescript
|
|
143
|
+
* const config = new GuardConfiguration(
|
|
144
|
+
* {
|
|
145
|
+
* permissionResolutionStrategy: PermissionResolutionStrategy.PRE_EXPANSION,
|
|
146
|
+
* conservativeCacheInvalidation: true,
|
|
147
|
+
* maxExpressionComplexity: 100
|
|
148
|
+
* },
|
|
149
|
+
* {
|
|
150
|
+
* maxEntries: 10000,
|
|
151
|
+
* defaultTtlMs: 300000,
|
|
152
|
+
* userContextTtlMs: 600000,
|
|
153
|
+
* authTokenTtlMs: 900000
|
|
154
|
+
* },
|
|
155
|
+
* {
|
|
156
|
+
* enablePerformanceTracking: true,
|
|
157
|
+
* enableDetailedLogging: false,
|
|
158
|
+
* logLevel: 'info',
|
|
159
|
+
* metricsCollectionInterval: 60000
|
|
160
|
+
* }
|
|
161
|
+
* );
|
|
162
|
+
* ```
|
|
163
|
+
*/
|
|
164
|
+
constructor(security, cache, monitoring) {
|
|
165
|
+
this.security = security;
|
|
166
|
+
this.cache = cache;
|
|
167
|
+
this.monitoring = monitoring;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Create GuardConfiguration from environment profile.
|
|
171
|
+
* Factory method that constructs a configuration from a complete environment profile.
|
|
172
|
+
*
|
|
173
|
+
* @param profile - Complete environment profile with all configuration sections
|
|
174
|
+
* @returns New GuardConfiguration instance
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* Create from production profile:
|
|
178
|
+
* ```typescript
|
|
179
|
+
* const productionProfile: GuardEnvironmentProfile = {
|
|
180
|
+
* environment: 'production',
|
|
181
|
+
* cacheType: 'redis',
|
|
182
|
+
* security: {
|
|
183
|
+
* permissionResolutionStrategy: PermissionResolutionStrategy.PRE_EXPANSION,
|
|
184
|
+
* conservativeCacheInvalidation: true,
|
|
185
|
+
* maxExpressionComplexity: 100
|
|
186
|
+
* },
|
|
187
|
+
* cache: {
|
|
188
|
+
* maxEntries: 50000,
|
|
189
|
+
* defaultTtlMs: 600000,
|
|
190
|
+
* userContextTtlMs: 1800000,
|
|
191
|
+
* authTokenTtlMs: 3600000
|
|
192
|
+
* },
|
|
193
|
+
* monitoring: {
|
|
194
|
+
* enablePerformanceTracking: true,
|
|
195
|
+
* enableDetailedLogging: false,
|
|
196
|
+
* logLevel: 'error',
|
|
197
|
+
* metricsCollectionInterval: 60000
|
|
198
|
+
* }
|
|
199
|
+
* };
|
|
200
|
+
*
|
|
201
|
+
* const config = GuardConfiguration.fromEnvironmentProfile(productionProfile);
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
static fromEnvironmentProfile(profile) {
|
|
205
|
+
return new GuardConfiguration(profile.security, profile.cache, profile.monitoring);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Create default development configuration.
|
|
209
|
+
* Pre-configured settings optimized for development environments with fast refresh
|
|
210
|
+
* and detailed logging for debugging.
|
|
211
|
+
*
|
|
212
|
+
* @returns GuardConfiguration optimized for development
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```typescript
|
|
216
|
+
* const devConfig = GuardConfiguration.development();
|
|
217
|
+
*
|
|
218
|
+
* // Configuration includes:
|
|
219
|
+
* // - On-demand permission resolution (lower memory, dynamic)
|
|
220
|
+
* // - Conservative cache invalidation disabled (faster refresh)
|
|
221
|
+
* // - Lower complexity limits for faster feedback
|
|
222
|
+
* // - Shorter TTL values for rapid development cycles
|
|
223
|
+
* // - Detailed logging and debug level
|
|
224
|
+
* // - Frequent metrics collection (30 seconds)
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
227
|
+
static development() {
|
|
228
|
+
return new GuardConfiguration({
|
|
229
|
+
permissionResolutionStrategy: PermissionResolutionStrategy.ON_DEMAND,
|
|
230
|
+
conservativeCacheInvalidation: false,
|
|
231
|
+
maxExpressionComplexity: 50,
|
|
232
|
+
maxPatternDepth: 3,
|
|
233
|
+
maxNestingDepth: 2,
|
|
234
|
+
}, {
|
|
235
|
+
maxEntries: 500,
|
|
236
|
+
defaultTtlMs: 5 * 60 * 1000, // 5 minutes
|
|
237
|
+
userContextTtlMs: 2 * 60 * 1000, // 2 minutes
|
|
238
|
+
authTokenTtlMs: 2 * 60 * 1000, // 2 minutes
|
|
239
|
+
}, {
|
|
240
|
+
enablePerformanceTracking: true,
|
|
241
|
+
enableDetailedLogging: true,
|
|
242
|
+
logLevel: 'debug',
|
|
243
|
+
metricsCollectionInterval: 30000, // 30 seconds
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Create default production configuration.
|
|
248
|
+
* Pre-configured settings optimized for production environments with high performance,
|
|
249
|
+
* security, and stability.
|
|
250
|
+
*
|
|
251
|
+
* @returns GuardConfiguration optimized for production
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* ```typescript
|
|
255
|
+
* const prodConfig = GuardConfiguration.production();
|
|
256
|
+
*
|
|
257
|
+
* // Configuration includes:
|
|
258
|
+
* // - Pre-expansion permission resolution (high performance)
|
|
259
|
+
* // - Conservative cache invalidation enabled (high security)
|
|
260
|
+
* // - Higher complexity limits for production workloads
|
|
261
|
+
* // - Longer TTL values for better performance
|
|
262
|
+
* // - Performance tracking enabled, detailed logging disabled
|
|
263
|
+
* // - Standard metrics collection (1 minute intervals)
|
|
264
|
+
* ```
|
|
265
|
+
*/
|
|
266
|
+
static production() {
|
|
267
|
+
return new GuardConfiguration({
|
|
268
|
+
permissionResolutionStrategy: PermissionResolutionStrategy.PRE_EXPANSION,
|
|
269
|
+
conservativeCacheInvalidation: true,
|
|
270
|
+
maxExpressionComplexity: 100,
|
|
271
|
+
maxPatternDepth: 3,
|
|
272
|
+
maxNestingDepth: 2,
|
|
273
|
+
}, {
|
|
274
|
+
maxEntries: 2000,
|
|
275
|
+
defaultTtlMs: 15 * 60 * 1000, // 15 minutes
|
|
276
|
+
userContextTtlMs: 10 * 60 * 1000, // 10 minutes
|
|
277
|
+
authTokenTtlMs: 5 * 60 * 1000, // 5 minutes
|
|
278
|
+
}, {
|
|
279
|
+
enablePerformanceTracking: true,
|
|
280
|
+
enableDetailedLogging: false,
|
|
281
|
+
logLevel: 'info',
|
|
282
|
+
metricsCollectionInterval: 60000, // 1 minute
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Validate configuration settings.
|
|
287
|
+
* Ensures all configuration values are within acceptable bounds and constraints
|
|
288
|
+
* to prevent security vulnerabilities and performance issues.
|
|
289
|
+
*
|
|
290
|
+
* @throws Error if any configuration value is invalid
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* ```typescript
|
|
294
|
+
* const config = new GuardConfiguration(securityConfig, cacheConfig, monitoringConfig);
|
|
295
|
+
*
|
|
296
|
+
* try {
|
|
297
|
+
* config.validate();
|
|
298
|
+
* console.log('Configuration is valid');
|
|
299
|
+
* } catch (error) {
|
|
300
|
+
* console.error('Invalid configuration:', error.message);
|
|
301
|
+
* // Handle configuration error
|
|
302
|
+
* }
|
|
303
|
+
* ```
|
|
304
|
+
*
|
|
305
|
+
* @example
|
|
306
|
+
* Validation constraints:
|
|
307
|
+
* ```typescript
|
|
308
|
+
* // These will throw validation errors:
|
|
309
|
+
* // maxPatternDepth must be 2 or 3 (prevents deep recursion)
|
|
310
|
+
* // maxNestingDepth must be 2 (prevents complex expressions)
|
|
311
|
+
* // maxExpressionComplexity must be positive
|
|
312
|
+
* // defaultTtlMs must be at least 1000ms (1 second)
|
|
313
|
+
* ```
|
|
314
|
+
*/
|
|
315
|
+
validate() {
|
|
316
|
+
if (this.security.maxPatternDepth !== undefined &&
|
|
317
|
+
(this.security.maxPatternDepth < 2 || this.security.maxPatternDepth > 3)) {
|
|
318
|
+
throw new Error('maxPatternDepth must be 2 or 3');
|
|
319
|
+
}
|
|
320
|
+
if (this.security.maxNestingDepth !== undefined &&
|
|
321
|
+
this.security.maxNestingDepth !== 2) {
|
|
322
|
+
throw new Error('maxNestingDepth must be 2');
|
|
323
|
+
}
|
|
324
|
+
if (this.security.maxExpressionComplexity !== undefined &&
|
|
325
|
+
this.security.maxExpressionComplexity < 1) {
|
|
326
|
+
throw new Error('maxExpressionComplexity must be positive');
|
|
327
|
+
}
|
|
328
|
+
if (this.cache.defaultTtlMs < 1000) {
|
|
329
|
+
throw new Error('defaultTtlMs must be at least 1 second');
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
exports.GuardConfiguration = GuardConfiguration;
|
|
334
|
+
//# sourceMappingURL=GuardConfiguration.js.map
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fast Authentication Guard
|
|
3
|
+
*
|
|
4
|
+
* High-performance authentication guard with multi-layer caching for serverless
|
|
5
|
+
* environments. Provides sub-millisecond cached authentication checks while
|
|
6
|
+
* maintaining security through conservative cache invalidation strategies.
|
|
7
|
+
*
|
|
8
|
+
* Key Features:
|
|
9
|
+
* - Multi-layer caching (L1 memory + L2 distributed)
|
|
10
|
+
* - JWT token validation with caching
|
|
11
|
+
* - User context loading and caching
|
|
12
|
+
* - Permission pre-loading for faster authorization
|
|
13
|
+
* - Security-first approach with automatic cache invalidation
|
|
14
|
+
* - Comprehensive audit logging and metrics
|
|
15
|
+
*
|
|
16
|
+
* Performance Characteristics:
|
|
17
|
+
* - Cached authentication: ~0.1ms (sub-millisecond)
|
|
18
|
+
* - Cold authentication: ~2-5ms (including token validation)
|
|
19
|
+
* - Memory usage: Low (LRU cache with configurable limits)
|
|
20
|
+
* - Network usage: Minimal (cached responses)
|
|
21
|
+
*
|
|
22
|
+
* Security Features:
|
|
23
|
+
* - Token signature validation
|
|
24
|
+
* - Token expiration checks
|
|
25
|
+
* - User status validation (active/suspended/deleted)
|
|
26
|
+
* - Automatic cache invalidation on security events
|
|
27
|
+
* - Rate limiting integration
|
|
28
|
+
* - Audit trail for all authentication events
|
|
29
|
+
*
|
|
30
|
+
* @author Noony Framework Team
|
|
31
|
+
* @version 1.0.0
|
|
32
|
+
*/
|
|
33
|
+
import { Context } from '../../../core/core';
|
|
34
|
+
import { BaseMiddleware } from '../../../core/handler';
|
|
35
|
+
import { CacheAdapter } from '../cache/CacheAdapter';
|
|
36
|
+
import { GuardConfiguration } from '../config/GuardConfiguration';
|
|
37
|
+
import { FastUserContextService, UserContext } from '../services/FastUserContextService';
|
|
38
|
+
import { ConservativeCacheInvalidation } from '../cache/ConservativeCacheInvalidation';
|
|
39
|
+
/**
|
|
40
|
+
* Authentication result with user context
|
|
41
|
+
*/
|
|
42
|
+
export interface AuthenticationResult {
|
|
43
|
+
success: boolean;
|
|
44
|
+
user?: UserContext;
|
|
45
|
+
token?: {
|
|
46
|
+
decoded: any;
|
|
47
|
+
raw: string;
|
|
48
|
+
expiresAt: string;
|
|
49
|
+
issuer?: string;
|
|
50
|
+
};
|
|
51
|
+
cached: boolean;
|
|
52
|
+
resolutionTimeUs: number;
|
|
53
|
+
reason?: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Authentication configuration
|
|
57
|
+
*/
|
|
58
|
+
export interface AuthGuardConfig {
|
|
59
|
+
jwtSecret?: string;
|
|
60
|
+
jwtPublicKey?: string;
|
|
61
|
+
tokenHeader: string;
|
|
62
|
+
tokenPrefix: string;
|
|
63
|
+
allowedIssuers?: string[];
|
|
64
|
+
requireEmailVerification: boolean;
|
|
65
|
+
allowInactiveUsers: boolean;
|
|
66
|
+
customValidation?: (token: any, user: UserContext) => Promise<boolean>;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Token validation service interface
|
|
70
|
+
*/
|
|
71
|
+
export interface TokenValidator {
|
|
72
|
+
/**
|
|
73
|
+
* Validate and decode JWT token
|
|
74
|
+
*/
|
|
75
|
+
validateToken(token: string): Promise<{
|
|
76
|
+
valid: boolean;
|
|
77
|
+
decoded?: any;
|
|
78
|
+
error?: string;
|
|
79
|
+
}>;
|
|
80
|
+
/**
|
|
81
|
+
* Extract user ID from decoded token
|
|
82
|
+
*/
|
|
83
|
+
extractUserId(decoded: any): string;
|
|
84
|
+
/**
|
|
85
|
+
* Check if token is expired
|
|
86
|
+
*/
|
|
87
|
+
isTokenExpired(decoded: any): boolean;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Fast Authentication Guard Implementation
|
|
91
|
+
*/
|
|
92
|
+
export declare class FastAuthGuard implements BaseMiddleware {
|
|
93
|
+
private readonly cache;
|
|
94
|
+
private readonly config;
|
|
95
|
+
private readonly authConfig;
|
|
96
|
+
private readonly userContextService;
|
|
97
|
+
private readonly cacheInvalidation;
|
|
98
|
+
private readonly tokenValidator;
|
|
99
|
+
private authAttempts;
|
|
100
|
+
private cacheHits;
|
|
101
|
+
private cacheMisses;
|
|
102
|
+
private authFailures;
|
|
103
|
+
private totalResolutionTimeUs;
|
|
104
|
+
private suspiciousAttempts;
|
|
105
|
+
private blockedTokens;
|
|
106
|
+
private lastSecurityEvent;
|
|
107
|
+
constructor(cache: CacheAdapter, config: GuardConfiguration, authConfig: AuthGuardConfig, userContextService: FastUserContextService, cacheInvalidation: ConservativeCacheInvalidation, tokenValidator: TokenValidator);
|
|
108
|
+
/**
|
|
109
|
+
* Execute authentication check
|
|
110
|
+
*
|
|
111
|
+
* This is the main middleware execution method that handles the complete
|
|
112
|
+
* authentication flow with caching and security validations.
|
|
113
|
+
*/
|
|
114
|
+
before(context: Context): Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* Authenticate user with multi-layer caching
|
|
117
|
+
*
|
|
118
|
+
* Implements the core authentication logic with intelligent caching
|
|
119
|
+
* to minimize database calls and token validation overhead.
|
|
120
|
+
*
|
|
121
|
+
* @param token - JWT token string
|
|
122
|
+
* @returns Authentication result with user context
|
|
123
|
+
*/
|
|
124
|
+
authenticateUser(token: string): Promise<AuthenticationResult>;
|
|
125
|
+
/**
|
|
126
|
+
* Invalidate authentication cache for user
|
|
127
|
+
*
|
|
128
|
+
* Called when user permissions change or security events occur.
|
|
129
|
+
* Uses conservative invalidation to ensure security.
|
|
130
|
+
*
|
|
131
|
+
* @param userId - User ID to invalidate
|
|
132
|
+
* @param reason - Reason for invalidation
|
|
133
|
+
*/
|
|
134
|
+
invalidateUserAuth(userId: string, reason: string): Promise<void>;
|
|
135
|
+
/**
|
|
136
|
+
* Block token for security reasons
|
|
137
|
+
*
|
|
138
|
+
* Immediately blocks a token from being used and clears its cache.
|
|
139
|
+
*
|
|
140
|
+
* @param token - Token to block
|
|
141
|
+
* @param reason - Reason for blocking
|
|
142
|
+
*/
|
|
143
|
+
blockToken(token: string, reason: string): Promise<void>;
|
|
144
|
+
/**
|
|
145
|
+
* Get authentication statistics
|
|
146
|
+
*/
|
|
147
|
+
getStats(): {
|
|
148
|
+
authAttempts: number;
|
|
149
|
+
authFailures: number;
|
|
150
|
+
successRate: number;
|
|
151
|
+
cacheHitRate: number;
|
|
152
|
+
cacheHits: number;
|
|
153
|
+
cacheMisses: number;
|
|
154
|
+
averageResolutionTimeUs: number;
|
|
155
|
+
totalResolutionTimeUs: number;
|
|
156
|
+
suspiciousAttempts: number;
|
|
157
|
+
blockedTokens: number;
|
|
158
|
+
lastSecurityEvent: number;
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* Reset statistics
|
|
162
|
+
*/
|
|
163
|
+
resetStats(): void;
|
|
164
|
+
/**
|
|
165
|
+
* Extract token from request context
|
|
166
|
+
*/
|
|
167
|
+
private extractToken;
|
|
168
|
+
/**
|
|
169
|
+
* Check if cached authentication is still valid
|
|
170
|
+
*/
|
|
171
|
+
private isCachedAuthValid;
|
|
172
|
+
/**
|
|
173
|
+
* Check if user is allowed to authenticate
|
|
174
|
+
*/
|
|
175
|
+
private isUserAllowed;
|
|
176
|
+
/**
|
|
177
|
+
* Cache authentication result
|
|
178
|
+
*/
|
|
179
|
+
private cacheAuthResult;
|
|
180
|
+
/**
|
|
181
|
+
* Check if request appears suspicious
|
|
182
|
+
*/
|
|
183
|
+
private isSuspiciousRequest;
|
|
184
|
+
/**
|
|
185
|
+
* Handle suspicious activity
|
|
186
|
+
*/
|
|
187
|
+
private handleSuspiciousActivity;
|
|
188
|
+
/**
|
|
189
|
+
* Record security event
|
|
190
|
+
*/
|
|
191
|
+
private recordSecurityEvent;
|
|
192
|
+
/**
|
|
193
|
+
* Hash token for secure logging
|
|
194
|
+
*/
|
|
195
|
+
private hashToken;
|
|
196
|
+
/**
|
|
197
|
+
* Log authentication event
|
|
198
|
+
*/
|
|
199
|
+
private logAuthenticationEvent;
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=FastAuthGuard.d.ts.map
|