exguard-backend 1.0.22 → 1.0.23

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/dist/index.cjs CHANGED
@@ -290,11 +290,14 @@ var ExGuardRealtime = class {
290
290
  reconnectDelay = 1e3;
291
291
  /**
292
292
  * Connect to realtime server
293
+ * @param url - WebSocket URL
294
+ * @param token - Optional authentication token
293
295
  */
294
296
  connect(url, token) {
295
297
  return new Promise((resolve, reject) => {
296
298
  try {
297
- this.websocket = new WebSocket(`${url}?token=${token}`);
299
+ const wsUrl = token ? `${url}?token=${token}` : url;
300
+ this.websocket = new WebSocket(wsUrl);
298
301
  const timeout = setTimeout(() => {
299
302
  reject(new Error("Connection timeout"));
300
303
  }, 1e4);
@@ -425,7 +428,7 @@ var ExGuardBackendEnhanced = class {
425
428
  "Content-Type": "application/json"
426
429
  }
427
430
  });
428
- if (this.config.realtime?.enabled && this.config.realtime.url && this.config.realtime.token) {
431
+ if (this.config.realtime?.enabled && this.config.realtime.url) {
429
432
  this.setupRealtime();
430
433
  }
431
434
  setInterval(() => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/exguard-backend.ts","../src/exguard-backend-enhanced.ts","../src/cache.ts","../src/realtime.ts","../src/guards.ts","../src/express.ts","../src/fastify.ts"],"sourcesContent":["export { ExGuardBackend } from './exguard-backend.js';\nexport { ExGuardBackendEnhanced } from './exguard-backend-enhanced.js';\nexport { cache, ExGuardCache } from './cache.js';\nexport { realtime, ExGuardRealtime } from './realtime.js';\n\n// Backend protection exports\nexport { ExGuardBackend as Guard } from './guards.js';\nexport { createExGuardExpress } from './express.js';\nexport { createExGuardFastify } from './fastify.js';\nexport type { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig,\n ExGuardEnhancedConfig,\n ExGuardCacheConfig,\n ExGuardRealtimeConfig,\n GuardContext,\n GuardResult,\n GuardOptions\n} from './types.js';\n","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\n\nexport class ExGuardBackend {\n private client: AxiosInstance;\n private config: ExGuardConfig;\n\n constructor(config: ExGuardConfig) {\n this.config = {\n timeout: 10000,\n ...config,\n };\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Get user roles and permissions from the /guard/me endpoint\n * @param token - JWT access token\n * @returns Promise<UserAccessResponse>\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission\n * @param token - JWT access token\n * @param permission - Permission to check (e.g., 'events:create')\n * @returns Promise<boolean>\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Check if user has specific role\n * @param token - JWT access token\n * @param role - Role to check (e.g., 'Event Manager')\n * @returns Promise<boolean>\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Get all permissions for a specific module\n * @param token - JWT access token\n * @param moduleKey - Module key (e.g., 'events')\n * @returns Promise<string[]>\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user roles\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserRoles(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user field offices\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n } catch (error) {\n return [];\n }\n }\n}\n","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\nimport { cache, ExGuardCache } from './cache.js';\nimport { realtime, RealtimeEvent, ExGuardRealtime } from './realtime.js';\n\nexport interface ExGuardEnhancedConfig extends ExGuardConfig {\n cache?: {\n ttl?: number;\n enabled?: boolean;\n };\n realtime?: {\n enabled?: boolean;\n url?: string;\n token?: string;\n };\n}\n\nexport class ExGuardBackendEnhanced {\n private client: AxiosInstance;\n private config: ExGuardEnhancedConfig;\n private cache: ExGuardCache;\n private realtime: ExGuardRealtime;\n private userId: string | null = null;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000, // 5 minutes\n },\n realtime: {\n enabled: false,\n },\n ...config,\n };\n\n this.cache = cache;\n this.realtime = realtime;\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Setup realtime if enabled\n if (this.config.realtime?.enabled && this.config.realtime.url && this.config.realtime.token) {\n this.setupRealtime();\n }\n\n // Setup periodic cache cleanup\n setInterval(() => {\n this.cache.cleanup();\n }, 60000); // Every minute\n }\n\n /**\n * Setup realtime connection and event handlers\n */\n private async setupRealtime(): Promise<void> {\n try {\n await this.realtime.connect(this.config.realtime!.url!, this.config.realtime!.token!);\n \n // Subscribe to RBAC updates\n this.realtime.subscribe('rbac_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] RBAC update received:', event);\n \n // Clear cache for affected user\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n // Clear all cache if no specific user\n this.cache.clear();\n }\n });\n\n // Subscribe to user updates\n this.realtime.subscribe('user_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] User update received:', event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n }\n });\n\n } catch (error) {\n console.error('[ExGuardBackend] Failed to setup realtime:', error);\n }\n }\n\n /**\n * Extract user ID from JWT token\n */\n private extractUserIdFromToken(token: string): string | null {\n try {\n const payload = JSON.parse(atob(token.split('.')[1]));\n return payload.sub || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Get cache key for user data\n */\n private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\n\n /**\n * Get user roles and permissions from cache or API\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n if (!this.config.cache?.enabled) {\n return this.fetchUserAccess(token);\n }\n\n const cacheKey = this.getCacheKey(token, 'access');\n const cached = this.cache.get<UserAccessResponse>(cacheKey);\n \n if (cached) {\n console.log('[ExGuardBackend] Cache hit for user access');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user access');\n const data = await this.fetchUserAccess(token);\n \n // Cache the result\n this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\n\n /**\n * Fetch user access from API (always hits the server)\n */\n private async fetchUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission (cached)\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n }\n\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for permission: ${permission}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking permission: ${permission}`);\n const userAccess = await this.getUserAccess(token);\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n \n // Cache the result with shorter TTL for permissions\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\n\n /**\n * Check if user has specific role (cached)\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n }\n\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for role: ${role}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking role: ${role}`);\n const userAccess = await this.getUserAccess(token);\n const hasRole = userAccess.roles.includes(role);\n \n // Cache the result with shorter TTL for roles\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\n\n /**\n * Get all permissions for a specific module (cached)\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n }\n\n const cacheKey = this.getCacheKey(token, `module:${moduleKey}`);\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for module: ${moduleKey}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, fetching module permissions: ${moduleKey}`);\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n const permissions = module?.permissions || [];\n \n // Cache the result\n this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\n\n /**\n * Get user roles (cached)\n */\n async getUserRoles(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n }\n\n const cacheKey = this.getCacheKey(token, 'roles');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for user roles');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user roles');\n const userAccess = await this.getUserAccess(token);\n const roles = userAccess.roles;\n \n // Cache the result\n this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\n\n /**\n * Get user field offices (cached)\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n }\n\n const cacheKey = this.getCacheKey(token, 'field-offices');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for field offices');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching field offices');\n const userAccess = await this.getUserAccess(token);\n const fieldOffices = userAccess.fieldOffices;\n \n // Cache the result\n this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n /**\n * Batch check multiple permissions (optimized)\n */\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all permissions\n const uncachedPermissions: string[] = [];\n \n for (const permission of permissions) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[permission] = cached;\n } else {\n uncachedPermissions.push(permission);\n }\n } else {\n uncachedPermissions.push(permission);\n }\n }\n\n // Fetch user access once for all uncached permissions\n if (uncachedPermissions.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const permission of uncachedPermissions) {\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n results[permission] = hasPermission;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Batch check multiple roles (optimized)\n */\n async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all roles\n const uncachedRoles: string[] = [];\n \n for (const role of roles) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[role] = cached;\n } else {\n uncachedRoles.push(role);\n }\n } else {\n uncachedRoles.push(role);\n }\n }\n\n // Fetch user access once for all uncached roles\n if (uncachedRoles.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const role of uncachedRoles) {\n const hasRole = userAccess.roles.includes(role);\n results[role] = hasRole;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(token: string): void {\n const userId = this.extractUserIdFromToken(token);\n if (userId) {\n this.cache.clearUserCache(userId);\n console.log(`[ExGuardBackend] Cache cleared for user: ${userId}`);\n }\n }\n\n /**\n * Get cache statistics\n */\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.realtime.disconnect();\n }\n}\n","/**\n * In-memory cache for user access data with TTL support\n */\n\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n ttl: number;\n}\n\nexport class ExGuardCache {\n private cache = new Map<string, CacheEntry<any>>();\n private subscribers = new Map<string, Set<() => void>>();\n private defaultTTL = 300000; // 5 minutes\n\n /**\n * Get cached data\n */\n get<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n\n // Check if expired\n if (Date.now() - entry.timestamp > entry.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data;\n }\n\n /**\n * Set cached data with TTL\n */\n set<T>(key: string, data: T, ttl?: number): void {\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n ttl: ttl || this.defaultTTL,\n });\n }\n\n /**\n * Delete cached data\n */\n delete(key: string): boolean {\n const deleted = this.cache.delete(key);\n if (deleted) {\n this.notifySubscribers(key);\n }\n return deleted;\n }\n\n /**\n * Clear all cache\n */\n clear(): void {\n const keys = Array.from(this.cache.keys());\n this.cache.clear();\n keys.forEach(key => this.notifySubscribers(key));\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(userId: string): void {\n const keysToDelete = Array.from(this.cache.keys()).filter(key => \n key.startsWith(`user:${userId}:`)\n );\n \n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n\n /**\n * Subscribe to cache changes\n */\n subscribe(key: string, callback: () => void): () => void {\n if (!this.subscribers.has(key)) {\n this.subscribers.set(key, new Set());\n }\n \n this.subscribers.get(key)!.add(callback);\n \n // Return unsubscribe function\n return () => {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscribers.delete(key);\n }\n }\n };\n }\n\n /**\n * Notify subscribers of cache changes\n */\n private notifySubscribers(key: string): void {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.forEach(callback => {\n try {\n callback();\n } catch (error) {\n console.error('Cache subscriber error:', error);\n }\n });\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats(): { size: number; keys: string[] } {\n return {\n size: this.cache.size,\n keys: Array.from(this.cache.keys()),\n };\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n const keysToDelete: string[] = [];\n\n this.cache.forEach((entry, key) => {\n if (now - entry.timestamp > entry.ttl) {\n keysToDelete.push(key);\n }\n });\n\n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n}\n\n// Global cache instance\nexport const cache = new ExGuardCache();\n","/**\n * Realtime event handling for cache invalidation\n */\n\nexport interface RealtimeEvent {\n type: 'rbac_update' | 'user_update' | 'role_update' | 'permission_update';\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private websocket: WebSocket | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000;\n\n /**\n * Connect to realtime server\n */\n connect(url: string, token: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.websocket = new WebSocket(`${url}?token=${token}`);\n\n const timeout = setTimeout(() => {\n reject(new Error('Connection timeout'));\n }, 10000);\n\n this.websocket.onopen = () => {\n clearTimeout(timeout);\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected to realtime server');\n resolve();\n };\n\n this.websocket.onmessage = (event) => {\n try {\n const realtimeEvent: RealtimeEvent = JSON.parse(event.data);\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to parse event:', error);\n }\n };\n\n this.websocket.onclose = () => {\n clearTimeout(timeout);\n console.log('[ExGuardRealtime] Disconnected from realtime server');\n this.handleReconnect(url, token);\n };\n\n this.websocket.onerror = (error) => {\n clearTimeout(timeout);\n console.error('[ExGuardRealtime] WebSocket error:', error);\n reject(error);\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n if (this.websocket) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribe(eventType: string, handler: RealtimeEventHandler): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n \n this.handlers.get(eventType)!.add(handler);\n \n // Return unsubscribe function\n return () => {\n const handlers = this.handlers.get(eventType);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n this.handlers.delete(eventType);\n }\n }\n };\n }\n\n /**\n * Handle incoming realtime events\n */\n private handleEvent(event: RealtimeEvent): void {\n console.log('[ExGuardRealtime] Received event:', event);\n \n const handlers = this.handlers.get(event.type);\n if (handlers) {\n handlers.forEach(handler => {\n try {\n handler(event);\n } catch (error) {\n console.error('[ExGuardRealtime] Event handler error:', error);\n }\n });\n }\n }\n\n /**\n * Handle reconnection logic\n */\n private handleReconnect(url: string, token: string): void {\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(url, token).catch(error => {\n console.error('[ExGuardRealtime] Reconnection failed:', error);\n });\n }, delay);\n } else {\n console.error('[ExGuardRealtime] Max reconnection attempts reached');\n }\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.websocket?.readyState === WebSocket.OPEN;\n }\n}\n\n// Global realtime instance\nexport const realtime = new ExGuardRealtime();\n","/**\n * Framework-agnostic guards for protecting backend endpoints\n */\n\nimport { ExGuardBackendEnhanced } from './exguard-backend-enhanced.js';\nimport { ExGuardEnhancedConfig, UserAccessResponse, GuardContext, GuardResult, GuardOptions } from './types.js';\n\n// Re-export types for use in other modules\nexport type { GuardContext, GuardResult, GuardOptions, UserAccessResponse };\n\n/**\n * Framework-agnostic guard class for endpoint protection\n */\nexport class ExGuardBackend {\n private exGuard: ExGuardBackendEnhanced;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.exGuard = new ExGuardBackendEnhanced(config);\n }\n\n /**\n * Check if user has specific permissions\n */\n async requirePermissions(\n context: GuardContext, \n permissions: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL permissions\n const results = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAll = permissions.every(permission => results[permission]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY permission (default)\n const hasPermission = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAny = Object.values(hasPermission).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required any of: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Permission check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has specific roles\n */\n async requireRoles(\n context: GuardContext, \n roles: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL roles\n const results = await this.exGuard.hasRoles(context.token, roles);\n const hasAll = roles.every(role => results[role]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient roles. Required: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY role (default)\n const hasRole = await this.exGuard.hasRoles(context.token, roles);\n const hasAny = Object.values(hasRole).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient roles. Required any of: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Role check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific modules\n */\n async requireModules(\n context: GuardContext, \n modules: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n const userModuleKeys = userAccess.modules.map(m => m.key);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL modules\n hasAccess = modules.every(module => userModuleKeys.includes(module));\n } else {\n // Require ANY module (default)\n hasAccess = modules.some(module => userModuleKeys.includes(module));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient module access. Required: ${modules.join(', ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Module check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific field offices\n */\n async requireFieldOffices(\n context: GuardContext, \n fieldOffices: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userFieldOffices = await this.exGuard.getUserFieldOffices(context.token);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL field offices\n hasAccess = fieldOffices.every(office => userFieldOffices.includes(office));\n } else {\n // Require ANY field office (default)\n hasAccess = fieldOffices.some(office => userFieldOffices.includes(office));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient field office access. Required: ${fieldOffices.join(', ')}`,\n statusCode: 403\n };\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Field office check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Flexible guard with multiple requirements\n */\n async require(context: GuardContext, options: GuardOptions): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n let passed = true;\n const failures: string[] = [];\n\n // Check permissions\n if (options.permissions && options.permissions.length > 0) {\n const userPermissions = userAccess.modules.flatMap(m => m.permissions);\n const hasPermissions = options.requireAll\n ? options.permissions.every(p => userPermissions.includes(p))\n : options.permissions.some(p => userPermissions.includes(p));\n \n if (!hasPermissions) {\n passed = false;\n failures.push(`permissions: ${options.permissions.join(', ')}`);\n }\n }\n\n // Check roles\n if (options.roles && options.roles.length > 0) {\n const hasRoles = options.requireAll\n ? options.roles.every(r => userAccess.roles.includes(r))\n : options.roles.some(r => userAccess.roles.includes(r));\n \n if (!hasRoles) {\n passed = false;\n failures.push(`roles: ${options.roles.join(', ')}`);\n }\n }\n\n // Check modules\n if (options.modules && options.modules.length > 0) {\n const userModuleKeys = userAccess.modules.map(m => m.key);\n const hasModules = options.requireAll\n ? options.modules.every(m => userModuleKeys.includes(m))\n : options.modules.some(m => userModuleKeys.includes(m));\n \n if (!hasModules) {\n passed = false;\n failures.push(`modules: ${options.modules.join(', ')}`);\n }\n }\n\n // Check field offices\n if (options.fieldOffices && options.fieldOffices.length > 0) {\n const hasFieldOffices = options.requireAll\n ? options.fieldOffices.every(fo => userAccess.fieldOffices.includes(fo))\n : options.fieldOffices.some(fo => userAccess.fieldOffices.includes(fo));\n \n if (!hasFieldOffices) {\n passed = false;\n failures.push(`field offices: ${options.fieldOffices.join(', ')}`);\n }\n }\n\n if (!passed) {\n return {\n allowed: false,\n error: `Access denied. Missing: ${failures.join('; ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Access check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Simple authentication (just validates token)\n */\n async authenticate(context: GuardContext): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Authentication failed',\n statusCode: 401\n };\n }\n }\n\n /**\n * Get the underlying ExGuardBackendEnhanced instance\n */\n getExGuard(): ExGuardBackendEnhanced {\n return this.exGuard;\n }\n}\n\n/**\n * Helper function to extract token from various request types\n */\nexport function extractToken(request: any): string | null {\n // Express-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Fastify-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Custom header\n if (request.headers?.['x-access-token']) {\n return request.headers['x-access-token'];\n }\n\n // Query parameter\n if (request.query?.token) {\n return request.query.token;\n }\n\n return null;\n}\n\n/**\n * Create a guard context from a request\n */\nexport function createGuardContext(request: any): GuardContext | null {\n const token = extractToken(request);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request\n };\n}\n","/**\n * Express.js middleware for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when express is not installed\ntype Request = any;\ntype Response = any;\ntype NextFunction = any;\n\nexport interface AuthenticatedRequest extends Request {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Express middleware factory\n */\nexport function createExGuardExpress(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Simple authentication middleware\n */\n authenticate() {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 401).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: Request): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n","/**\n * Fastify plugin for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when fastify is not installed\ntype FastifyRequest = any;\ntype FastifyReply = any;\n\nexport interface AuthenticatedRequest extends FastifyRequest {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Fastify plugin factory\n */\nexport function createExGuardFastify(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Simple authentication hook\n */\n authenticate() {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 401).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: FastifyRequest): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAoD;AAO7C,IAAM,iBAAN,MAAqB;AAAA,EAClB;AAAA,EACA;AAAA,EAER,YAAY,QAAuB;AACjC,SAAK,SAAS;AAAA,MACZ,SAAS;AAAA,MACT,GAAG;AAAA,IACL;AAEA,SAAK,SAAS,aAAAC,Q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AM,OAAO,OAAO,cAAc,GAAG,EAAE,KAAK;AAAA,YACjD,SAAS;AAAA,YACT,SAAS,OAAO;AAAA,UAClB,CAAC;AAAA,QACH;AAGA,YAAI,OAAO,MAAM;AACf,cAAI,OAAO;AAAA,YACT,IAAI,OAAO,KAAK,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK,KAAK;AAAA,YAC/B,UAAU,OAAO,KAAK,KAAK;AAAA,YAC3B,OAAO,OAAO,KAAK,KAAK;AAAA,YACxB,OAAO,OAAO,KAAK;AAAA,YACnB,aAAa,OAAO,KAAK,QAAQ,QAAQ,OAAK,EAAE,WAAW;AAAA,YAC3D,SAAS,OAAO,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK;AAAA,UAC5B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,WAA2B;AACzB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,SAASA,oBAAmB,KAA0C;AACpE,QAAM,QAAQ,aAAa,GAAG;AAC9B,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":["ExGuardBackend","axios","module","import_axios","axios","userAccess","module","ExGuardBackend","module","ExGuardBackend","ExGuardBackend","createGuardContext"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/exguard-backend.ts","../src/exguard-backend-enhanced.ts","../src/cache.ts","../src/realtime.ts","../src/guards.ts","../src/express.ts","../src/fastify.ts"],"sourcesContent":["export { ExGuardBackend } from './exguard-backend.js';\nexport { ExGuardBackendEnhanced } from './exguard-backend-enhanced.js';\nexport { cache, ExGuardCache } from './cache.js';\nexport { realtime, ExGuardRealtime } from './realtime.js';\n\n// Backend protection exports\nexport { ExGuardBackend as Guard } from './guards.js';\nexport { createExGuardExpress } from './express.js';\nexport { createExGuardFastify } from './fastify.js';\nexport type { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig,\n ExGuardEnhancedConfig,\n ExGuardCacheConfig,\n ExGuardRealtimeConfig,\n GuardContext,\n GuardResult,\n GuardOptions\n} from './types.js';\n","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\n\nexport class ExGuardBackend {\n private client: AxiosInstance;\n private config: ExGuardConfig;\n\n constructor(config: ExGuardConfig) {\n this.config = {\n timeout: 10000,\n ...config,\n };\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Get user roles and permissions from the /guard/me endpoint\n * @param token - JWT access token\n * @returns Promise<UserAccessResponse>\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission\n * @param token - JWT access token\n * @param permission - Permission to check (e.g., 'events:create')\n * @returns Promise<boolean>\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Check if user has specific role\n * @param token - JWT access token\n * @param role - Role to check (e.g., 'Event Manager')\n * @returns Promise<boolean>\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Get all permissions for a specific module\n * @param token - JWT access token\n * @param moduleKey - Module key (e.g., 'events')\n * @returns Promise<string[]>\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user roles\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserRoles(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user field offices\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n } catch (error) {\n return [];\n }\n }\n}\n","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\nimport { cache, ExGuardCache } from './cache.js';\nimport { realtime, RealtimeEvent, ExGuardRealtime } from './realtime.js';\n\nexport interface ExGuardEnhancedConfig extends ExGuardConfig {\n cache?: {\n ttl?: number;\n enabled?: boolean;\n };\n realtime?: {\n enabled?: boolean;\n url?: string;\n token?: string;\n };\n}\n\nexport class ExGuardBackendEnhanced {\n private client: AxiosInstance;\n private config: ExGuardEnhancedConfig;\n private cache: ExGuardCache;\n private realtime: ExGuardRealtime;\n private userId: string | null = null;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000, // 5 minutes\n },\n realtime: {\n enabled: false,\n },\n ...config,\n };\n\n this.cache = cache;\n this.realtime = realtime;\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Setup realtime if enabled\n if (this.config.realtime?.enabled && this.config.realtime.url) {\n this.setupRealtime();\n }\n\n // Setup periodic cache cleanup\n setInterval(() => {\n this.cache.cleanup();\n }, 60000); // Every minute\n }\n\n /**\n * Setup realtime connection and event handlers\n */\n private async setupRealtime(): Promise<void> {\n try {\n await this.realtime.connect(this.config.realtime!.url!, this.config.realtime!.token!);\n \n // Subscribe to RBAC updates\n this.realtime.subscribe('rbac_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] RBAC update received:', event);\n \n // Clear cache for affected user\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n // Clear all cache if no specific user\n this.cache.clear();\n }\n });\n\n // Subscribe to user updates\n this.realtime.subscribe('user_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] User update received:', event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n }\n });\n\n } catch (error) {\n console.error('[ExGuardBackend] Failed to setup realtime:', error);\n }\n }\n\n /**\n * Extract user ID from JWT token\n */\n private extractUserIdFromToken(token: string): string | null {\n try {\n const payload = JSON.parse(atob(token.split('.')[1]));\n return payload.sub || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Get cache key for user data\n */\n private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\n\n /**\n * Get user roles and permissions from cache or API\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n if (!this.config.cache?.enabled) {\n return this.fetchUserAccess(token);\n }\n\n const cacheKey = this.getCacheKey(token, 'access');\n const cached = this.cache.get<UserAccessResponse>(cacheKey);\n \n if (cached) {\n console.log('[ExGuardBackend] Cache hit for user access');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user access');\n const data = await this.fetchUserAccess(token);\n \n // Cache the result\n this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\n\n /**\n * Fetch user access from API (always hits the server)\n */\n private async fetchUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission (cached)\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n }\n\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for permission: ${permission}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking permission: ${permission}`);\n const userAccess = await this.getUserAccess(token);\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n \n // Cache the result with shorter TTL for permissions\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\n\n /**\n * Check if user has specific role (cached)\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n }\n\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for role: ${role}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking role: ${role}`);\n const userAccess = await this.getUserAccess(token);\n const hasRole = userAccess.roles.includes(role);\n \n // Cache the result with shorter TTL for roles\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\n\n /**\n * Get all permissions for a specific module (cached)\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n }\n\n const cacheKey = this.getCacheKey(token, `module:${moduleKey}`);\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for module: ${moduleKey}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, fetching module permissions: ${moduleKey}`);\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n const permissions = module?.permissions || [];\n \n // Cache the result\n this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\n\n /**\n * Get user roles (cached)\n */\n async getUserRoles(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n }\n\n const cacheKey = this.getCacheKey(token, 'roles');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for user roles');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user roles');\n const userAccess = await this.getUserAccess(token);\n const roles = userAccess.roles;\n \n // Cache the result\n this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\n\n /**\n * Get user field offices (cached)\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n }\n\n const cacheKey = this.getCacheKey(token, 'field-offices');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for field offices');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching field offices');\n const userAccess = await this.getUserAccess(token);\n const fieldOffices = userAccess.fieldOffices;\n \n // Cache the result\n this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n /**\n * Batch check multiple permissions (optimized)\n */\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all permissions\n const uncachedPermissions: string[] = [];\n \n for (const permission of permissions) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[permission] = cached;\n } else {\n uncachedPermissions.push(permission);\n }\n } else {\n uncachedPermissions.push(permission);\n }\n }\n\n // Fetch user access once for all uncached permissions\n if (uncachedPermissions.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const permission of uncachedPermissions) {\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n results[permission] = hasPermission;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Batch check multiple roles (optimized)\n */\n async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all roles\n const uncachedRoles: string[] = [];\n \n for (const role of roles) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[role] = cached;\n } else {\n uncachedRoles.push(role);\n }\n } else {\n uncachedRoles.push(role);\n }\n }\n\n // Fetch user access once for all uncached roles\n if (uncachedRoles.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const role of uncachedRoles) {\n const hasRole = userAccess.roles.includes(role);\n results[role] = hasRole;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(token: string): void {\n const userId = this.extractUserIdFromToken(token);\n if (userId) {\n this.cache.clearUserCache(userId);\n console.log(`[ExGuardBackend] Cache cleared for user: ${userId}`);\n }\n }\n\n /**\n * Get cache statistics\n */\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.realtime.disconnect();\n }\n}\n","/**\n * In-memory cache for user access data with TTL support\n */\n\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n ttl: number;\n}\n\nexport class ExGuardCache {\n private cache = new Map<string, CacheEntry<any>>();\n private subscribers = new Map<string, Set<() => void>>();\n private defaultTTL = 300000; // 5 minutes\n\n /**\n * Get cached data\n */\n get<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n\n // Check if expired\n if (Date.now() - entry.timestamp > entry.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data;\n }\n\n /**\n * Set cached data with TTL\n */\n set<T>(key: string, data: T, ttl?: number): void {\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n ttl: ttl || this.defaultTTL,\n });\n }\n\n /**\n * Delete cached data\n */\n delete(key: string): boolean {\n const deleted = this.cache.delete(key);\n if (deleted) {\n this.notifySubscribers(key);\n }\n return deleted;\n }\n\n /**\n * Clear all cache\n */\n clear(): void {\n const keys = Array.from(this.cache.keys());\n this.cache.clear();\n keys.forEach(key => this.notifySubscribers(key));\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(userId: string): void {\n const keysToDelete = Array.from(this.cache.keys()).filter(key => \n key.startsWith(`user:${userId}:`)\n );\n \n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n\n /**\n * Subscribe to cache changes\n */\n subscribe(key: string, callback: () => void): () => void {\n if (!this.subscribers.has(key)) {\n this.subscribers.set(key, new Set());\n }\n \n this.subscribers.get(key)!.add(callback);\n \n // Return unsubscribe function\n return () => {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscribers.delete(key);\n }\n }\n };\n }\n\n /**\n * Notify subscribers of cache changes\n */\n private notifySubscribers(key: string): void {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.forEach(callback => {\n try {\n callback();\n } catch (error) {\n console.error('Cache subscriber error:', error);\n }\n });\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats(): { size: number; keys: string[] } {\n return {\n size: this.cache.size,\n keys: Array.from(this.cache.keys()),\n };\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n const keysToDelete: string[] = [];\n\n this.cache.forEach((entry, key) => {\n if (now - entry.timestamp > entry.ttl) {\n keysToDelete.push(key);\n }\n });\n\n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n}\n\n// Global cache instance\nexport const cache = new ExGuardCache();\n","/**\n * Realtime event handling for cache invalidation\n */\n\nexport interface RealtimeEvent {\n type: 'rbac_update' | 'user_update' | 'role_update' | 'permission_update';\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private websocket: WebSocket | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000;\n\n /**\n * Connect to realtime server\n * @param url - WebSocket URL\n * @param token - Optional authentication token\n */\n connect(url: string, token?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n const wsUrl = token ? `${url}?token=${token}` : url;\n this.websocket = new WebSocket(wsUrl);\n\n const timeout = setTimeout(() => {\n reject(new Error('Connection timeout'));\n }, 10000);\n\n this.websocket.onopen = () => {\n clearTimeout(timeout);\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected to realtime server');\n resolve();\n };\n\n this.websocket.onmessage = (event) => {\n try {\n const realtimeEvent: RealtimeEvent = JSON.parse(event.data);\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to parse event:', error);\n }\n };\n\n this.websocket.onclose = () => {\n clearTimeout(timeout);\n console.log('[ExGuardRealtime] Disconnected from realtime server');\n this.handleReconnect(url, token);\n };\n\n this.websocket.onerror = (error) => {\n clearTimeout(timeout);\n console.error('[ExGuardRealtime] WebSocket error:', error);\n reject(error);\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n if (this.websocket) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribe(eventType: string, handler: RealtimeEventHandler): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n \n this.handlers.get(eventType)!.add(handler);\n \n // Return unsubscribe function\n return () => {\n const handlers = this.handlers.get(eventType);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n this.handlers.delete(eventType);\n }\n }\n };\n }\n\n /**\n * Handle incoming realtime events\n */\n private handleEvent(event: RealtimeEvent): void {\n console.log('[ExGuardRealtime] Received event:', event);\n \n const handlers = this.handlers.get(event.type);\n if (handlers) {\n handlers.forEach(handler => {\n try {\n handler(event);\n } catch (error) {\n console.error('[ExGuardRealtime] Event handler error:', error);\n }\n });\n }\n }\n\n /**\n * Handle reconnection logic\n */\n private handleReconnect(url: string, token?: string): void {\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(url, token).catch(error => {\n console.error('[ExGuardRealtime] Reconnection failed:', error);\n });\n }, delay);\n } else {\n console.error('[ExGuardRealtime] Max reconnection attempts reached');\n }\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.websocket?.readyState === WebSocket.OPEN;\n }\n}\n\n// Global realtime instance\nexport const realtime = new ExGuardRealtime();\n","/**\n * Framework-agnostic guards for protecting backend endpoints\n */\n\nimport { ExGuardBackendEnhanced } from './exguard-backend-enhanced.js';\nimport { ExGuardEnhancedConfig, UserAccessResponse, GuardContext, GuardResult, GuardOptions } from './types.js';\n\n// Re-export types for use in other modules\nexport type { GuardContext, GuardResult, GuardOptions, UserAccessResponse };\n\n/**\n * Framework-agnostic guard class for endpoint protection\n */\nexport class ExGuardBackend {\n private exGuard: ExGuardBackendEnhanced;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.exGuard = new ExGuardBackendEnhanced(config);\n }\n\n /**\n * Check if user has specific permissions\n */\n async requirePermissions(\n context: GuardContext, \n permissions: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL permissions\n const results = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAll = permissions.every(permission => results[permission]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY permission (default)\n const hasPermission = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAny = Object.values(hasPermission).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required any of: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Permission check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has specific roles\n */\n async requireRoles(\n context: GuardContext, \n roles: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL roles\n const results = await this.exGuard.hasRoles(context.token, roles);\n const hasAll = roles.every(role => results[role]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient roles. Required: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY role (default)\n const hasRole = await this.exGuard.hasRoles(context.token, roles);\n const hasAny = Object.values(hasRole).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient roles. Required any of: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Role check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific modules\n */\n async requireModules(\n context: GuardContext, \n modules: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n const userModuleKeys = userAccess.modules.map(m => m.key);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL modules\n hasAccess = modules.every(module => userModuleKeys.includes(module));\n } else {\n // Require ANY module (default)\n hasAccess = modules.some(module => userModuleKeys.includes(module));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient module access. Required: ${modules.join(', ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Module check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific field offices\n */\n async requireFieldOffices(\n context: GuardContext, \n fieldOffices: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userFieldOffices = await this.exGuard.getUserFieldOffices(context.token);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL field offices\n hasAccess = fieldOffices.every(office => userFieldOffices.includes(office));\n } else {\n // Require ANY field office (default)\n hasAccess = fieldOffices.some(office => userFieldOffices.includes(office));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient field office access. Required: ${fieldOffices.join(', ')}`,\n statusCode: 403\n };\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Field office check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Flexible guard with multiple requirements\n */\n async require(context: GuardContext, options: GuardOptions): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n let passed = true;\n const failures: string[] = [];\n\n // Check permissions\n if (options.permissions && options.permissions.length > 0) {\n const userPermissions = userAccess.modules.flatMap(m => m.permissions);\n const hasPermissions = options.requireAll\n ? options.permissions.every(p => userPermissions.includes(p))\n : options.permissions.some(p => userPermissions.includes(p));\n \n if (!hasPermissions) {\n passed = false;\n failures.push(`permissions: ${options.permissions.join(', ')}`);\n }\n }\n\n // Check roles\n if (options.roles && options.roles.length > 0) {\n const hasRoles = options.requireAll\n ? options.roles.every(r => userAccess.roles.includes(r))\n : options.roles.some(r => userAccess.roles.includes(r));\n \n if (!hasRoles) {\n passed = false;\n failures.push(`roles: ${options.roles.join(', ')}`);\n }\n }\n\n // Check modules\n if (options.modules && options.modules.length > 0) {\n const userModuleKeys = userAccess.modules.map(m => m.key);\n const hasModules = options.requireAll\n ? options.modules.every(m => userModuleKeys.includes(m))\n : options.modules.some(m => userModuleKeys.includes(m));\n \n if (!hasModules) {\n passed = false;\n failures.push(`modules: ${options.modules.join(', ')}`);\n }\n }\n\n // Check field offices\n if (options.fieldOffices && options.fieldOffices.length > 0) {\n const hasFieldOffices = options.requireAll\n ? options.fieldOffices.every(fo => userAccess.fieldOffices.includes(fo))\n : options.fieldOffices.some(fo => userAccess.fieldOffices.includes(fo));\n \n if (!hasFieldOffices) {\n passed = false;\n failures.push(`field offices: ${options.fieldOffices.join(', ')}`);\n }\n }\n\n if (!passed) {\n return {\n allowed: false,\n error: `Access denied. Missing: ${failures.join('; ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Access check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Simple authentication (just validates token)\n */\n async authenticate(context: GuardContext): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Authentication failed',\n statusCode: 401\n };\n }\n }\n\n /**\n * Get the underlying ExGuardBackendEnhanced instance\n */\n getExGuard(): ExGuardBackendEnhanced {\n return this.exGuard;\n }\n}\n\n/**\n * Helper function to extract token from various request types\n */\nexport function extractToken(request: any): string | null {\n // Express-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Fastify-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Custom header\n if (request.headers?.['x-access-token']) {\n return request.headers['x-access-token'];\n }\n\n // Query parameter\n if (request.query?.token) {\n return request.query.token;\n }\n\n return null;\n}\n\n/**\n * Create a guard context from a request\n */\nexport function createGuardContext(request: any): GuardContext | null {\n const token = extractToken(request);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request\n };\n}\n","/**\n * Express.js middleware for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when express is not installed\ntype Request = any;\ntype Response = any;\ntype NextFunction = any;\n\nexport interface AuthenticatedRequest extends Request {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Express middleware factory\n */\nexport function createExGuardExpress(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Simple authentication middleware\n */\n authenticate() {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 401).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: Request): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n","/**\n * Fastify plugin for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when fastify is not installed\ntype FastifyRequest = any;\ntype FastifyReply = any;\n\nexport interface AuthenticatedRequest extends FastifyRequest {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Fastify plugin factory\n */\nexport function createExGuardFastify(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Simple authentication hook\n */\n authenticate() {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 401).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: FastifyRequest): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAo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AAO,MAAM,OAAO,GAAG,EAAE,KAAK;AAAA,YAC5B,SAAS;AAAA,YACT,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAEA,cAAM,SAAS,MAAM,MAAM,aAAa,OAAO;AAE/C,YAAI,CAAC,OAAO,SAAS;AACnB,iBAAO,MAAM,OAAO,OAAO,cAAc,GAAG,EAAE,KAAK;AAAA,YACjD,SAAS;AAAA,YACT,SAAS,OAAO;AAAA,UAClB,CAAC;AAAA,QACH;AAGA,YAAI,OAAO,MAAM;AACf,cAAI,OAAO;AAAA,YACT,IAAI,OAAO,KAAK,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK,KAAK;AAAA,YAC/B,UAAU,OAAO,KAAK,KAAK;AAAA,YAC3B,OAAO,OAAO,KAAK,KAAK;AAAA,YACxB,OAAO,OAAO,KAAK;AAAA,YACnB,aAAa,OAAO,KAAK,QAAQ,QAAQ,OAAK,EAAE,WAAW;AAAA,YAC3D,SAAS,OAAO,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK;AAAA,UAC5B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,WAA2B;AACzB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,SAASA,oBAAmB,KAA0C;AACpE,QAAM,QAAQ,aAAa,GAAG;AAC9B,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":["ExGuardBackend","axios","module","import_axios","axios","userAccess","module","ExGuardBackend","module","ExGuardBackend","ExGuardBackend","createGuardContext"]}
package/dist/index.d.cts CHANGED
@@ -263,8 +263,10 @@ declare class ExGuardRealtime {
263
263
  private reconnectDelay;
264
264
  /**
265
265
  * Connect to realtime server
266
+ * @param url - WebSocket URL
267
+ * @param token - Optional authentication token
266
268
  */
267
- connect(url: string, token: string): Promise<void>;
269
+ connect(url: string, token?: string): Promise<void>;
268
270
  /**
269
271
  * Disconnect from realtime server
270
272
  */
package/dist/index.d.ts CHANGED
@@ -263,8 +263,10 @@ declare class ExGuardRealtime {
263
263
  private reconnectDelay;
264
264
  /**
265
265
  * Connect to realtime server
266
+ * @param url - WebSocket URL
267
+ * @param token - Optional authentication token
266
268
  */
267
- connect(url: string, token: string): Promise<void>;
269
+ connect(url: string, token?: string): Promise<void>;
268
270
  /**
269
271
  * Disconnect from realtime server
270
272
  */
package/dist/index.js CHANGED
@@ -246,11 +246,14 @@ var ExGuardRealtime = class {
246
246
  reconnectDelay = 1e3;
247
247
  /**
248
248
  * Connect to realtime server
249
+ * @param url - WebSocket URL
250
+ * @param token - Optional authentication token
249
251
  */
250
252
  connect(url, token) {
251
253
  return new Promise((resolve, reject) => {
252
254
  try {
253
- this.websocket = new WebSocket(`${url}?token=${token}`);
255
+ const wsUrl = token ? `${url}?token=${token}` : url;
256
+ this.websocket = new WebSocket(wsUrl);
254
257
  const timeout = setTimeout(() => {
255
258
  reject(new Error("Connection timeout"));
256
259
  }, 1e4);
@@ -381,7 +384,7 @@ var ExGuardBackendEnhanced = class {
381
384
  "Content-Type": "application/json"
382
385
  }
383
386
  });
384
- if (this.config.realtime?.enabled && this.config.realtime.url && this.config.realtime.token) {
387
+ if (this.config.realtime?.enabled && this.config.realtime.url) {
385
388
  this.setupRealtime();
386
389
  }
387
390
  setInterval(() => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/exguard-backend.ts","../src/exguard-backend-enhanced.ts","../src/cache.ts","../src/realtime.ts","../src/guards.ts","../src/express.ts","../src/fastify.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\n\nexport class ExGuardBackend {\n private client: AxiosInstance;\n private config: ExGuardConfig;\n\n constructor(config: ExGuardConfig) {\n this.config = {\n timeout: 10000,\n ...config,\n };\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Get user roles and permissions from the /guard/me endpoint\n * @param token - JWT access token\n * @returns Promise<UserAccessResponse>\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission\n * @param token - JWT access token\n * @param permission - Permission to check (e.g., 'events:create')\n * @returns Promise<boolean>\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Check if user has specific role\n * @param token - JWT access token\n * @param role - Role to check (e.g., 'Event Manager')\n * @returns Promise<boolean>\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Get all permissions for a specific module\n * @param token - JWT access token\n * @param moduleKey - Module key (e.g., 'events')\n * @returns Promise<string[]>\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user roles\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserRoles(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user field offices\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n } catch (error) {\n return [];\n }\n }\n}\n","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\nimport { cache, ExGuardCache } from './cache.js';\nimport { realtime, RealtimeEvent, ExGuardRealtime } from './realtime.js';\n\nexport interface ExGuardEnhancedConfig extends ExGuardConfig {\n cache?: {\n ttl?: number;\n enabled?: boolean;\n };\n realtime?: {\n enabled?: boolean;\n url?: string;\n token?: string;\n };\n}\n\nexport class ExGuardBackendEnhanced {\n private client: AxiosInstance;\n private config: ExGuardEnhancedConfig;\n private cache: ExGuardCache;\n private realtime: ExGuardRealtime;\n private userId: string | null = null;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000, // 5 minutes\n },\n realtime: {\n enabled: false,\n },\n ...config,\n };\n\n this.cache = cache;\n this.realtime = realtime;\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Setup realtime if enabled\n if (this.config.realtime?.enabled && this.config.realtime.url && this.config.realtime.token) {\n this.setupRealtime();\n }\n\n // Setup periodic cache cleanup\n setInterval(() => {\n this.cache.cleanup();\n }, 60000); // Every minute\n }\n\n /**\n * Setup realtime connection and event handlers\n */\n private async setupRealtime(): Promise<void> {\n try {\n await this.realtime.connect(this.config.realtime!.url!, this.config.realtime!.token!);\n \n // Subscribe to RBAC updates\n this.realtime.subscribe('rbac_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] RBAC update received:', event);\n \n // Clear cache for affected user\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n // Clear all cache if no specific user\n this.cache.clear();\n }\n });\n\n // Subscribe to user updates\n this.realtime.subscribe('user_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] User update received:', event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n }\n });\n\n } catch (error) {\n console.error('[ExGuardBackend] Failed to setup realtime:', error);\n }\n }\n\n /**\n * Extract user ID from JWT token\n */\n private extractUserIdFromToken(token: string): string | null {\n try {\n const payload = JSON.parse(atob(token.split('.')[1]));\n return payload.sub || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Get cache key for user data\n */\n private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\n\n /**\n * Get user roles and permissions from cache or API\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n if (!this.config.cache?.enabled) {\n return this.fetchUserAccess(token);\n }\n\n const cacheKey = this.getCacheKey(token, 'access');\n const cached = this.cache.get<UserAccessResponse>(cacheKey);\n \n if (cached) {\n console.log('[ExGuardBackend] Cache hit for user access');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user access');\n const data = await this.fetchUserAccess(token);\n \n // Cache the result\n this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\n\n /**\n * Fetch user access from API (always hits the server)\n */\n private async fetchUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission (cached)\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n }\n\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for permission: ${permission}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking permission: ${permission}`);\n const userAccess = await this.getUserAccess(token);\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n \n // Cache the result with shorter TTL for permissions\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\n\n /**\n * Check if user has specific role (cached)\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n }\n\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for role: ${role}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking role: ${role}`);\n const userAccess = await this.getUserAccess(token);\n const hasRole = userAccess.roles.includes(role);\n \n // Cache the result with shorter TTL for roles\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\n\n /**\n * Get all permissions for a specific module (cached)\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n }\n\n const cacheKey = this.getCacheKey(token, `module:${moduleKey}`);\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for module: ${moduleKey}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, fetching module permissions: ${moduleKey}`);\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n const permissions = module?.permissions || [];\n \n // Cache the result\n this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\n\n /**\n * Get user roles (cached)\n */\n async getUserRoles(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n }\n\n const cacheKey = this.getCacheKey(token, 'roles');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for user roles');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user roles');\n const userAccess = await this.getUserAccess(token);\n const roles = userAccess.roles;\n \n // Cache the result\n this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\n\n /**\n * Get user field offices (cached)\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n }\n\n const cacheKey = this.getCacheKey(token, 'field-offices');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for field offices');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching field offices');\n const userAccess = await this.getUserAccess(token);\n const fieldOffices = userAccess.fieldOffices;\n \n // Cache the result\n this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n /**\n * Batch check multiple permissions (optimized)\n */\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all permissions\n const uncachedPermissions: string[] = [];\n \n for (const permission of permissions) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[permission] = cached;\n } else {\n uncachedPermissions.push(permission);\n }\n } else {\n uncachedPermissions.push(permission);\n }\n }\n\n // Fetch user access once for all uncached permissions\n if (uncachedPermissions.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const permission of uncachedPermissions) {\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n results[permission] = hasPermission;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Batch check multiple roles (optimized)\n */\n async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all roles\n const uncachedRoles: string[] = [];\n \n for (const role of roles) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[role] = cached;\n } else {\n uncachedRoles.push(role);\n }\n } else {\n uncachedRoles.push(role);\n }\n }\n\n // Fetch user access once for all uncached roles\n if (uncachedRoles.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const role of uncachedRoles) {\n const hasRole = userAccess.roles.includes(role);\n results[role] = hasRole;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(token: string): void {\n const userId = this.extractUserIdFromToken(token);\n if (userId) {\n this.cache.clearUserCache(userId);\n console.log(`[ExGuardBackend] Cache cleared for user: ${userId}`);\n }\n }\n\n /**\n * Get cache statistics\n */\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.realtime.disconnect();\n }\n}\n","/**\n * In-memory cache for user access data with TTL support\n */\n\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n ttl: number;\n}\n\nexport class ExGuardCache {\n private cache = new Map<string, CacheEntry<any>>();\n private subscribers = new Map<string, Set<() => void>>();\n private defaultTTL = 300000; // 5 minutes\n\n /**\n * Get cached data\n */\n get<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n\n // Check if expired\n if (Date.now() - entry.timestamp > entry.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data;\n }\n\n /**\n * Set cached data with TTL\n */\n set<T>(key: string, data: T, ttl?: number): void {\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n ttl: ttl || this.defaultTTL,\n });\n }\n\n /**\n * Delete cached data\n */\n delete(key: string): boolean {\n const deleted = this.cache.delete(key);\n if (deleted) {\n this.notifySubscribers(key);\n }\n return deleted;\n }\n\n /**\n * Clear all cache\n */\n clear(): void {\n const keys = Array.from(this.cache.keys());\n this.cache.clear();\n keys.forEach(key => this.notifySubscribers(key));\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(userId: string): void {\n const keysToDelete = Array.from(this.cache.keys()).filter(key => \n key.startsWith(`user:${userId}:`)\n );\n \n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n\n /**\n * Subscribe to cache changes\n */\n subscribe(key: string, callback: () => void): () => void {\n if (!this.subscribers.has(key)) {\n this.subscribers.set(key, new Set());\n }\n \n this.subscribers.get(key)!.add(callback);\n \n // Return unsubscribe function\n return () => {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscribers.delete(key);\n }\n }\n };\n }\n\n /**\n * Notify subscribers of cache changes\n */\n private notifySubscribers(key: string): void {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.forEach(callback => {\n try {\n callback();\n } catch (error) {\n console.error('Cache subscriber error:', error);\n }\n });\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats(): { size: number; keys: string[] } {\n return {\n size: this.cache.size,\n keys: Array.from(this.cache.keys()),\n };\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n const keysToDelete: string[] = [];\n\n this.cache.forEach((entry, key) => {\n if (now - entry.timestamp > entry.ttl) {\n keysToDelete.push(key);\n }\n });\n\n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n}\n\n// Global cache instance\nexport const cache = new ExGuardCache();\n","/**\n * Realtime event handling for cache invalidation\n */\n\nexport interface RealtimeEvent {\n type: 'rbac_update' | 'user_update' | 'role_update' | 'permission_update';\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private websocket: WebSocket | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000;\n\n /**\n * Connect to realtime server\n */\n connect(url: string, token: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.websocket = new WebSocket(`${url}?token=${token}`);\n\n const timeout = setTimeout(() => {\n reject(new Error('Connection timeout'));\n }, 10000);\n\n this.websocket.onopen = () => {\n clearTimeout(timeout);\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected to realtime server');\n resolve();\n };\n\n this.websocket.onmessage = (event) => {\n try {\n const realtimeEvent: RealtimeEvent = JSON.parse(event.data);\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to parse event:', error);\n }\n };\n\n this.websocket.onclose = () => {\n clearTimeout(timeout);\n console.log('[ExGuardRealtime] Disconnected from realtime server');\n this.handleReconnect(url, token);\n };\n\n this.websocket.onerror = (error) => {\n clearTimeout(timeout);\n console.error('[ExGuardRealtime] WebSocket error:', error);\n reject(error);\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n if (this.websocket) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribe(eventType: string, handler: RealtimeEventHandler): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n \n this.handlers.get(eventType)!.add(handler);\n \n // Return unsubscribe function\n return () => {\n const handlers = this.handlers.get(eventType);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n this.handlers.delete(eventType);\n }\n }\n };\n }\n\n /**\n * Handle incoming realtime events\n */\n private handleEvent(event: RealtimeEvent): void {\n console.log('[ExGuardRealtime] Received event:', event);\n \n const handlers = this.handlers.get(event.type);\n if (handlers) {\n handlers.forEach(handler => {\n try {\n handler(event);\n } catch (error) {\n console.error('[ExGuardRealtime] Event handler error:', error);\n }\n });\n }\n }\n\n /**\n * Handle reconnection logic\n */\n private handleReconnect(url: string, token: string): void {\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(url, token).catch(error => {\n console.error('[ExGuardRealtime] Reconnection failed:', error);\n });\n }, delay);\n } else {\n console.error('[ExGuardRealtime] Max reconnection attempts reached');\n }\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.websocket?.readyState === WebSocket.OPEN;\n }\n}\n\n// Global realtime instance\nexport const realtime = new ExGuardRealtime();\n","/**\n * Framework-agnostic guards for protecting backend endpoints\n */\n\nimport { ExGuardBackendEnhanced } from './exguard-backend-enhanced.js';\nimport { ExGuardEnhancedConfig, UserAccessResponse, GuardContext, GuardResult, GuardOptions } from './types.js';\n\n// Re-export types for use in other modules\nexport type { GuardContext, GuardResult, GuardOptions, UserAccessResponse };\n\n/**\n * Framework-agnostic guard class for endpoint protection\n */\nexport class ExGuardBackend {\n private exGuard: ExGuardBackendEnhanced;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.exGuard = new ExGuardBackendEnhanced(config);\n }\n\n /**\n * Check if user has specific permissions\n */\n async requirePermissions(\n context: GuardContext, \n permissions: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL permissions\n const results = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAll = permissions.every(permission => results[permission]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY permission (default)\n const hasPermission = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAny = Object.values(hasPermission).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required any of: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Permission check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has specific roles\n */\n async requireRoles(\n context: GuardContext, \n roles: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL roles\n const results = await this.exGuard.hasRoles(context.token, roles);\n const hasAll = roles.every(role => results[role]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient roles. Required: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY role (default)\n const hasRole = await this.exGuard.hasRoles(context.token, roles);\n const hasAny = Object.values(hasRole).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient roles. Required any of: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Role check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific modules\n */\n async requireModules(\n context: GuardContext, \n modules: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n const userModuleKeys = userAccess.modules.map(m => m.key);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL modules\n hasAccess = modules.every(module => userModuleKeys.includes(module));\n } else {\n // Require ANY module (default)\n hasAccess = modules.some(module => userModuleKeys.includes(module));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient module access. Required: ${modules.join(', ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Module check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific field offices\n */\n async requireFieldOffices(\n context: GuardContext, \n fieldOffices: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userFieldOffices = await this.exGuard.getUserFieldOffices(context.token);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL field offices\n hasAccess = fieldOffices.every(office => userFieldOffices.includes(office));\n } else {\n // Require ANY field office (default)\n hasAccess = fieldOffices.some(office => userFieldOffices.includes(office));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient field office access. Required: ${fieldOffices.join(', ')}`,\n statusCode: 403\n };\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Field office check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Flexible guard with multiple requirements\n */\n async require(context: GuardContext, options: GuardOptions): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n let passed = true;\n const failures: string[] = [];\n\n // Check permissions\n if (options.permissions && options.permissions.length > 0) {\n const userPermissions = userAccess.modules.flatMap(m => m.permissions);\n const hasPermissions = options.requireAll\n ? options.permissions.every(p => userPermissions.includes(p))\n : options.permissions.some(p => userPermissions.includes(p));\n \n if (!hasPermissions) {\n passed = false;\n failures.push(`permissions: ${options.permissions.join(', ')}`);\n }\n }\n\n // Check roles\n if (options.roles && options.roles.length > 0) {\n const hasRoles = options.requireAll\n ? options.roles.every(r => userAccess.roles.includes(r))\n : options.roles.some(r => userAccess.roles.includes(r));\n \n if (!hasRoles) {\n passed = false;\n failures.push(`roles: ${options.roles.join(', ')}`);\n }\n }\n\n // Check modules\n if (options.modules && options.modules.length > 0) {\n const userModuleKeys = userAccess.modules.map(m => m.key);\n const hasModules = options.requireAll\n ? options.modules.every(m => userModuleKeys.includes(m))\n : options.modules.some(m => userModuleKeys.includes(m));\n \n if (!hasModules) {\n passed = false;\n failures.push(`modules: ${options.modules.join(', ')}`);\n }\n }\n\n // Check field offices\n if (options.fieldOffices && options.fieldOffices.length > 0) {\n const hasFieldOffices = options.requireAll\n ? options.fieldOffices.every(fo => userAccess.fieldOffices.includes(fo))\n : options.fieldOffices.some(fo => userAccess.fieldOffices.includes(fo));\n \n if (!hasFieldOffices) {\n passed = false;\n failures.push(`field offices: ${options.fieldOffices.join(', ')}`);\n }\n }\n\n if (!passed) {\n return {\n allowed: false,\n error: `Access denied. Missing: ${failures.join('; ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Access check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Simple authentication (just validates token)\n */\n async authenticate(context: GuardContext): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Authentication failed',\n statusCode: 401\n };\n }\n }\n\n /**\n * Get the underlying ExGuardBackendEnhanced instance\n */\n getExGuard(): ExGuardBackendEnhanced {\n return this.exGuard;\n }\n}\n\n/**\n * Helper function to extract token from various request types\n */\nexport function extractToken(request: any): string | null {\n // Express-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Fastify-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Custom header\n if (request.headers?.['x-access-token']) {\n return request.headers['x-access-token'];\n }\n\n // Query parameter\n if (request.query?.token) {\n return request.query.token;\n }\n\n return null;\n}\n\n/**\n * Create a guard context from a request\n */\nexport function createGuardContext(request: any): GuardContext | null {\n const token = extractToken(request);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request\n };\n}\n","/**\n * Express.js middleware for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when express is not installed\ntype Request = any;\ntype Response = any;\ntype NextFunction = any;\n\nexport interface AuthenticatedRequest extends Request {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Express middleware factory\n */\nexport function createExGuardExpress(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Simple authentication middleware\n */\n authenticate() {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 401).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: Request): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n","/**\n * Fastify plugin for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when fastify is not installed\ntype FastifyRequest = any;\ntype FastifyReply = any;\n\nexport interface AuthenticatedRequest extends FastifyRequest {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Fastify plugin factory\n */\nexport function createExGuardFastify(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Simple authentication hook\n */\n authenticate() {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 401).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: FastifyRequest): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n"],"mappings":";AAAA,OAAO,WAA6C;AAO7C,IAAM,iBAAN,MAAqB;AAAA,EAClB;AAAA,EACA;AAAA,EAER,YAAY,QAAuB;AACjC,SAAK,SAAS;AAAA,MACZ,SAAS;AAAA,MACT,GAAG;AAAA,IACL;AAEA,SAAK,SAAS,MAAM,OAAO;AAAA,MACzB,SAAS,KAAK,OAAO;AAAA,MACrB,SAAS,KAAK,OAAO;AAAA,MACrB,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAc,OAA4C;AAC9D,QAAI;AACF,YAAM,WACJ,MAAM,KAAK,OAAO,IAAI,aAAa;AAAA,QACjC,SAAS;AAAA,UACP,iBAAiB,UAAU,KAAK;AAAA,QAClC;AA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AAO,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK;AAAA,UAC5B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,WAA2B;AACzB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,SAASA,oBAAmB,KAA0C;AACpE,QAAM,QAAQ,aAAa,GAAG;AAC9B,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":["axios","axios","userAccess","module","ExGuardBackend","ExGuardBackend","ExGuardBackend","createGuardContext"]}
1
+ {"version":3,"sources":["../src/exguard-backend.ts","../src/exguard-backend-enhanced.ts","../src/cache.ts","../src/realtime.ts","../src/guards.ts","../src/express.ts","../src/fastify.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\n\nexport class ExGuardBackend {\n private client: AxiosInstance;\n private config: ExGuardConfig;\n\n constructor(config: ExGuardConfig) {\n this.config = {\n timeout: 10000,\n ...config,\n };\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Get user roles and permissions from the /guard/me endpoint\n * @param token - JWT access token\n * @returns Promise<UserAccessResponse>\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission\n * @param token - JWT access token\n * @param permission - Permission to check (e.g., 'events:create')\n * @returns Promise<boolean>\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Check if user has specific role\n * @param token - JWT access token\n * @param role - Role to check (e.g., 'Event Manager')\n * @returns Promise<boolean>\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Get all permissions for a specific module\n * @param token - JWT access token\n * @param moduleKey - Module key (e.g., 'events')\n * @returns Promise<string[]>\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user roles\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserRoles(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Get user field offices\n * @param token - JWT access token\n * @returns Promise<string[]>\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n try {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n } catch (error) {\n return [];\n }\n }\n}\n","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport { \n UserAccessResponse, \n ApiResponse, \n ExGuardConfig \n} from './types.js';\nimport { cache, ExGuardCache } from './cache.js';\nimport { realtime, RealtimeEvent, ExGuardRealtime } from './realtime.js';\n\nexport interface ExGuardEnhancedConfig extends ExGuardConfig {\n cache?: {\n ttl?: number;\n enabled?: boolean;\n };\n realtime?: {\n enabled?: boolean;\n url?: string;\n token?: string;\n };\n}\n\nexport class ExGuardBackendEnhanced {\n private client: AxiosInstance;\n private config: ExGuardEnhancedConfig;\n private cache: ExGuardCache;\n private realtime: ExGuardRealtime;\n private userId: string | null = null;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000, // 5 minutes\n },\n realtime: {\n enabled: false,\n },\n ...config,\n };\n\n this.cache = cache;\n this.realtime = realtime;\n\n this.client = axios.create({\n baseURL: this.config.apiUrl,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Setup realtime if enabled\n if (this.config.realtime?.enabled && this.config.realtime.url) {\n this.setupRealtime();\n }\n\n // Setup periodic cache cleanup\n setInterval(() => {\n this.cache.cleanup();\n }, 60000); // Every minute\n }\n\n /**\n * Setup realtime connection and event handlers\n */\n private async setupRealtime(): Promise<void> {\n try {\n await this.realtime.connect(this.config.realtime!.url!, this.config.realtime!.token!);\n \n // Subscribe to RBAC updates\n this.realtime.subscribe('rbac_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] RBAC update received:', event);\n \n // Clear cache for affected user\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n // Clear all cache if no specific user\n this.cache.clear();\n }\n });\n\n // Subscribe to user updates\n this.realtime.subscribe('user_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] User update received:', event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n }\n });\n\n } catch (error) {\n console.error('[ExGuardBackend] Failed to setup realtime:', error);\n }\n }\n\n /**\n * Extract user ID from JWT token\n */\n private extractUserIdFromToken(token: string): string | null {\n try {\n const payload = JSON.parse(atob(token.split('.')[1]));\n return payload.sub || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Get cache key for user data\n */\n private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\n\n /**\n * Get user roles and permissions from cache or API\n */\n async getUserAccess(token: string): Promise<UserAccessResponse> {\n if (!this.config.cache?.enabled) {\n return this.fetchUserAccess(token);\n }\n\n const cacheKey = this.getCacheKey(token, 'access');\n const cached = this.cache.get<UserAccessResponse>(cacheKey);\n \n if (cached) {\n console.log('[ExGuardBackend] Cache hit for user access');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user access');\n const data = await this.fetchUserAccess(token);\n \n // Cache the result\n this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\n\n /**\n * Fetch user access from API (always hits the server)\n */\n private async fetchUserAccess(token: string): Promise<UserAccessResponse> {\n try {\n const response: AxiosResponse<ApiResponse<UserAccessResponse>> = \n await this.client.get('/guard/me', {\n headers: {\n 'Authorization': `Bearer ${token}`,\n },\n });\n\n if (!response.data.success) {\n throw new Error('Failed to fetch user access information');\n }\n\n return response.data.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n throw new Error('Unauthorized: Invalid or expired token');\n }\n throw new Error(`API Error: ${error.response?.data?.message || error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if user has specific permission (cached)\n */\n async hasPermission(token: string, permission: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n }\n\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for permission: ${permission}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking permission: ${permission}`);\n const userAccess = await this.getUserAccess(token);\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n \n // Cache the result with shorter TTL for permissions\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\n\n /**\n * Check if user has specific role (cached)\n */\n async hasRole(token: string, role: string): Promise<boolean> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles.includes(role);\n }\n\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for role: ${role}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, checking role: ${role}`);\n const userAccess = await this.getUserAccess(token);\n const hasRole = userAccess.roles.includes(role);\n \n // Cache the result with shorter TTL for roles\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\n\n /**\n * Get all permissions for a specific module (cached)\n */\n async getModulePermissions(token: string, moduleKey: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n return module?.permissions || [];\n }\n\n const cacheKey = this.getCacheKey(token, `module:${moduleKey}`);\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log(`[ExGuardBackend] Cache hit for module: ${moduleKey}`);\n return cached;\n }\n\n console.log(`[ExGuardBackend] Cache miss, fetching module permissions: ${moduleKey}`);\n const userAccess = await this.getUserAccess(token);\n const module = userAccess.modules.find(m => m.key === moduleKey);\n const permissions = module?.permissions || [];\n \n // Cache the result\n this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\n\n /**\n * Get user roles (cached)\n */\n async getUserRoles(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.roles;\n }\n\n const cacheKey = this.getCacheKey(token, 'roles');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for user roles');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching user roles');\n const userAccess = await this.getUserAccess(token);\n const roles = userAccess.roles;\n \n // Cache the result\n this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\n\n /**\n * Get user field offices (cached)\n */\n async getUserFieldOffices(token: string): Promise<string[]> {\n if (!this.config.cache?.enabled) {\n const userAccess = await this.getUserAccess(token);\n return userAccess.fieldOffices;\n }\n\n const cacheKey = this.getCacheKey(token, 'field-offices');\n const cached = this.cache.get<string[]>(cacheKey);\n \n if (cached !== null) {\n console.log('[ExGuardBackend] Cache hit for field offices');\n return cached;\n }\n\n console.log('[ExGuardBackend] Cache miss, fetching field offices');\n const userAccess = await this.getUserAccess(token);\n const fieldOffices = userAccess.fieldOffices;\n \n // Cache the result\n this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n /**\n * Batch check multiple permissions (optimized)\n */\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all permissions\n const uncachedPermissions: string[] = [];\n \n for (const permission of permissions) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[permission] = cached;\n } else {\n uncachedPermissions.push(permission);\n }\n } else {\n uncachedPermissions.push(permission);\n }\n }\n\n // Fetch user access once for all uncached permissions\n if (uncachedPermissions.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const permission of uncachedPermissions) {\n const hasPermission = userAccess.modules.some(module => \n module.permissions.includes(permission)\n );\n results[permission] = hasPermission;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `permission:${permission}`);\n this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Batch check multiple roles (optimized)\n */\n async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n \n // Check cache first for all roles\n const uncachedRoles: string[] = [];\n \n for (const role of roles) {\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n const cached = this.cache.get<boolean>(cacheKey);\n \n if (cached !== null) {\n results[role] = cached;\n } else {\n uncachedRoles.push(role);\n }\n } else {\n uncachedRoles.push(role);\n }\n }\n\n // Fetch user access once for all uncached roles\n if (uncachedRoles.length > 0) {\n const userAccess = await this.getUserAccess(token);\n \n for (const role of uncachedRoles) {\n const hasRole = userAccess.roles.includes(role);\n results[role] = hasRole;\n \n // Cache the result\n if (this.config.cache?.enabled) {\n const cacheKey = this.getCacheKey(token, `role:${role}`);\n this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n }\n }\n }\n\n return results;\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(token: string): void {\n const userId = this.extractUserIdFromToken(token);\n if (userId) {\n this.cache.clearUserCache(userId);\n console.log(`[ExGuardBackend] Cache cleared for user: ${userId}`);\n }\n }\n\n /**\n * Get cache statistics\n */\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.realtime.disconnect();\n }\n}\n","/**\n * In-memory cache for user access data with TTL support\n */\n\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n ttl: number;\n}\n\nexport class ExGuardCache {\n private cache = new Map<string, CacheEntry<any>>();\n private subscribers = new Map<string, Set<() => void>>();\n private defaultTTL = 300000; // 5 minutes\n\n /**\n * Get cached data\n */\n get<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n\n // Check if expired\n if (Date.now() - entry.timestamp > entry.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data;\n }\n\n /**\n * Set cached data with TTL\n */\n set<T>(key: string, data: T, ttl?: number): void {\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n ttl: ttl || this.defaultTTL,\n });\n }\n\n /**\n * Delete cached data\n */\n delete(key: string): boolean {\n const deleted = this.cache.delete(key);\n if (deleted) {\n this.notifySubscribers(key);\n }\n return deleted;\n }\n\n /**\n * Clear all cache\n */\n clear(): void {\n const keys = Array.from(this.cache.keys());\n this.cache.clear();\n keys.forEach(key => this.notifySubscribers(key));\n }\n\n /**\n * Clear cache for a specific user\n */\n clearUserCache(userId: string): void {\n const keysToDelete = Array.from(this.cache.keys()).filter(key => \n key.startsWith(`user:${userId}:`)\n );\n \n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n\n /**\n * Subscribe to cache changes\n */\n subscribe(key: string, callback: () => void): () => void {\n if (!this.subscribers.has(key)) {\n this.subscribers.set(key, new Set());\n }\n \n this.subscribers.get(key)!.add(callback);\n \n // Return unsubscribe function\n return () => {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscribers.delete(key);\n }\n }\n };\n }\n\n /**\n * Notify subscribers of cache changes\n */\n private notifySubscribers(key: string): void {\n const callbacks = this.subscribers.get(key);\n if (callbacks) {\n callbacks.forEach(callback => {\n try {\n callback();\n } catch (error) {\n console.error('Cache subscriber error:', error);\n }\n });\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats(): { size: number; keys: string[] } {\n return {\n size: this.cache.size,\n keys: Array.from(this.cache.keys()),\n };\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n const keysToDelete: string[] = [];\n\n this.cache.forEach((entry, key) => {\n if (now - entry.timestamp > entry.ttl) {\n keysToDelete.push(key);\n }\n });\n\n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n }\n}\n\n// Global cache instance\nexport const cache = new ExGuardCache();\n","/**\n * Realtime event handling for cache invalidation\n */\n\nexport interface RealtimeEvent {\n type: 'rbac_update' | 'user_update' | 'role_update' | 'permission_update';\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private websocket: WebSocket | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000;\n\n /**\n * Connect to realtime server\n * @param url - WebSocket URL\n * @param token - Optional authentication token\n */\n connect(url: string, token?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n const wsUrl = token ? `${url}?token=${token}` : url;\n this.websocket = new WebSocket(wsUrl);\n\n const timeout = setTimeout(() => {\n reject(new Error('Connection timeout'));\n }, 10000);\n\n this.websocket.onopen = () => {\n clearTimeout(timeout);\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected to realtime server');\n resolve();\n };\n\n this.websocket.onmessage = (event) => {\n try {\n const realtimeEvent: RealtimeEvent = JSON.parse(event.data);\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to parse event:', error);\n }\n };\n\n this.websocket.onclose = () => {\n clearTimeout(timeout);\n console.log('[ExGuardRealtime] Disconnected from realtime server');\n this.handleReconnect(url, token);\n };\n\n this.websocket.onerror = (error) => {\n clearTimeout(timeout);\n console.error('[ExGuardRealtime] WebSocket error:', error);\n reject(error);\n };\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n if (this.websocket) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribe(eventType: string, handler: RealtimeEventHandler): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n \n this.handlers.get(eventType)!.add(handler);\n \n // Return unsubscribe function\n return () => {\n const handlers = this.handlers.get(eventType);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n this.handlers.delete(eventType);\n }\n }\n };\n }\n\n /**\n * Handle incoming realtime events\n */\n private handleEvent(event: RealtimeEvent): void {\n console.log('[ExGuardRealtime] Received event:', event);\n \n const handlers = this.handlers.get(event.type);\n if (handlers) {\n handlers.forEach(handler => {\n try {\n handler(event);\n } catch (error) {\n console.error('[ExGuardRealtime] Event handler error:', error);\n }\n });\n }\n }\n\n /**\n * Handle reconnection logic\n */\n private handleReconnect(url: string, token?: string): void {\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(url, token).catch(error => {\n console.error('[ExGuardRealtime] Reconnection failed:', error);\n });\n }, delay);\n } else {\n console.error('[ExGuardRealtime] Max reconnection attempts reached');\n }\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.websocket?.readyState === WebSocket.OPEN;\n }\n}\n\n// Global realtime instance\nexport const realtime = new ExGuardRealtime();\n","/**\n * Framework-agnostic guards for protecting backend endpoints\n */\n\nimport { ExGuardBackendEnhanced } from './exguard-backend-enhanced.js';\nimport { ExGuardEnhancedConfig, UserAccessResponse, GuardContext, GuardResult, GuardOptions } from './types.js';\n\n// Re-export types for use in other modules\nexport type { GuardContext, GuardResult, GuardOptions, UserAccessResponse };\n\n/**\n * Framework-agnostic guard class for endpoint protection\n */\nexport class ExGuardBackend {\n private exGuard: ExGuardBackendEnhanced;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.exGuard = new ExGuardBackendEnhanced(config);\n }\n\n /**\n * Check if user has specific permissions\n */\n async requirePermissions(\n context: GuardContext, \n permissions: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL permissions\n const results = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAll = permissions.every(permission => results[permission]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY permission (default)\n const hasPermission = await this.exGuard.hasPermissions(context.token, permissions);\n const hasAny = Object.values(hasPermission).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient permissions. Required any of: ${permissions.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Permission check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has specific roles\n */\n async requireRoles(\n context: GuardContext, \n roles: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n if (options.requireAll) {\n // Require ALL roles\n const results = await this.exGuard.hasRoles(context.token, roles);\n const hasAll = roles.every(role => results[role]);\n \n if (!hasAll) {\n return {\n allowed: false,\n error: `Insufficient roles. Required: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n } else {\n // Require ANY role (default)\n const hasRole = await this.exGuard.hasRoles(context.token, roles);\n const hasAny = Object.values(hasRole).some(Boolean);\n \n if (!hasAny) {\n return {\n allowed: false,\n error: `Insufficient roles. Required any of: ${roles.join(', ')}`,\n statusCode: 403\n };\n }\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Role check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific modules\n */\n async requireModules(\n context: GuardContext, \n modules: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n const userModuleKeys = userAccess.modules.map(m => m.key);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL modules\n hasAccess = modules.every(module => userModuleKeys.includes(module));\n } else {\n // Require ANY module (default)\n hasAccess = modules.some(module => userModuleKeys.includes(module));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient module access. Required: ${modules.join(', ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Module check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Check if user has access to specific field offices\n */\n async requireFieldOffices(\n context: GuardContext, \n fieldOffices: string[], \n options: { requireAll?: boolean } = {}\n ): Promise<GuardResult> {\n try {\n const userFieldOffices = await this.exGuard.getUserFieldOffices(context.token);\n\n let hasAccess: boolean;\n\n if (options.requireAll) {\n // Require ALL field offices\n hasAccess = fieldOffices.every(office => userFieldOffices.includes(office));\n } else {\n // Require ANY field office (default)\n hasAccess = fieldOffices.some(office => userFieldOffices.includes(office));\n }\n\n if (!hasAccess) {\n return {\n allowed: false,\n error: `Insufficient field office access. Required: ${fieldOffices.join(', ')}`,\n statusCode: 403\n };\n }\n\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Field office check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Flexible guard with multiple requirements\n */\n async require(context: GuardContext, options: GuardOptions): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n let passed = true;\n const failures: string[] = [];\n\n // Check permissions\n if (options.permissions && options.permissions.length > 0) {\n const userPermissions = userAccess.modules.flatMap(m => m.permissions);\n const hasPermissions = options.requireAll\n ? options.permissions.every(p => userPermissions.includes(p))\n : options.permissions.some(p => userPermissions.includes(p));\n \n if (!hasPermissions) {\n passed = false;\n failures.push(`permissions: ${options.permissions.join(', ')}`);\n }\n }\n\n // Check roles\n if (options.roles && options.roles.length > 0) {\n const hasRoles = options.requireAll\n ? options.roles.every(r => userAccess.roles.includes(r))\n : options.roles.some(r => userAccess.roles.includes(r));\n \n if (!hasRoles) {\n passed = false;\n failures.push(`roles: ${options.roles.join(', ')}`);\n }\n }\n\n // Check modules\n if (options.modules && options.modules.length > 0) {\n const userModuleKeys = userAccess.modules.map(m => m.key);\n const hasModules = options.requireAll\n ? options.modules.every(m => userModuleKeys.includes(m))\n : options.modules.some(m => userModuleKeys.includes(m));\n \n if (!hasModules) {\n passed = false;\n failures.push(`modules: ${options.modules.join(', ')}`);\n }\n }\n\n // Check field offices\n if (options.fieldOffices && options.fieldOffices.length > 0) {\n const hasFieldOffices = options.requireAll\n ? options.fieldOffices.every(fo => userAccess.fieldOffices.includes(fo))\n : options.fieldOffices.some(fo => userAccess.fieldOffices.includes(fo));\n \n if (!hasFieldOffices) {\n passed = false;\n failures.push(`field offices: ${options.fieldOffices.join(', ')}`);\n }\n }\n\n if (!passed) {\n return {\n allowed: false,\n error: `Access denied. Missing: ${failures.join('; ')}`,\n statusCode: 403\n };\n }\n\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Access check failed',\n statusCode: 500\n };\n }\n }\n\n /**\n * Simple authentication (just validates token)\n */\n async authenticate(context: GuardContext): Promise<GuardResult> {\n try {\n const userAccess = await this.exGuard.getUserAccess(context.token);\n return { allowed: true, user: userAccess };\n } catch (error) {\n return {\n allowed: false,\n error: 'Authentication failed',\n statusCode: 401\n };\n }\n }\n\n /**\n * Get the underlying ExGuardBackendEnhanced instance\n */\n getExGuard(): ExGuardBackendEnhanced {\n return this.exGuard;\n }\n}\n\n/**\n * Helper function to extract token from various request types\n */\nexport function extractToken(request: any): string | null {\n // Express-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Fastify-style\n if (request.headers?.authorization) {\n const authHeader = request.headers.authorization;\n if (authHeader.startsWith('Bearer ')) {\n return authHeader.substring(7);\n }\n }\n\n // Custom header\n if (request.headers?.['x-access-token']) {\n return request.headers['x-access-token'];\n }\n\n // Query parameter\n if (request.query?.token) {\n return request.query.token;\n }\n\n return null;\n}\n\n/**\n * Create a guard context from a request\n */\nexport function createGuardContext(request: any): GuardContext | null {\n const token = extractToken(request);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request\n };\n}\n","/**\n * Express.js middleware for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when express is not installed\ntype Request = any;\ntype Response = any;\ntype NextFunction = any;\n\nexport interface AuthenticatedRequest extends Request {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Express middleware factory\n */\nexport function createExGuardExpress(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 403).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Simple authentication middleware\n */\n authenticate() {\n return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {\n const context = createGuardContext(req);\n if (!context) {\n return res.status(401).json({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return res.status(result.statusCode || 401).json({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n\n next();\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: Request): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n","/**\n * Fastify plugin for ExGuard endpoint protection\n */\n\nimport { ExGuardBackend, GuardContext, GuardOptions, extractToken } from './guards.js';\n\n// Conditional types to avoid build errors when fastify is not installed\ntype FastifyRequest = any;\ntype FastifyReply = any;\n\nexport interface AuthenticatedRequest extends FastifyRequest {\n user?: {\n id: string;\n cognitoSubId: string;\n username: string;\n email: string;\n roles: string[];\n permissions: string[];\n modules: Array<{ key: string; permissions: string[] }>;\n fieldOffices: string[];\n };\n}\n\n/**\n * Fastify plugin factory\n */\nexport function createExGuardFastify(config: any) {\n const guard = new ExGuardBackend(config);\n\n return {\n /**\n * Require specific permissions\n */\n requirePermissions(permissions: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requirePermissions(context, permissions, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require specific roles\n */\n requireRoles(roles: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireRoles(context, roles, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require module access\n */\n requireModules(modules: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireModules(context, modules, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Require field office access\n */\n requireFieldOffices(fieldOffices: string[], options: { requireAll?: boolean } = {}) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.requireFieldOffices(context, fieldOffices, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Flexible guard with multiple requirements\n */\n require(options: GuardOptions) {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.require(context, options);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 403).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Simple authentication hook\n */\n authenticate() {\n return async (req: AuthenticatedRequest, reply: FastifyReply) => {\n const context = createGuardContext(req);\n if (!context) {\n return reply.status(401).send({\n success: false,\n message: 'No authentication token provided'\n });\n }\n\n const result = await guard.authenticate(context);\n \n if (!result.allowed) {\n return reply.status(result.statusCode || 401).send({\n success: false,\n message: result.error\n });\n }\n\n // Attach user data to request\n if (result.user) {\n req.user = {\n id: result.user.user.id,\n cognitoSubId: result.user.user.cognitoSubId,\n username: result.user.user.username,\n email: result.user.user.email,\n roles: result.user.roles,\n permissions: result.user.modules.flatMap(m => m.permissions),\n modules: result.user.modules,\n fieldOffices: result.user.fieldOffices,\n };\n }\n };\n },\n\n /**\n * Get the underlying guard instance\n */\n getGuard(): ExGuardBackend {\n return guard;\n }\n };\n}\n\nfunction createGuardContext(req: FastifyRequest): GuardContext | null {\n const token = extractToken(req);\n if (!token) {\n return null;\n }\n\n return {\n token,\n request: req\n };\n}\n"],"mappings":";AAAA,OAAO,WAA6C;AAO7C,IAAM,iBAAN,MAAqB;AAAA,EAClB;AAAA,EACA;AAAA,EAER,YAAY,QAAuB;AACjC,SAAK,SAAS;AAAA,MACZ,SAAS;AAAA,MACT,GAAG;AAAA,IACL;AAEA,SAAK,SAAS,MAAM,OAAO;AAAA,MACzB,SAAS,KAAK,OAAO;AAAA,MACrB,SAAS,KAAK,OAAO;AAAA,MACrB,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAc,OAA4C;AAC9D,QAAI;AACF,YAAM,WACJ,MAAM,KAAK,OAAO,IAAI,aAAa;AAAA,QACjC,SAAS;AAAA,UACP,iBAAiB,UAAU,KAAK;AAAA,QAClC;AAAA,MACF,CAAC;AAEH,UAAI,CAAC,SAAS,KAAK,SAAS;AAC1B,cAAM,IAAI,MAAM,yCAAyC;AAAA,MAC3D;AAEA,aAAO,SAAS,KAAK;AAAA,IACvB,SAAS,OAAO;AACd,UAAI,MAAM,aAAa,KAAK,GAAG;AAC7B,YAAI,MAAM,UAAU,WAAW,KAAK;AAClC,gBAAM,IAAI,MAAM,wCAAwC;AAAA,QAC1D;AACA,cAAM,IAAI,MAAM,cAAc,MAAM,UAAU,MAAM,WAAW,MAAM,OAAO,EAAE;AAAA,MAChF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,cAA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,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK;AAAA,UAC5B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,eAAe;AACb,aAAO,OAAO,KAA2B,UAAwB;AAC/D,cAAM,UAAUA,oBAAmB,GAAG;AACtC,YAAI,CAAC,SAAS;AACZ,iBAAO,MAAM,OAAO,GAAG,EAAE,KAAK;AAAA,YAC5B,SAAS;AAAA,YACT,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAEA,cAAM,SAAS,MAAM,MAAM,aAAa,OAAO;AAE/C,YAAI,CAAC,OAAO,SAAS;AACnB,iBAAO,MAAM,OAAO,OAAO,cAAc,GAAG,EAAE,KAAK;AAAA,YACjD,SAAS;AAAA,YACT,SAAS,OAAO;AAAA,UAClB,CAAC;AAAA,QACH;AAGA,YAAI,OAAO,MAAM;AACf,cAAI,OAAO;AAAA,YACT,IAAI,OAAO,KAAK,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK,KAAK;AAAA,YAC/B,UAAU,OAAO,KAAK,KAAK;AAAA,YAC3B,OAAO,OAAO,KAAK,KAAK;AAAA,YACxB,OAAO,OAAO,KAAK;AAAA,YACnB,aAAa,OAAO,KAAK,QAAQ,QAAQ,OAAK,EAAE,WAAW;AAAA,YAC3D,SAAS,OAAO,KAAK;AAAA,YACrB,cAAc,OAAO,KAAK;AAAA,UAC5B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,WAA2B;AACzB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,SAASA,oBAAmB,KAA0C;AACpE,QAAM,QAAQ,aAAa,GAAG;AAC9B,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":["axios","axios","userAccess","module","ExGuardBackend","ExGuardBackend","ExGuardBackend","createGuardContext"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "exguard-backend",
3
- "version": "1.0.22",
3
+ "version": "1.0.23",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -129,7 +129,7 @@ import { Guard } from 'exguard-backend';
129
129
  },
130
130
  timeout: parseInt(process.env.EXGUARD_TIMEOUT || '10000'), // 10 seconds
131
131
  realtime: {
132
- enabled: process.env.EXGUARD_REALTIME_ENABLED === 'true' && !!process.env.EXGUARD_REALTIME_URL && !!process.env.EXGUARD_SERVICE_TOKEN,
132
+ enabled: process.env.EXGUARD_REALTIME_ENABLED === 'true' && !!process.env.EXGUARD_REALTIME_URL,
133
133
  url: process.env.EXGUARD_REALTIME_URL || undefined,
134
134
  token: process.env.EXGUARD_SERVICE_TOKEN || undefined,
135
135
  },
@@ -644,10 +644,12 @@ EXGUARD_CACHE_ENABLED=true
644
644
  EXGUARD_CACHE_TTL=300000
645
645
 
646
646
  # Realtime Configuration (for automatic cache invalidation)
647
- # Set to true to enable WebSocket connection for real-time RBAC updates
647
+ # Enable realtime to automatically clear cache when permissions change
648
648
  EXGUARD_REALTIME_ENABLED=true
649
649
  EXGUARD_REALTIME_URL=ws://localhost:3000/realtime
650
- EXGUARD_SERVICE_TOKEN=your-service-jwt-token
650
+
651
+ # Optional: Service token for realtime authentication (if required by your server)
652
+ # EXGUARD_SERVICE_TOKEN=your-service-jwt-token
651
653
  `;
652
654
 
653
655
  const envPath = path.join(process.cwd(), '.env');