@noony-serverless/core 0.1.1 → 0.2.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 (62) hide show
  1. package/build/core/core.d.ts +16 -48
  2. package/build/core/core.js +2 -61
  3. package/build/core/handler.d.ts +37 -16
  4. package/build/core/handler.js +131 -42
  5. package/build/core/index.d.ts +0 -1
  6. package/build/core/index.js +0 -1
  7. package/build/middlewares/ConsolidatedValidationMiddleware.d.ts +126 -0
  8. package/build/middlewares/ConsolidatedValidationMiddleware.js +330 -0
  9. package/build/middlewares/ProcessingMiddleware.d.ts +138 -0
  10. package/build/middlewares/ProcessingMiddleware.js +425 -0
  11. package/build/middlewares/SecurityMiddleware.d.ts +157 -0
  12. package/build/middlewares/SecurityMiddleware.js +307 -0
  13. package/build/middlewares/authenticationMiddleware.d.ts +379 -0
  14. package/build/middlewares/authenticationMiddleware.js +216 -0
  15. package/build/middlewares/bodyParserMiddleware.d.ts +99 -0
  16. package/build/middlewares/bodyParserMiddleware.js +99 -0
  17. package/build/middlewares/bodyValidationMiddleware.d.ts +69 -3
  18. package/build/middlewares/bodyValidationMiddleware.js +68 -2
  19. package/build/middlewares/dependencyInjectionMiddleware.d.ts +238 -0
  20. package/build/middlewares/dependencyInjectionMiddleware.js +238 -0
  21. package/build/middlewares/errorHandlerMiddleware.d.ts +94 -0
  22. package/build/middlewares/errorHandlerMiddleware.js +105 -0
  23. package/build/middlewares/guards/RouteGuards.d.ts +476 -21
  24. package/build/middlewares/guards/RouteGuards.js +418 -21
  25. package/build/middlewares/guards/adapters/CustomTokenVerificationPortAdapter.d.ts +271 -0
  26. package/build/middlewares/guards/adapters/CustomTokenVerificationPortAdapter.js +301 -0
  27. package/build/middlewares/guards/cache/CacheAdapter.d.ts +369 -28
  28. package/build/middlewares/guards/cache/CacheAdapter.js +124 -5
  29. package/build/middlewares/guards/cache/MemoryCacheAdapter.d.ts +113 -4
  30. package/build/middlewares/guards/cache/MemoryCacheAdapter.js +113 -4
  31. package/build/middlewares/guards/config/GuardConfiguration.d.ts +568 -18
  32. package/build/middlewares/guards/config/GuardConfiguration.js +266 -10
  33. package/build/middlewares/guards/guards/FastAuthGuard.d.ts +5 -5
  34. package/build/middlewares/guards/guards/PermissionGuardFactory.d.ts +5 -13
  35. package/build/middlewares/guards/guards/PermissionGuardFactory.js +4 -4
  36. package/build/middlewares/guards/index.d.ts +43 -1
  37. package/build/middlewares/guards/index.js +46 -1
  38. package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.d.ts +1 -1
  39. package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.js +1 -1
  40. package/build/middlewares/guards/resolvers/PermissionResolver.d.ts +1 -1
  41. package/build/middlewares/guards/resolvers/PlainPermissionResolver.d.ts +1 -1
  42. package/build/middlewares/guards/resolvers/WildcardPermissionResolver.d.ts +1 -1
  43. package/build/middlewares/guards/services/FastUserContextService.d.ts +20 -33
  44. package/build/middlewares/guards/services/FastUserContextService.js +19 -5
  45. package/build/middlewares/headerVariablesMiddleware.d.ts +118 -0
  46. package/build/middlewares/headerVariablesMiddleware.js +118 -0
  47. package/build/middlewares/httpAttributesMiddleware.d.ts +235 -0
  48. package/build/middlewares/httpAttributesMiddleware.js +236 -1
  49. package/build/middlewares/index.d.ts +3 -1
  50. package/build/middlewares/index.js +6 -1
  51. package/build/middlewares/queryParametersMiddleware.d.ts +105 -0
  52. package/build/middlewares/queryParametersMiddleware.js +105 -0
  53. package/build/middlewares/rateLimitingMiddleware.d.ts +601 -9
  54. package/build/middlewares/rateLimitingMiddleware.js +623 -11
  55. package/build/middlewares/responseWrapperMiddleware.d.ts +170 -1
  56. package/build/middlewares/responseWrapperMiddleware.js +170 -1
  57. package/build/middlewares/securityAuditMiddleware.js +5 -5
  58. package/package.json +11 -9
  59. package/build/core/containerPool.d.ts +0 -44
  60. package/build/core/containerPool.js +0 -103
  61. package/build/middlewares/validationMiddleware.d.ts +0 -9
  62. package/build/middlewares/validationMiddleware.js +0 -40
@@ -15,105 +15,446 @@
15
15
  * @version 1.0.0
16
16
  */
17
17
  /**
18
- * Cache adapter interface for pluggable caching strategies
19
- *
18
+ * Cache adapter interface for pluggable caching strategies.
20
19
  * Provides async operations for storing and retrieving cached data
21
20
  * with optional TTL support and pattern-based operations.
21
+ *
22
+ * @example
23
+ * Basic usage with any cache adapter:
24
+ * ```typescript
25
+ * import { CacheAdapter } from '@noony/core';
26
+ *
27
+ * class MyService {
28
+ * constructor(private cache: CacheAdapter) {}
29
+ *
30
+ * async getUserPermissions(userId: string) {
31
+ * const cacheKey = `user:${userId}:permissions`;
32
+ *
33
+ * // Try cache first
34
+ * let permissions = await this.cache.get<string[]>(cacheKey);
35
+ * if (permissions) {
36
+ * return permissions;
37
+ * }
38
+ *
39
+ * // Load from database and cache
40
+ * permissions = await this.loadPermissionsFromDB(userId);
41
+ * await this.cache.set(cacheKey, permissions, 600000); // 10 minutes
42
+ *
43
+ * return permissions;
44
+ * }
45
+ * }
46
+ * ```
47
+ *
48
+ * @example
49
+ * Pattern-based cache invalidation:
50
+ * ```typescript
51
+ * // Invalidate all user-related cache entries
52
+ * await cache.deletePattern('user:123:*');
53
+ *
54
+ * // Clear all permission caches
55
+ * await cache.deletePattern('permissions:*');
56
+ *
57
+ * // Clear everything (use with caution)
58
+ * await cache.clear();
59
+ * ```
22
60
  */
23
61
  export interface CacheAdapter {
24
62
  /**
25
- * Retrieve a cached value by key
63
+ * Retrieve a cached value by key.
64
+ * Returns null if the key doesn't exist or has expired.
26
65
  *
27
66
  * @param key - Cache key to retrieve
28
67
  * @returns Promise resolving to cached value or null if not found
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * // Retrieve user permissions from cache
72
+ * const permissions = await cache.get<string[]>('user:123:permissions');
73
+ * if (permissions) {
74
+ * console.log('Cache hit:', permissions);
75
+ * } else {
76
+ * console.log('Cache miss - need to load from database');
77
+ * }
78
+ * ```
29
79
  */
30
80
  get<T>(key: string): Promise<T | null>;
31
81
  /**
32
- * Store a value in cache with optional TTL
82
+ * Store a value in cache with optional TTL.
83
+ * If TTL is not provided, uses the cache adapter's default TTL.
33
84
  *
34
85
  * @param key - Cache key to store under
35
86
  * @param value - Value to cache (must be serializable)
36
87
  * @param ttlMs - Time to live in milliseconds (optional)
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * // Cache user permissions for 10 minutes
92
+ * await cache.set('user:123:permissions', ['read', 'write'], 600000);
93
+ *
94
+ * // Cache with default TTL
95
+ * await cache.set('session:abc123', { userId: 123, roles: ['user'] });
96
+ *
97
+ * // Cache complex objects
98
+ * await cache.set('user:123:profile', {
99
+ * id: 123,
100
+ * name: 'John Doe',
101
+ * permissions: ['read', 'write'],
102
+ * lastLogin: new Date()
103
+ * }, 300000);
104
+ * ```
37
105
  */
38
106
  set<T>(key: string, value: T, ttlMs?: number): Promise<void>;
39
107
  /**
40
- * Delete a specific cache entry
108
+ * Delete a specific cache entry.
109
+ * Silently succeeds if the key doesn't exist.
41
110
  *
42
111
  * @param key - Cache key to delete
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * // Remove specific user permissions from cache
116
+ * await cache.delete('user:123:permissions');
117
+ *
118
+ * // Clean up expired session
119
+ * await cache.delete('session:abc123');
120
+ * ```
43
121
  */
44
122
  delete(key: string): Promise<void>;
45
123
  /**
46
- * Delete multiple cache entries matching a pattern
124
+ * Delete multiple cache entries matching a pattern.
125
+ * Pattern syntax varies by implementation (Redis vs memory cache).
47
126
  *
48
127
  * @param pattern - Pattern to match keys (implementation-specific)
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * // Clear all cache entries for a specific user
132
+ * await cache.deletePattern('user:123:*');
133
+ *
134
+ * // Clear all permission caches
135
+ * await cache.deletePattern('permissions:*');
136
+ *
137
+ * // Clear all session data
138
+ * await cache.deletePattern('session:*');
139
+ *
140
+ * // Redis-style patterns (if using Redis cache)
141
+ * await cache.deletePattern('auth:token:*'); // All auth tokens
142
+ * await cache.deletePattern('user:*:profile'); // All user profiles
143
+ * ```
49
144
  */
50
145
  deletePattern(pattern: string): Promise<void>;
51
146
  /**
52
- * Clear all cache entries (conservative invalidation strategy)
147
+ * Clear all cache entries (conservative invalidation strategy).
148
+ * Used for secure cache invalidation when permissions change globally.
149
+ * Use with caution in production as this affects all cached data.
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * // Emergency cache clear after security update
154
+ * await cache.flush();
53
155
  *
54
- * Used for secure cache invalidation when permissions change
156
+ * // Clear cache after major permission system changes
157
+ * if (permissionSystemUpdated) {
158
+ * await cache.flush();
159
+ * console.log('Cache cleared due to permission system update');
160
+ * }
161
+ * ```
55
162
  */
56
163
  flush(): Promise<void>;
57
164
  /**
58
- * Get cache statistics for monitoring
165
+ * Get cache statistics for monitoring.
166
+ * Provides performance metrics for monitoring cache effectiveness.
167
+ *
168
+ * @returns Cache statistics object with hit/miss ratios and entry counts
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * const stats = await cache.getStats();
173
+ * console.log(`Cache hit rate: ${stats.hitRate}%`);
174
+ * console.log(`Total entries: ${stats.totalEntries}`);
175
+ * console.log(`Memory usage: ${stats.memoryUsage} bytes`);
59
176
  *
60
- * @returns Cache statistics object
177
+ * // Monitor cache performance
178
+ * if (stats.hitRate < 70) {
179
+ * console.warn('Cache hit rate is low - consider adjusting TTL values');
180
+ * }
181
+ * ```
61
182
  */
62
183
  getStats(): Promise<CacheStats>;
63
184
  /**
64
- * Get the name of the cache adapter for debugging
185
+ * Get the name of the cache adapter for debugging.
186
+ * Useful for logging and debugging to identify which cache implementation is active.
65
187
  *
66
- * @returns Cache adapter name
188
+ * @returns Cache adapter name (e.g., 'MemoryCache', 'RedisCache', 'NoopCache')
189
+ *
190
+ * @example
191
+ * ```typescript
192
+ * console.log(`Using cache adapter: ${cache.getName()}`);
193
+ *
194
+ * // Environment-specific logging
195
+ * if (cache.getName() === 'NoopCache') {
196
+ * console.warn('Caching is disabled - performance may be reduced');
197
+ * }
198
+ * ```
67
199
  */
68
200
  getName(): string;
69
201
  }
70
202
  /**
71
- * Cache statistics for performance monitoring
203
+ * Cache statistics for performance monitoring.
204
+ * Provides comprehensive metrics for analyzing cache performance and effectiveness.
205
+ *
206
+ * @example
207
+ * Using cache statistics for monitoring:
208
+ * ```typescript
209
+ * const stats = await cache.getStats();
210
+ *
211
+ * // Performance monitoring
212
+ * console.log(`Cache Performance Report:
213
+ * Hit Rate: ${stats.hitRate}%
214
+ * Total Entries: ${stats.totalEntries}
215
+ * Memory Usage: ${(stats.memoryUsage / 1024 / 1024).toFixed(2)} MB
216
+ * Average TTL: ${stats.averageTtlMs / 1000}s
217
+ * Evictions: ${stats.evictions}`);
218
+ *
219
+ * // Alert on poor performance
220
+ * if (stats.hitRate < 70) {
221
+ * console.warn('Low cache hit rate detected');
222
+ * }
223
+ *
224
+ * if (stats.memoryUsage > stats.maxMemoryUsage * 0.9) {
225
+ * console.warn('Cache memory usage near limit');
226
+ * }
227
+ * ```
228
+ *
229
+ * @example
230
+ * Integration with monitoring systems:
231
+ * ```typescript
232
+ * // Send metrics to monitoring service
233
+ * async function reportCacheMetrics() {
234
+ * const stats = await cache.getStats();
235
+ *
236
+ * metrics.gauge('cache.hit_rate', stats.hitRate);
237
+ * metrics.gauge('cache.total_entries', stats.totalEntries);
238
+ * metrics.gauge('cache.memory_usage', stats.memoryUsage);
239
+ * metrics.counter('cache.evictions', stats.evictions);
240
+ * }
241
+ * ```
72
242
  */
73
243
  export interface CacheStats {
74
- /** Total number of cache entries */
244
+ /**
245
+ * Total number of cache entries currently stored.
246
+ * Includes all cached items regardless of TTL status.
247
+ */
75
248
  totalEntries: number;
76
- /** Number of cache hits since startup */
249
+ /**
250
+ * Number of cache hits since startup.
251
+ * Incremented each time a requested key is found in cache.
252
+ */
77
253
  hits: number;
78
- /** Number of cache misses since startup */
254
+ /**
255
+ * Number of cache misses since startup.
256
+ * Incremented each time a requested key is not found in cache.
257
+ */
79
258
  misses: number;
80
- /** Cache hit rate as percentage (0-100) */
259
+ /**
260
+ * Cache hit rate as percentage (0-100).
261
+ * Calculated as: (hits / (hits + misses)) * 100
262
+ */
81
263
  hitRate: number;
82
- /** Memory usage in bytes (if applicable) */
264
+ /**
265
+ * Memory usage in bytes (if applicable).
266
+ * Available for memory-based cache adapters, optional for others.
267
+ */
83
268
  memoryUsage?: number;
84
- /** Time since cache was created */
269
+ /**
270
+ * Time since cache was created, in milliseconds.
271
+ * Useful for calculating rates and monitoring uptime.
272
+ */
85
273
  uptime: number;
86
274
  }
87
275
  /**
88
- * Configuration options for cache adapters
276
+ * Configuration options for cache adapters.
277
+ * Provides standardized configuration interface for all cache implementations.
278
+ *
279
+ * @example
280
+ * Memory cache configuration:
281
+ * ```typescript
282
+ * const memoryConfig: CacheConfiguration = {
283
+ * maxSize: 10000, // Store up to 10k entries
284
+ * defaultTTL: 300000, // 5 minutes default TTL
285
+ * name: 'UserPermissions' // For debugging and monitoring
286
+ * };
287
+ *
288
+ * const cache = new MemoryCacheAdapter(memoryConfig);
289
+ * ```
290
+ *
291
+ * @example
292
+ * Redis cache configuration:
293
+ * ```typescript
294
+ * const redisConfig: CacheConfiguration = {
295
+ * maxSize: 50000, // Higher capacity for distributed cache
296
+ * defaultTTL: 600000, // 10 minutes default TTL
297
+ * name: 'DistributedAuth' // Identify this cache instance
298
+ * };
299
+ *
300
+ * const cache = new RedisCacheAdapter(redisConfig, redisClient);
301
+ * ```
89
302
  */
90
303
  export interface CacheConfiguration {
91
- /** Maximum number of entries to store */
304
+ /**
305
+ * Maximum number of entries to store.
306
+ * When exceeded, cache will use eviction policy (usually LRU).
307
+ */
92
308
  maxSize: number;
93
- /** Default time to live in milliseconds */
309
+ /**
310
+ * Default time to live in milliseconds.
311
+ * Applied to cache entries when no specific TTL is provided.
312
+ */
94
313
  defaultTTL: number;
95
- /** Name for debugging/logging purposes */
314
+ /**
315
+ * Name for debugging/logging purposes.
316
+ * Helps identify cache instances in logs and monitoring.
317
+ */
96
318
  name?: string;
97
319
  }
98
320
  /**
99
- * Cache key utilities for consistent key generation
321
+ * Cache key utilities for consistent key generation.
322
+ * Provides standardized key generation methods for different types of cached data
323
+ * in the guard system, ensuring consistent naming and avoiding key collisions.
324
+ *
325
+ * @example
326
+ * Basic key generation:
327
+ * ```typescript
328
+ * // Generate cache keys for different data types
329
+ * const userKey = CacheKeyBuilder.userContext('user123');
330
+ * // Returns: "noony:guard:user:user123"
331
+ *
332
+ * const tokenKey = CacheKeyBuilder.authToken('jwt-token-here');
333
+ * // Returns: "noony:guard:auth:jwt-toke...ken-here"
334
+ *
335
+ * const permKey = CacheKeyBuilder.userPermission('user123', 'admin.users.read');
336
+ * // Returns: "noony:guard:perm:user123:admin.users.read"
337
+ * ```
338
+ *
339
+ * @example
340
+ * Pattern-based cache keys:
341
+ * ```typescript
342
+ * // Cache wildcard resolution results
343
+ * const patterns = ['admin.*', 'user.read'];
344
+ * const userPerms = ['admin.users', 'admin.reports', 'user.read'];
345
+ * const wildcardKey = CacheKeyBuilder.wildcardPattern(patterns, userPerms);
346
+ *
347
+ * // Cache expression evaluation results
348
+ * const expr = '(admin.users OR admin.reports) AND user.active';
349
+ * const exprKey = CacheKeyBuilder.expressionResult(expr, userPerms);
350
+ * ```
351
+ *
352
+ * @example
353
+ * Custom key generation:
354
+ * ```typescript
355
+ * // Generate application-specific keys
356
+ * const customKey = CacheKeyBuilder.custom('feature', 'value1', 'value2');
357
+ * // Returns: "noony:guard:feature:value1:value2"
358
+ * ```
100
359
  */
101
360
  export declare class CacheKeyBuilder {
102
361
  private static readonly PREFIX;
103
362
  /**
104
- * Generate a cache key for user context
363
+ * Generate a cache key for user context.
364
+ * Creates a standardized key for caching user authentication and role data.
365
+ *
366
+ * @param userId - Unique identifier for the user
367
+ * @returns Cache key string for user context
368
+ *
369
+ * @example
370
+ * ```typescript
371
+ * const key = CacheKeyBuilder.userContext('user123');
372
+ * // Returns: "noony:guard:user:user123"
373
+ *
374
+ * await cache.set(key, {
375
+ * userId: 'user123',
376
+ * roles: ['admin', 'user'],
377
+ * permissions: ['read', 'write'],
378
+ * lastLogin: new Date()
379
+ * });
380
+ * ```
105
381
  */
106
382
  static userContext(userId: string): string;
107
383
  /**
108
- * Generate a cache key for authentication token
384
+ * Generate a cache key for authentication token.
385
+ * Creates a secure key by using partial token hash to avoid storing full tokens.
386
+ *
387
+ * @param token - Authentication token (JWT, API key, etc.)
388
+ * @returns Cache key string for auth token
389
+ *
390
+ * @example
391
+ * ```typescript
392
+ * const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
393
+ * const key = CacheKeyBuilder.authToken(token);
394
+ * // Returns: "noony:guard:auth:eyJhbGci...dCI6IkpXVCJ9"
395
+ *
396
+ * await cache.set(key, {
397
+ * valid: true,
398
+ * userId: 'user123',
399
+ * expires: new Date(Date.now() + 3600000)
400
+ * });
401
+ * ```
109
402
  */
110
403
  static authToken(token: string): string;
111
404
  /**
112
- * Generate a cache key for wildcard permission resolution
405
+ * Generate a cache key for wildcard permission resolution.
406
+ * Creates a key for caching the results of wildcard pattern matching
407
+ * against user permissions.
408
+ *
409
+ * @param patterns - Array of wildcard patterns to match
410
+ * @param userPermissions - Array of user's actual permissions
411
+ * @returns Cache key string for wildcard resolution
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * const patterns = ['admin.*', 'user.read'];
416
+ * const userPerms = ['admin.users', 'admin.reports', 'user.read'];
417
+ * const key = CacheKeyBuilder.wildcardPattern(patterns, userPerms);
418
+ * // Returns: "noony:guard:wildcard:hash1:hash2"
419
+ *
420
+ * // Cache the expansion result
421
+ * await cache.set(key, {
422
+ * matched: ['admin.users', 'admin.reports', 'user.read'],
423
+ * expandedPatterns: {
424
+ * 'admin.*': ['admin.users', 'admin.reports'],
425
+ * 'user.read': ['user.read']
426
+ * }
427
+ * });
428
+ * ```
113
429
  */
114
430
  static wildcardPattern(patterns: string[], userPermissions: string[]): string;
115
431
  /**
116
- * Generate a cache key for expression permission resolution
432
+ * Generate a cache key for expression permission resolution.
433
+ * Creates a key for caching the results of boolean expression evaluation
434
+ * against user permissions.
435
+ *
436
+ * @param expression - Boolean expression object to evaluate
437
+ * @param userPermissions - Array of user's actual permissions
438
+ * @returns Cache key string for expression evaluation
439
+ *
440
+ * @example
441
+ * ```typescript
442
+ * const expression = {
443
+ * type: 'AND',
444
+ * left: { type: 'permission', value: 'admin.users' },
445
+ * right: { type: 'permission', value: 'admin.reports' }
446
+ * };
447
+ * const userPerms = ['admin.users', 'admin.reports', 'user.read'];
448
+ * const key = CacheKeyBuilder.expressionResult(expression, userPerms);
449
+ * // Returns: "noony:guard:expression:exprHash:permHash"
450
+ *
451
+ * // Cache the evaluation result
452
+ * await cache.set(key, {
453
+ * result: true,
454
+ * evaluatedAt: new Date(),
455
+ * usedPermissions: ['admin.users', 'admin.reports']
456
+ * });
457
+ * ```
117
458
  */
118
459
  static expressionResult(expression: object, userPermissions: string[]): string;
119
460
  /**
@@ -18,25 +18,119 @@
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
19
  exports.CacheKeyBuilder = void 0;
20
20
  /**
21
- * Cache key utilities for consistent key generation
21
+ * Cache key utilities for consistent key generation.
22
+ * Provides standardized key generation methods for different types of cached data
23
+ * in the guard system, ensuring consistent naming and avoiding key collisions.
24
+ *
25
+ * @example
26
+ * Basic key generation:
27
+ * ```typescript
28
+ * // Generate cache keys for different data types
29
+ * const userKey = CacheKeyBuilder.userContext('user123');
30
+ * // Returns: "noony:guard:user:user123"
31
+ *
32
+ * const tokenKey = CacheKeyBuilder.authToken('jwt-token-here');
33
+ * // Returns: "noony:guard:auth:jwt-toke...ken-here"
34
+ *
35
+ * const permKey = CacheKeyBuilder.userPermission('user123', 'admin.users.read');
36
+ * // Returns: "noony:guard:perm:user123:admin.users.read"
37
+ * ```
38
+ *
39
+ * @example
40
+ * Pattern-based cache keys:
41
+ * ```typescript
42
+ * // Cache wildcard resolution results
43
+ * const patterns = ['admin.*', 'user.read'];
44
+ * const userPerms = ['admin.users', 'admin.reports', 'user.read'];
45
+ * const wildcardKey = CacheKeyBuilder.wildcardPattern(patterns, userPerms);
46
+ *
47
+ * // Cache expression evaluation results
48
+ * const expr = '(admin.users OR admin.reports) AND user.active';
49
+ * const exprKey = CacheKeyBuilder.expressionResult(expr, userPerms);
50
+ * ```
51
+ *
52
+ * @example
53
+ * Custom key generation:
54
+ * ```typescript
55
+ * // Generate application-specific keys
56
+ * const customKey = CacheKeyBuilder.custom('feature', 'value1', 'value2');
57
+ * // Returns: "noony:guard:feature:value1:value2"
58
+ * ```
22
59
  */
23
60
  class CacheKeyBuilder {
24
61
  static PREFIX = 'noony:guard';
25
62
  /**
26
- * Generate a cache key for user context
63
+ * Generate a cache key for user context.
64
+ * Creates a standardized key for caching user authentication and role data.
65
+ *
66
+ * @param userId - Unique identifier for the user
67
+ * @returns Cache key string for user context
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const key = CacheKeyBuilder.userContext('user123');
72
+ * // Returns: "noony:guard:user:user123"
73
+ *
74
+ * await cache.set(key, {
75
+ * userId: 'user123',
76
+ * roles: ['admin', 'user'],
77
+ * permissions: ['read', 'write'],
78
+ * lastLogin: new Date()
79
+ * });
80
+ * ```
27
81
  */
28
82
  static userContext(userId) {
29
83
  return `${this.PREFIX}:user:${userId}`;
30
84
  }
31
85
  /**
32
- * Generate a cache key for authentication token
86
+ * Generate a cache key for authentication token.
87
+ * Creates a secure key by using partial token hash to avoid storing full tokens.
88
+ *
89
+ * @param token - Authentication token (JWT, API key, etc.)
90
+ * @returns Cache key string for auth token
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
95
+ * const key = CacheKeyBuilder.authToken(token);
96
+ * // Returns: "noony:guard:auth:eyJhbGci...dCI6IkpXVCJ9"
97
+ *
98
+ * await cache.set(key, {
99
+ * valid: true,
100
+ * userId: 'user123',
101
+ * expires: new Date(Date.now() + 3600000)
102
+ * });
103
+ * ```
33
104
  */
34
105
  static authToken(token) {
35
106
  const tokenHash = token.substring(0, 8) + '...' + token.substring(token.length - 8);
36
107
  return `${this.PREFIX}:auth:${tokenHash}`;
37
108
  }
38
109
  /**
39
- * Generate a cache key for wildcard permission resolution
110
+ * Generate a cache key for wildcard permission resolution.
111
+ * Creates a key for caching the results of wildcard pattern matching
112
+ * against user permissions.
113
+ *
114
+ * @param patterns - Array of wildcard patterns to match
115
+ * @param userPermissions - Array of user's actual permissions
116
+ * @returns Cache key string for wildcard resolution
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * const patterns = ['admin.*', 'user.read'];
121
+ * const userPerms = ['admin.users', 'admin.reports', 'user.read'];
122
+ * const key = CacheKeyBuilder.wildcardPattern(patterns, userPerms);
123
+ * // Returns: "noony:guard:wildcard:hash1:hash2"
124
+ *
125
+ * // Cache the expansion result
126
+ * await cache.set(key, {
127
+ * matched: ['admin.users', 'admin.reports', 'user.read'],
128
+ * expandedPatterns: {
129
+ * 'admin.*': ['admin.users', 'admin.reports'],
130
+ * 'user.read': ['user.read']
131
+ * }
132
+ * });
133
+ * ```
40
134
  */
41
135
  static wildcardPattern(patterns, userPermissions) {
42
136
  const patternHash = this.hashArray(patterns);
@@ -44,7 +138,32 @@ class CacheKeyBuilder {
44
138
  return `${this.PREFIX}:wildcard:${patternHash}:${permissionHash}`;
45
139
  }
46
140
  /**
47
- * Generate a cache key for expression permission resolution
141
+ * Generate a cache key for expression permission resolution.
142
+ * Creates a key for caching the results of boolean expression evaluation
143
+ * against user permissions.
144
+ *
145
+ * @param expression - Boolean expression object to evaluate
146
+ * @param userPermissions - Array of user's actual permissions
147
+ * @returns Cache key string for expression evaluation
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * const expression = {
152
+ * type: 'AND',
153
+ * left: { type: 'permission', value: 'admin.users' },
154
+ * right: { type: 'permission', value: 'admin.reports' }
155
+ * };
156
+ * const userPerms = ['admin.users', 'admin.reports', 'user.read'];
157
+ * const key = CacheKeyBuilder.expressionResult(expression, userPerms);
158
+ * // Returns: "noony:guard:expression:exprHash:permHash"
159
+ *
160
+ * // Cache the evaluation result
161
+ * await cache.set(key, {
162
+ * result: true,
163
+ * evaluatedAt: new Date(),
164
+ * usedPermissions: ['admin.users', 'admin.reports']
165
+ * });
166
+ * ```
48
167
  */
49
168
  static expressionResult(expression, userPermissions) {
50
169
  const expressionHash = this.hashObject(expression);