exguard-backend 1.0.34 → 1.0.35
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 +50 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +50 -35
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -210,16 +210,20 @@ var ExGuardCache = class {
|
|
|
210
210
|
keys.forEach((key) => this.notifySubscribers(key));
|
|
211
211
|
}
|
|
212
212
|
/**
|
|
213
|
-
* Clear cache for a specific user
|
|
213
|
+
* Clear cache for a specific user - clears ALL caches related to this user
|
|
214
214
|
*/
|
|
215
215
|
clearUserCache(userId) {
|
|
216
216
|
const keysToDelete = Array.from(this.cache.keys()).filter(
|
|
217
|
-
(key) => key.
|
|
217
|
+
(key) => key.includes(userId)
|
|
218
218
|
);
|
|
219
|
+
console.log(`[ExGuardCache] Clearing cache for user ${userId}, found ${keysToDelete.length} keys:`, keysToDelete);
|
|
219
220
|
keysToDelete.forEach((key) => {
|
|
220
221
|
this.cache.delete(key);
|
|
221
222
|
this.notifySubscribers(key);
|
|
222
223
|
});
|
|
224
|
+
if (keysToDelete.length === 0) {
|
|
225
|
+
console.log(`[ExGuardCache] No cache entries found for user ${userId}`);
|
|
226
|
+
}
|
|
223
227
|
}
|
|
224
228
|
/**
|
|
225
229
|
* Subscribe to cache changes
|
|
@@ -449,6 +453,7 @@ var ExGuardRealtime = class {
|
|
|
449
453
|
}
|
|
450
454
|
/**
|
|
451
455
|
* Subscribe to realtime events
|
|
456
|
+
* Use '*' as eventType to receive ALL events
|
|
452
457
|
*/
|
|
453
458
|
subscribe(eventType, handler) {
|
|
454
459
|
if (!this.handlers.has(eventType)) {
|
|
@@ -466,14 +471,10 @@ var ExGuardRealtime = class {
|
|
|
466
471
|
};
|
|
467
472
|
}
|
|
468
473
|
/**
|
|
469
|
-
* Subscribe to
|
|
474
|
+
* Subscribe to ALL realtime events (wildcard)
|
|
470
475
|
*/
|
|
471
476
|
subscribeAll(handler) {
|
|
472
|
-
|
|
473
|
-
const unsubscribes = eventTypes.map((type) => this.subscribe(type, handler));
|
|
474
|
-
return () => {
|
|
475
|
-
unsubscribes.forEach((unsub) => unsub());
|
|
476
|
-
};
|
|
477
|
+
return this.subscribe("*", handler);
|
|
477
478
|
}
|
|
478
479
|
/**
|
|
479
480
|
* Handle incoming realtime events
|
|
@@ -490,6 +491,16 @@ var ExGuardRealtime = class {
|
|
|
490
491
|
}
|
|
491
492
|
});
|
|
492
493
|
}
|
|
494
|
+
const wildcardHandlers = this.handlers.get("*");
|
|
495
|
+
if (wildcardHandlers) {
|
|
496
|
+
wildcardHandlers.forEach((handler) => {
|
|
497
|
+
try {
|
|
498
|
+
handler(event);
|
|
499
|
+
} catch (error) {
|
|
500
|
+
console.error("[ExGuardRealtime] Wildcard handler error:", error);
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
}
|
|
493
504
|
}
|
|
494
505
|
/**
|
|
495
506
|
* Handle reconnection logic
|
|
@@ -639,36 +650,40 @@ var ExGuardBackendEnhanced = class {
|
|
|
639
650
|
this.config.realtime.url,
|
|
640
651
|
this.config.realtime.accessToken
|
|
641
652
|
);
|
|
642
|
-
this.realtime.
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
this.
|
|
653
|
+
this.realtime.subscribeToChannel("rbac");
|
|
654
|
+
this.realtime.subscribeToChannel("roles");
|
|
655
|
+
this.realtime.subscribeToChannel("permissions");
|
|
656
|
+
this.realtime.subscribe("*", (event) => {
|
|
657
|
+
console.log("[ExGuardBackend] Realtime event received:", event);
|
|
658
|
+
if (event.type.includes("rbac") || event.type === "rbac_update") {
|
|
659
|
+
this.config.realtime?.onRBACUpdate?.(event);
|
|
660
|
+
if (event.userId) {
|
|
661
|
+
this.cache.clearUserCache(event.userId);
|
|
662
|
+
} else {
|
|
663
|
+
this.cache.clear();
|
|
664
|
+
}
|
|
649
665
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
666
|
+
if (event.type.includes("user") || event.type === "user_update") {
|
|
667
|
+
this.config.realtime?.onUserUpdate?.(event);
|
|
668
|
+
if (event.userId) {
|
|
669
|
+
this.cache.clearUserCache(event.userId);
|
|
670
|
+
} else {
|
|
671
|
+
this.cache.clear();
|
|
672
|
+
}
|
|
656
673
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
this.cache.clear();
|
|
674
|
+
if (event.type.includes("role") || event.type === "role_update") {
|
|
675
|
+
if (event.userId) {
|
|
676
|
+
this.cache.clearUserCache(event.userId);
|
|
677
|
+
} else {
|
|
678
|
+
this.cache.clear();
|
|
679
|
+
}
|
|
664
680
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
this.cache.clear();
|
|
681
|
+
if (event.type.includes("permission") || event.type === "permission_update") {
|
|
682
|
+
if (event.userId) {
|
|
683
|
+
this.cache.clearUserCache(event.userId);
|
|
684
|
+
} else {
|
|
685
|
+
this.cache.clear();
|
|
686
|
+
}
|
|
672
687
|
}
|
|
673
688
|
});
|
|
674
689
|
} catch (error) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -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, createRealtime } from './realtime.js';\nexport type { \n RealtimeEvent, \n RealtimeEventHandler,\n RealtimeConnectionHandler,\n RealtimeErrorHandler,\n RealtimeAuthOptions,\n ExGuardRealtimeConfig \n} 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 as ExGuardRealtimeConfigType,\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 { \n realtime, \n RealtimeEvent, \n ExGuardRealtime,\n ExGuardRealtimeConfig,\n createRealtime \n} 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 accessToken?: string;\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n autoConnect?: boolean;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onRBACUpdate?: (event: RealtimeEvent) => void;\n onUserUpdate?: (event: RealtimeEvent) => void;\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 private _isRealtimeConnected = false;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000,\n },\n realtime: {\n enabled: false,\n autoReconnect: true,\n maxReconnectAttempts: 5,\n reconnectDelay: 1000,\n },\n ...config,\n };\n\n this.cache = cache;\n \n const realtimeConfig: ExGuardRealtimeConfig = {\n autoReconnect: this.config.realtime?.autoReconnect ?? true,\n maxReconnectAttempts: this.config.realtime?.maxReconnectAttempts ?? 5,\n reconnectDelay: this.config.realtime?.reconnectDelay ?? 1000,\n onConnect: () => {\n this._isRealtimeConnected = true;\n this.config.realtime?.onConnect?.();\n },\n onDisconnect: () => {\n this._isRealtimeConnected = false;\n this.config.realtime?.onDisconnect?.();\n },\n onError: (error) => {\n this.config.realtime?.onError?.(error);\n },\n };\n \n this.realtime = createRealtime(realtimeConfig);\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 if (this.config.realtime?.enabled && this.config.realtime.url) {\n this.setupRealtime();\n }\n\n setInterval(() => {\n this.cache.cleanup();\n }, 60000);\n }\n\n private async setupRealtime(): Promise<void> {\n // Only connect if explicitly enabled AND URL is provided\n if (!this.config.realtime?.enabled || !this.config.realtime?.url) {\n return;\n }\n\n try {\n await this.realtime.connect(\n this.config.realtime.url, \n this.config.realtime.accessToken\n );\n \n this.realtime.subscribe('rbac_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] RBAC update received:', event);\n this.config.realtime?.onRBACUpdate?.(event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n });\n\n this.realtime.subscribe('user_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] User update received:', event);\n this.config.realtime?.onUserUpdate?.(event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n }\n });\n\n this.realtime.subscribe('role_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] Role update received:', event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n });\n\n this.realtime.subscribe('permission_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] Permission update received:', event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n });\n\n } catch (error) {\n console.warn('[ExGuardBackend] Realtime connection failed (will retry on demand):', error);\n }\n }\n\n /**\n * Manually connect to realtime server\n */\n async connectRealtime(url?: string, accessToken?: string): Promise<void> {\n const wsUrl = url || this.config.realtime?.url;\n const wsToken = accessToken || this.config.realtime?.accessToken;\n \n if (!wsUrl) {\n throw new Error('WebSocket URL is required');\n }\n \n await this.setupRealtime();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnectRealtime(): void {\n this.realtime.disconnect();\n }\n\n /**\n * Check if realtime is connected\n */\n isRealtimeConnected(): boolean {\n return this._isRealtimeConnected || this.realtime.isConnected();\n }\n\n /**\n * Get realtime connection status\n */\n getRealtimeStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n return this.realtime.getStatus();\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribeToRealtime(eventType: string, handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribe(eventType, handler);\n }\n\n /**\n * Subscribe to all realtime events\n */\n subscribeToAllRealtime(handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribeAll(handler);\n }\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 private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\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 this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\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 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 this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\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 this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\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 this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\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 this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\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 this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 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 clearAllCache(): void {\n this.cache.clear();\n console.log('[ExGuardBackend] All cache cleared');\n }\n\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\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 with Socket.IO support\n * Works in both browser and Node.js environments\n */\n\nimport { io, type Socket } from 'socket.io-client';\n\nexport interface RealtimeEvent {\n type: string;\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport interface RealtimeConnectionHandler {\n (): void;\n}\n\nexport interface RealtimeAuthOptions {\n accessToken?: string;\n apiKey?: string;\n bearerToken?: string;\n userId?: string;\n}\n\nexport interface RealtimeErrorHandler {\n (error: Error): void;\n}\n\nexport interface ExGuardRealtimeConfig {\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n reconnectMaxDelay?: number;\n onConnect?: RealtimeConnectionHandler;\n onDisconnect?: RealtimeConnectionHandler;\n onError?: RealtimeErrorHandler;\n autoConnect?: boolean;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private socket: Socket | null = null;\n private reconnectAttempts = 0;\n private config: Required<ExGuardRealtimeConfig>;\n private currentUrl: string | null = null;\n private currentToken: string | null = null;\n private currentUserId: string | null = null;\n private shouldReconnect = true;\n\n constructor(config: ExGuardRealtimeConfig = {}) {\n this.config = {\n autoReconnect: config.autoReconnect ?? true,\n maxReconnectAttempts: config.maxReconnectAttempts ?? 5,\n reconnectDelay: config.reconnectDelay ?? 1000,\n reconnectMaxDelay: config.reconnectMaxDelay ?? 30000,\n onConnect: config.onConnect ?? (() => {}),\n onDisconnect: config.onDisconnect ?? (() => {}),\n onError: config.onError ?? ((error: Error) => console.error('[ExGuardRealtime] Error:', error)),\n autoConnect: config.autoConnect ?? false,\n };\n }\n\n /**\n * Initialize and optionally connect to realtime server\n */\n async init(url?: string, accessToken?: string, userId?: string): Promise<void> {\n if (url) {\n this.currentUrl = url;\n this.currentToken = accessToken ?? null;\n this.currentUserId = userId ?? null;\n if (this.config.autoConnect) {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Auto-connect failed, will retry on demand:', error);\n }\n }\n }\n }\n\n /**\n * Connect to realtime server using Socket.IO\n * @param url - Server URL (e.g., https://api.example.com)\n * @param auth - Authentication options (accessToken, apiKey, bearerToken, userId)\n */\n connect(url: string, auth?: string | RealtimeAuthOptions, userId?: string): Promise<void> {\n let authToken: string | undefined;\n let authUserId: string | undefined;\n\n if (typeof auth === 'string') {\n authToken = auth;\n authUserId = userId || 'unknown';\n } else if (typeof auth === 'object') {\n authToken = auth.accessToken || auth.bearerToken || auth.apiKey;\n authUserId = auth.userId || userId || 'unknown';\n }\n\n return new Promise((resolve, reject) => {\n this.shouldReconnect = true;\n this.currentUrl = url;\n this.currentToken = authToken ?? null;\n this.currentUserId = authUserId ?? null;\n\n try {\n // Disconnect existing socket\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n\n const socketUrl = `${url}/realtime`;\n console.log('[ExGuardRealtime] Connecting to:', socketUrl);\n\n this.socket = io(socketUrl, {\n auth: {\n token: authToken,\n userId: authUserId,\n },\n transports: ['websocket', 'polling'],\n reconnection: this.config.autoReconnect,\n reconnectionDelay: this.config.reconnectDelay,\n reconnectionDelayMax: this.config.reconnectMaxDelay,\n reconnectionAttempts: this.config.maxReconnectAttempts,\n timeout: 20000,\n });\n\n this.socket.on('connect', () => {\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected! Socket ID:', this.socket?.id);\n this.config.onConnect();\n resolve();\n });\n\n this.socket.on('disconnect', (reason: string) => {\n console.log('[ExGuardRealtime] Disconnected:', reason);\n this.config.onDisconnect();\n if (this.shouldReconnect && this.config.autoReconnect) {\n this.handleReconnect();\n }\n });\n\n this.socket.on('connect_error', (error: any) => {\n console.error('[ExGuardRealtime] Connection error:', error.message);\n const err = new Error(`Connection error: ${error.message}`);\n this.config.onError(err);\n if (!this.shouldReconnect || this.reconnectAttempts >= this.config.maxReconnectAttempts) {\n reject(err);\n }\n });\n\n this.socket.on('error', (error: any) => {\n console.error('[ExGuardRealtime] Socket error:', error);\n const err = new Error(`Socket error: ${error}`);\n this.config.onError(err);\n });\n\n this.socket.on('reconnect_attempt', (attempt: number) => {\n this.reconnectAttempts = attempt;\n console.log(`[ExGuardRealtime] Reconnecting... (attempt ${attempt})`);\n });\n\n this.socket.on('reconnect', () => {\n console.log('[ExGuardRealtime] Reconnected!');\n });\n\n this.socket.on('reconnect_failed', () => {\n console.error('[ExGuardRealtime] Reconnection failed after max attempts');\n const err = new Error('Reconnection failed after maximum attempts');\n this.config.onError(err);\n reject(err);\n });\n\n // Listen to all realtime events\n this.socket.onAny((eventName: string, payload: any) => {\n try {\n const realtimeEvent: RealtimeEvent = {\n type: eventName,\n timestamp: payload?.timestamp || Date.now(),\n data: payload?.data || payload,\n userId: payload?.userId,\n };\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to handle event:', error);\n }\n });\n\n // Set connection timeout\n setTimeout(() => {\n if (!this.socket?.connected) {\n const err = new Error('Connection timeout');\n this.config.onError(err);\n this.socket?.disconnect();\n reject(err);\n }\n }, 20000);\n\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Subscribe to channels\n */\n subscribeToChannel(channel: 'roles' | 'permissions' | 'rbac'): void {\n if (this.socket?.connected) {\n this.socket.emit(`subscribe:${channel}`);\n console.log(`[ExGuardRealtime] Subscribed to channel: ${channel}`);\n }\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n if (this.socket) {\n this.socket.disconnect();\n this.socket = 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 () => {\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 * Subscribe to all realtime events\n */\n subscribeAll(handler: RealtimeEventHandler): () => void {\n const eventTypes = ['rbac_update', 'user_update', 'role_update', 'permission_update'];\n const unsubscribes = eventTypes.map(type => this.subscribe(type, handler));\n \n return () => {\n unsubscribes.forEach(unsub => unsub());\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(): void {\n if (!this.shouldReconnect || !this.config.autoReconnect || !this.currentUrl) {\n return;\n }\n\n if (this.reconnectAttempts < this.config.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = Math.min(\n this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),\n this.config.reconnectMaxDelay\n );\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(this.currentUrl!, this.currentToken!, this.currentUserId!).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 * Manually trigger reconnection with current auth\n */\n reconnect(): Promise<void> {\n if (this.currentUrl && this.currentToken) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl, this.currentToken, this.currentUserId || undefined);\n } else if (this.currentUrl) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl);\n }\n return Promise.reject(new Error('No URL configured'));\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.socket?.connected ?? false;\n }\n\n /**\n * Get connection status\n */\n getStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n if (!this.socket) return 'disconnected';\n if (this.socket.connected) return 'connected';\n return 'disconnected';\n }\n\n /**\n * Send a message to the server\n */\n send(event: string, data: any): void {\n if (this.socket?.connected) {\n this.socket.emit(event, data);\n }\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ExGuardRealtimeConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n };\n }\n\n /**\n * Connect on-demand with user's access token from request\n * Call this in your guard or middleware with the user's token\n */\n async connectWithUserToken(url: string, accessToken: string, userId?: string): Promise<void> {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Failed to connect with user token:', error);\n }\n }\n}\n\n// Factory function for creating realtime instance\nexport function createRealtime(config?: ExGuardRealtimeConfig): ExGuardRealtime {\n return new ExGuardRealtime(config);\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;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,QAAM,OA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AAK,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, createRealtime } from './realtime.js';\nexport type { \n RealtimeEvent, \n RealtimeEventHandler,\n RealtimeConnectionHandler,\n RealtimeErrorHandler,\n RealtimeAuthOptions,\n ExGuardRealtimeConfig \n} 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 as ExGuardRealtimeConfigType,\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 { \n realtime, \n RealtimeEvent, \n ExGuardRealtime,\n ExGuardRealtimeConfig,\n createRealtime \n} 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 accessToken?: string;\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n autoConnect?: boolean;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onRBACUpdate?: (event: RealtimeEvent) => void;\n onUserUpdate?: (event: RealtimeEvent) => void;\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 private _isRealtimeConnected = false;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000,\n },\n realtime: {\n enabled: false,\n autoReconnect: true,\n maxReconnectAttempts: 5,\n reconnectDelay: 1000,\n },\n ...config,\n };\n\n this.cache = cache;\n \n const realtimeConfig: ExGuardRealtimeConfig = {\n autoReconnect: this.config.realtime?.autoReconnect ?? true,\n maxReconnectAttempts: this.config.realtime?.maxReconnectAttempts ?? 5,\n reconnectDelay: this.config.realtime?.reconnectDelay ?? 1000,\n onConnect: () => {\n this._isRealtimeConnected = true;\n this.config.realtime?.onConnect?.();\n },\n onDisconnect: () => {\n this._isRealtimeConnected = false;\n this.config.realtime?.onDisconnect?.();\n },\n onError: (error) => {\n this.config.realtime?.onError?.(error);\n },\n };\n \n this.realtime = createRealtime(realtimeConfig);\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 if (this.config.realtime?.enabled && this.config.realtime.url) {\n this.setupRealtime();\n }\n\n setInterval(() => {\n this.cache.cleanup();\n }, 60000);\n }\n\n private async setupRealtime(): Promise<void> {\n // Only connect if explicitly enabled AND URL is provided\n if (!this.config.realtime?.enabled || !this.config.realtime?.url) {\n return;\n }\n\n try {\n await this.realtime.connect(\n this.config.realtime.url, \n this.config.realtime.accessToken\n );\n\n // Subscribe to channels for realtime updates\n this.realtime.subscribeToChannel('rbac');\n this.realtime.subscribeToChannel('roles');\n this.realtime.subscribeToChannel('permissions');\n \n // Listen to all events using wildcard\n this.realtime.subscribe('*', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] Realtime event received:', event);\n \n // Handle specific event types\n if (event.type.includes('rbac') || event.type === 'rbac_update') {\n this.config.realtime?.onRBACUpdate?.(event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n \n if (event.type.includes('user') || event.type === 'user_update') {\n this.config.realtime?.onUserUpdate?.(event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n \n if (event.type.includes('role') || event.type === 'role_update') {\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n \n if (event.type.includes('permission') || event.type === 'permission_update') {\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n });\n\n } catch (error) {\n console.warn('[ExGuardBackend] Realtime connection failed (will retry on demand):', error);\n }\n }\n\n /**\n * Manually connect to realtime server\n */\n async connectRealtime(url?: string, accessToken?: string): Promise<void> {\n const wsUrl = url || this.config.realtime?.url;\n const wsToken = accessToken || this.config.realtime?.accessToken;\n \n if (!wsUrl) {\n throw new Error('WebSocket URL is required');\n }\n \n await this.setupRealtime();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnectRealtime(): void {\n this.realtime.disconnect();\n }\n\n /**\n * Check if realtime is connected\n */\n isRealtimeConnected(): boolean {\n return this._isRealtimeConnected || this.realtime.isConnected();\n }\n\n /**\n * Get realtime connection status\n */\n getRealtimeStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n return this.realtime.getStatus();\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribeToRealtime(eventType: string, handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribe(eventType, handler);\n }\n\n /**\n * Subscribe to all realtime events\n */\n subscribeToAllRealtime(handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribeAll(handler);\n }\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 private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\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 this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\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 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 this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\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 this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\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 this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\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 this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\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 this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 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 clearAllCache(): void {\n this.cache.clear();\n console.log('[ExGuardBackend] All cache cleared');\n }\n\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\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 - clears ALL caches related to this user\n */\n clearUserCache(userId: string): void {\n // Clear all keys that contain this userId\n const keysToDelete = Array.from(this.cache.keys()).filter(key => \n key.includes(userId)\n );\n \n console.log(`[ExGuardCache] Clearing cache for user ${userId}, found ${keysToDelete.length} keys:`, keysToDelete);\n \n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n \n if (keysToDelete.length === 0) {\n console.log(`[ExGuardCache] No cache entries found for user ${userId}`);\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 with Socket.IO support\n * Works in both browser and Node.js environments\n */\n\nimport { io, type Socket } from 'socket.io-client';\n\nexport interface RealtimeEvent {\n type: string;\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport interface RealtimeConnectionHandler {\n (): void;\n}\n\nexport interface RealtimeAuthOptions {\n accessToken?: string;\n apiKey?: string;\n bearerToken?: string;\n userId?: string;\n}\n\nexport interface RealtimeErrorHandler {\n (error: Error): void;\n}\n\nexport interface ExGuardRealtimeConfig {\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n reconnectMaxDelay?: number;\n onConnect?: RealtimeConnectionHandler;\n onDisconnect?: RealtimeConnectionHandler;\n onError?: RealtimeErrorHandler;\n autoConnect?: boolean;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private socket: Socket | null = null;\n private reconnectAttempts = 0;\n private config: Required<ExGuardRealtimeConfig>;\n private currentUrl: string | null = null;\n private currentToken: string | null = null;\n private currentUserId: string | null = null;\n private shouldReconnect = true;\n\n constructor(config: ExGuardRealtimeConfig = {}) {\n this.config = {\n autoReconnect: config.autoReconnect ?? true,\n maxReconnectAttempts: config.maxReconnectAttempts ?? 5,\n reconnectDelay: config.reconnectDelay ?? 1000,\n reconnectMaxDelay: config.reconnectMaxDelay ?? 30000,\n onConnect: config.onConnect ?? (() => {}),\n onDisconnect: config.onDisconnect ?? (() => {}),\n onError: config.onError ?? ((error: Error) => console.error('[ExGuardRealtime] Error:', error)),\n autoConnect: config.autoConnect ?? false,\n };\n }\n\n /**\n * Initialize and optionally connect to realtime server\n */\n async init(url?: string, accessToken?: string, userId?: string): Promise<void> {\n if (url) {\n this.currentUrl = url;\n this.currentToken = accessToken ?? null;\n this.currentUserId = userId ?? null;\n if (this.config.autoConnect) {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Auto-connect failed, will retry on demand:', error);\n }\n }\n }\n }\n\n /**\n * Connect to realtime server using Socket.IO\n * @param url - Server URL (e.g., https://api.example.com)\n * @param auth - Authentication options (accessToken, apiKey, bearerToken, userId)\n */\n connect(url: string, auth?: string | RealtimeAuthOptions, userId?: string): Promise<void> {\n let authToken: string | undefined;\n let authUserId: string | undefined;\n\n if (typeof auth === 'string') {\n authToken = auth;\n authUserId = userId || 'unknown';\n } else if (typeof auth === 'object') {\n authToken = auth.accessToken || auth.bearerToken || auth.apiKey;\n authUserId = auth.userId || userId || 'unknown';\n }\n\n return new Promise((resolve, reject) => {\n this.shouldReconnect = true;\n this.currentUrl = url;\n this.currentToken = authToken ?? null;\n this.currentUserId = authUserId ?? null;\n\n try {\n // Disconnect existing socket\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n\n const socketUrl = `${url}/realtime`;\n console.log('[ExGuardRealtime] Connecting to:', socketUrl);\n\n this.socket = io(socketUrl, {\n auth: {\n token: authToken,\n userId: authUserId,\n },\n transports: ['websocket', 'polling'],\n reconnection: this.config.autoReconnect,\n reconnectionDelay: this.config.reconnectDelay,\n reconnectionDelayMax: this.config.reconnectMaxDelay,\n reconnectionAttempts: this.config.maxReconnectAttempts,\n timeout: 20000,\n });\n\n this.socket.on('connect', () => {\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected! Socket ID:', this.socket?.id);\n this.config.onConnect();\n resolve();\n });\n\n this.socket.on('disconnect', (reason: string) => {\n console.log('[ExGuardRealtime] Disconnected:', reason);\n this.config.onDisconnect();\n if (this.shouldReconnect && this.config.autoReconnect) {\n this.handleReconnect();\n }\n });\n\n this.socket.on('connect_error', (error: any) => {\n console.error('[ExGuardRealtime] Connection error:', error.message);\n const err = new Error(`Connection error: ${error.message}`);\n this.config.onError(err);\n if (!this.shouldReconnect || this.reconnectAttempts >= this.config.maxReconnectAttempts) {\n reject(err);\n }\n });\n\n this.socket.on('error', (error: any) => {\n console.error('[ExGuardRealtime] Socket error:', error);\n const err = new Error(`Socket error: ${error}`);\n this.config.onError(err);\n });\n\n this.socket.on('reconnect_attempt', (attempt: number) => {\n this.reconnectAttempts = attempt;\n console.log(`[ExGuardRealtime] Reconnecting... (attempt ${attempt})`);\n });\n\n this.socket.on('reconnect', () => {\n console.log('[ExGuardRealtime] Reconnected!');\n });\n\n this.socket.on('reconnect_failed', () => {\n console.error('[ExGuardRealtime] Reconnection failed after max attempts');\n const err = new Error('Reconnection failed after maximum attempts');\n this.config.onError(err);\n reject(err);\n });\n\n // Listen to all realtime events\n this.socket.onAny((eventName: string, payload: any) => {\n try {\n const realtimeEvent: RealtimeEvent = {\n type: eventName,\n timestamp: payload?.timestamp || Date.now(),\n data: payload?.data || payload,\n userId: payload?.userId,\n };\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to handle event:', error);\n }\n });\n\n // Set connection timeout\n setTimeout(() => {\n if (!this.socket?.connected) {\n const err = new Error('Connection timeout');\n this.config.onError(err);\n this.socket?.disconnect();\n reject(err);\n }\n }, 20000);\n\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Subscribe to channels\n */\n subscribeToChannel(channel: 'roles' | 'permissions' | 'rbac'): void {\n if (this.socket?.connected) {\n this.socket.emit(`subscribe:${channel}`);\n console.log(`[ExGuardRealtime] Subscribed to channel: ${channel}`);\n }\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n }\n\n /**\n * Subscribe to realtime events\n * Use '*' as eventType to receive ALL 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 () => {\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 * Subscribe to ALL realtime events (wildcard)\n */\n subscribeAll(handler: RealtimeEventHandler): () => void {\n return this.subscribe('*', handler);\n }\n\n /**\n * Handle incoming realtime events\n */\n private handleEvent(event: RealtimeEvent): void {\n console.log('[ExGuardRealtime] Received event:', event);\n \n // Call specific event handlers\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 // Call wildcard handlers for ALL events\n const wildcardHandlers = this.handlers.get('*');\n if (wildcardHandlers) {\n wildcardHandlers.forEach(handler => {\n try {\n handler(event);\n } catch (error) {\n console.error('[ExGuardRealtime] Wildcard handler error:', error);\n }\n });\n }\n }\n\n /**\n * Handle reconnection logic\n */\n private handleReconnect(): void {\n if (!this.shouldReconnect || !this.config.autoReconnect || !this.currentUrl) {\n return;\n }\n\n if (this.reconnectAttempts < this.config.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = Math.min(\n this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),\n this.config.reconnectMaxDelay\n );\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(this.currentUrl!, this.currentToken!, this.currentUserId!).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 * Manually trigger reconnection with current auth\n */\n reconnect(): Promise<void> {\n if (this.currentUrl && this.currentToken) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl, this.currentToken, this.currentUserId || undefined);\n } else if (this.currentUrl) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl);\n }\n return Promise.reject(new Error('No URL configured'));\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.socket?.connected ?? false;\n }\n\n /**\n * Get connection status\n */\n getStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n if (!this.socket) return 'disconnected';\n if (this.socket.connected) return 'connected';\n return 'disconnected';\n }\n\n /**\n * Send a message to the server\n */\n send(event: string, data: any): void {\n if (this.socket?.connected) {\n this.socket.emit(event, data);\n }\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ExGuardRealtimeConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n };\n }\n\n /**\n * Connect on-demand with user's access token from request\n * Call this in your guard or middleware with the user's token\n */\n async connectWithUserToken(url: string, accessToken: string, userId?: string): Promise<void> {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Failed to connect with user token:', error);\n }\n }\n}\n\n// Factory function for creating realtime instance\nexport function createRealtime(config?: ExGuardRealtimeConfig): ExGuardRealtime {\n return new ExGuardRealtime(config);\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;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,QAAM,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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AAI,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
|
@@ -180,10 +180,11 @@ declare class ExGuardRealtime {
|
|
|
180
180
|
disconnect(): void;
|
|
181
181
|
/**
|
|
182
182
|
* Subscribe to realtime events
|
|
183
|
+
* Use '*' as eventType to receive ALL events
|
|
183
184
|
*/
|
|
184
185
|
subscribe(eventType: string, handler: RealtimeEventHandler): () => void;
|
|
185
186
|
/**
|
|
186
|
-
* Subscribe to
|
|
187
|
+
* Subscribe to ALL realtime events (wildcard)
|
|
187
188
|
*/
|
|
188
189
|
subscribeAll(handler: RealtimeEventHandler): () => void;
|
|
189
190
|
/**
|
|
@@ -317,7 +318,7 @@ declare class ExGuardCache {
|
|
|
317
318
|
*/
|
|
318
319
|
clear(): void;
|
|
319
320
|
/**
|
|
320
|
-
* Clear cache for a specific user
|
|
321
|
+
* Clear cache for a specific user - clears ALL caches related to this user
|
|
321
322
|
*/
|
|
322
323
|
clearUserCache(userId: string): void;
|
|
323
324
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -180,10 +180,11 @@ declare class ExGuardRealtime {
|
|
|
180
180
|
disconnect(): void;
|
|
181
181
|
/**
|
|
182
182
|
* Subscribe to realtime events
|
|
183
|
+
* Use '*' as eventType to receive ALL events
|
|
183
184
|
*/
|
|
184
185
|
subscribe(eventType: string, handler: RealtimeEventHandler): () => void;
|
|
185
186
|
/**
|
|
186
|
-
* Subscribe to
|
|
187
|
+
* Subscribe to ALL realtime events (wildcard)
|
|
187
188
|
*/
|
|
188
189
|
subscribeAll(handler: RealtimeEventHandler): () => void;
|
|
189
190
|
/**
|
|
@@ -317,7 +318,7 @@ declare class ExGuardCache {
|
|
|
317
318
|
*/
|
|
318
319
|
clear(): void;
|
|
319
320
|
/**
|
|
320
|
-
* Clear cache for a specific user
|
|
321
|
+
* Clear cache for a specific user - clears ALL caches related to this user
|
|
321
322
|
*/
|
|
322
323
|
clearUserCache(userId: string): void;
|
|
323
324
|
/**
|
package/dist/index.js
CHANGED
|
@@ -165,16 +165,20 @@ var ExGuardCache = class {
|
|
|
165
165
|
keys.forEach((key) => this.notifySubscribers(key));
|
|
166
166
|
}
|
|
167
167
|
/**
|
|
168
|
-
* Clear cache for a specific user
|
|
168
|
+
* Clear cache for a specific user - clears ALL caches related to this user
|
|
169
169
|
*/
|
|
170
170
|
clearUserCache(userId) {
|
|
171
171
|
const keysToDelete = Array.from(this.cache.keys()).filter(
|
|
172
|
-
(key) => key.
|
|
172
|
+
(key) => key.includes(userId)
|
|
173
173
|
);
|
|
174
|
+
console.log(`[ExGuardCache] Clearing cache for user ${userId}, found ${keysToDelete.length} keys:`, keysToDelete);
|
|
174
175
|
keysToDelete.forEach((key) => {
|
|
175
176
|
this.cache.delete(key);
|
|
176
177
|
this.notifySubscribers(key);
|
|
177
178
|
});
|
|
179
|
+
if (keysToDelete.length === 0) {
|
|
180
|
+
console.log(`[ExGuardCache] No cache entries found for user ${userId}`);
|
|
181
|
+
}
|
|
178
182
|
}
|
|
179
183
|
/**
|
|
180
184
|
* Subscribe to cache changes
|
|
@@ -404,6 +408,7 @@ var ExGuardRealtime = class {
|
|
|
404
408
|
}
|
|
405
409
|
/**
|
|
406
410
|
* Subscribe to realtime events
|
|
411
|
+
* Use '*' as eventType to receive ALL events
|
|
407
412
|
*/
|
|
408
413
|
subscribe(eventType, handler) {
|
|
409
414
|
if (!this.handlers.has(eventType)) {
|
|
@@ -421,14 +426,10 @@ var ExGuardRealtime = class {
|
|
|
421
426
|
};
|
|
422
427
|
}
|
|
423
428
|
/**
|
|
424
|
-
* Subscribe to
|
|
429
|
+
* Subscribe to ALL realtime events (wildcard)
|
|
425
430
|
*/
|
|
426
431
|
subscribeAll(handler) {
|
|
427
|
-
|
|
428
|
-
const unsubscribes = eventTypes.map((type) => this.subscribe(type, handler));
|
|
429
|
-
return () => {
|
|
430
|
-
unsubscribes.forEach((unsub) => unsub());
|
|
431
|
-
};
|
|
432
|
+
return this.subscribe("*", handler);
|
|
432
433
|
}
|
|
433
434
|
/**
|
|
434
435
|
* Handle incoming realtime events
|
|
@@ -445,6 +446,16 @@ var ExGuardRealtime = class {
|
|
|
445
446
|
}
|
|
446
447
|
});
|
|
447
448
|
}
|
|
449
|
+
const wildcardHandlers = this.handlers.get("*");
|
|
450
|
+
if (wildcardHandlers) {
|
|
451
|
+
wildcardHandlers.forEach((handler) => {
|
|
452
|
+
try {
|
|
453
|
+
handler(event);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
console.error("[ExGuardRealtime] Wildcard handler error:", error);
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
}
|
|
448
459
|
}
|
|
449
460
|
/**
|
|
450
461
|
* Handle reconnection logic
|
|
@@ -594,36 +605,40 @@ var ExGuardBackendEnhanced = class {
|
|
|
594
605
|
this.config.realtime.url,
|
|
595
606
|
this.config.realtime.accessToken
|
|
596
607
|
);
|
|
597
|
-
this.realtime.
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
this.
|
|
608
|
+
this.realtime.subscribeToChannel("rbac");
|
|
609
|
+
this.realtime.subscribeToChannel("roles");
|
|
610
|
+
this.realtime.subscribeToChannel("permissions");
|
|
611
|
+
this.realtime.subscribe("*", (event) => {
|
|
612
|
+
console.log("[ExGuardBackend] Realtime event received:", event);
|
|
613
|
+
if (event.type.includes("rbac") || event.type === "rbac_update") {
|
|
614
|
+
this.config.realtime?.onRBACUpdate?.(event);
|
|
615
|
+
if (event.userId) {
|
|
616
|
+
this.cache.clearUserCache(event.userId);
|
|
617
|
+
} else {
|
|
618
|
+
this.cache.clear();
|
|
619
|
+
}
|
|
604
620
|
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
621
|
+
if (event.type.includes("user") || event.type === "user_update") {
|
|
622
|
+
this.config.realtime?.onUserUpdate?.(event);
|
|
623
|
+
if (event.userId) {
|
|
624
|
+
this.cache.clearUserCache(event.userId);
|
|
625
|
+
} else {
|
|
626
|
+
this.cache.clear();
|
|
627
|
+
}
|
|
611
628
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
this.cache.clear();
|
|
629
|
+
if (event.type.includes("role") || event.type === "role_update") {
|
|
630
|
+
if (event.userId) {
|
|
631
|
+
this.cache.clearUserCache(event.userId);
|
|
632
|
+
} else {
|
|
633
|
+
this.cache.clear();
|
|
634
|
+
}
|
|
619
635
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
this.cache.clear();
|
|
636
|
+
if (event.type.includes("permission") || event.type === "permission_update") {
|
|
637
|
+
if (event.userId) {
|
|
638
|
+
this.cache.clearUserCache(event.userId);
|
|
639
|
+
} else {
|
|
640
|
+
this.cache.clear();
|
|
641
|
+
}
|
|
627
642
|
}
|
|
628
643
|
});
|
|
629
644
|
} catch (error) {
|
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 { \n realtime, \n RealtimeEvent, \n ExGuardRealtime,\n ExGuardRealtimeConfig,\n createRealtime \n} 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 accessToken?: string;\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n autoConnect?: boolean;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onRBACUpdate?: (event: RealtimeEvent) => void;\n onUserUpdate?: (event: RealtimeEvent) => void;\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 private _isRealtimeConnected = false;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000,\n },\n realtime: {\n enabled: false,\n autoReconnect: true,\n maxReconnectAttempts: 5,\n reconnectDelay: 1000,\n },\n ...config,\n };\n\n this.cache = cache;\n \n const realtimeConfig: ExGuardRealtimeConfig = {\n autoReconnect: this.config.realtime?.autoReconnect ?? true,\n maxReconnectAttempts: this.config.realtime?.maxReconnectAttempts ?? 5,\n reconnectDelay: this.config.realtime?.reconnectDelay ?? 1000,\n onConnect: () => {\n this._isRealtimeConnected = true;\n this.config.realtime?.onConnect?.();\n },\n onDisconnect: () => {\n this._isRealtimeConnected = false;\n this.config.realtime?.onDisconnect?.();\n },\n onError: (error) => {\n this.config.realtime?.onError?.(error);\n },\n };\n \n this.realtime = createRealtime(realtimeConfig);\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 if (this.config.realtime?.enabled && this.config.realtime.url) {\n this.setupRealtime();\n }\n\n setInterval(() => {\n this.cache.cleanup();\n }, 60000);\n }\n\n private async setupRealtime(): Promise<void> {\n // Only connect if explicitly enabled AND URL is provided\n if (!this.config.realtime?.enabled || !this.config.realtime?.url) {\n return;\n }\n\n try {\n await this.realtime.connect(\n this.config.realtime.url, \n this.config.realtime.accessToken\n );\n \n this.realtime.subscribe('rbac_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] RBAC update received:', event);\n this.config.realtime?.onRBACUpdate?.(event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n });\n\n this.realtime.subscribe('user_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] User update received:', event);\n this.config.realtime?.onUserUpdate?.(event);\n \n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n }\n });\n\n this.realtime.subscribe('role_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] Role update received:', event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n });\n\n this.realtime.subscribe('permission_update', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] Permission update received:', event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n });\n\n } catch (error) {\n console.warn('[ExGuardBackend] Realtime connection failed (will retry on demand):', error);\n }\n }\n\n /**\n * Manually connect to realtime server\n */\n async connectRealtime(url?: string, accessToken?: string): Promise<void> {\n const wsUrl = url || this.config.realtime?.url;\n const wsToken = accessToken || this.config.realtime?.accessToken;\n \n if (!wsUrl) {\n throw new Error('WebSocket URL is required');\n }\n \n await this.setupRealtime();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnectRealtime(): void {\n this.realtime.disconnect();\n }\n\n /**\n * Check if realtime is connected\n */\n isRealtimeConnected(): boolean {\n return this._isRealtimeConnected || this.realtime.isConnected();\n }\n\n /**\n * Get realtime connection status\n */\n getRealtimeStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n return this.realtime.getStatus();\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribeToRealtime(eventType: string, handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribe(eventType, handler);\n }\n\n /**\n * Subscribe to all realtime events\n */\n subscribeToAllRealtime(handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribeAll(handler);\n }\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 private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\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 this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\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 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 this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\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 this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\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 this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\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 this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\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 this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 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 clearAllCache(): void {\n this.cache.clear();\n console.log('[ExGuardBackend] All cache cleared');\n }\n\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\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 with Socket.IO support\n * Works in both browser and Node.js environments\n */\n\nimport { io, type Socket } from 'socket.io-client';\n\nexport interface RealtimeEvent {\n type: string;\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport interface RealtimeConnectionHandler {\n (): void;\n}\n\nexport interface RealtimeAuthOptions {\n accessToken?: string;\n apiKey?: string;\n bearerToken?: string;\n userId?: string;\n}\n\nexport interface RealtimeErrorHandler {\n (error: Error): void;\n}\n\nexport interface ExGuardRealtimeConfig {\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n reconnectMaxDelay?: number;\n onConnect?: RealtimeConnectionHandler;\n onDisconnect?: RealtimeConnectionHandler;\n onError?: RealtimeErrorHandler;\n autoConnect?: boolean;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private socket: Socket | null = null;\n private reconnectAttempts = 0;\n private config: Required<ExGuardRealtimeConfig>;\n private currentUrl: string | null = null;\n private currentToken: string | null = null;\n private currentUserId: string | null = null;\n private shouldReconnect = true;\n\n constructor(config: ExGuardRealtimeConfig = {}) {\n this.config = {\n autoReconnect: config.autoReconnect ?? true,\n maxReconnectAttempts: config.maxReconnectAttempts ?? 5,\n reconnectDelay: config.reconnectDelay ?? 1000,\n reconnectMaxDelay: config.reconnectMaxDelay ?? 30000,\n onConnect: config.onConnect ?? (() => {}),\n onDisconnect: config.onDisconnect ?? (() => {}),\n onError: config.onError ?? ((error: Error) => console.error('[ExGuardRealtime] Error:', error)),\n autoConnect: config.autoConnect ?? false,\n };\n }\n\n /**\n * Initialize and optionally connect to realtime server\n */\n async init(url?: string, accessToken?: string, userId?: string): Promise<void> {\n if (url) {\n this.currentUrl = url;\n this.currentToken = accessToken ?? null;\n this.currentUserId = userId ?? null;\n if (this.config.autoConnect) {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Auto-connect failed, will retry on demand:', error);\n }\n }\n }\n }\n\n /**\n * Connect to realtime server using Socket.IO\n * @param url - Server URL (e.g., https://api.example.com)\n * @param auth - Authentication options (accessToken, apiKey, bearerToken, userId)\n */\n connect(url: string, auth?: string | RealtimeAuthOptions, userId?: string): Promise<void> {\n let authToken: string | undefined;\n let authUserId: string | undefined;\n\n if (typeof auth === 'string') {\n authToken = auth;\n authUserId = userId || 'unknown';\n } else if (typeof auth === 'object') {\n authToken = auth.accessToken || auth.bearerToken || auth.apiKey;\n authUserId = auth.userId || userId || 'unknown';\n }\n\n return new Promise((resolve, reject) => {\n this.shouldReconnect = true;\n this.currentUrl = url;\n this.currentToken = authToken ?? null;\n this.currentUserId = authUserId ?? null;\n\n try {\n // Disconnect existing socket\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n\n const socketUrl = `${url}/realtime`;\n console.log('[ExGuardRealtime] Connecting to:', socketUrl);\n\n this.socket = io(socketUrl, {\n auth: {\n token: authToken,\n userId: authUserId,\n },\n transports: ['websocket', 'polling'],\n reconnection: this.config.autoReconnect,\n reconnectionDelay: this.config.reconnectDelay,\n reconnectionDelayMax: this.config.reconnectMaxDelay,\n reconnectionAttempts: this.config.maxReconnectAttempts,\n timeout: 20000,\n });\n\n this.socket.on('connect', () => {\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected! Socket ID:', this.socket?.id);\n this.config.onConnect();\n resolve();\n });\n\n this.socket.on('disconnect', (reason: string) => {\n console.log('[ExGuardRealtime] Disconnected:', reason);\n this.config.onDisconnect();\n if (this.shouldReconnect && this.config.autoReconnect) {\n this.handleReconnect();\n }\n });\n\n this.socket.on('connect_error', (error: any) => {\n console.error('[ExGuardRealtime] Connection error:', error.message);\n const err = new Error(`Connection error: ${error.message}`);\n this.config.onError(err);\n if (!this.shouldReconnect || this.reconnectAttempts >= this.config.maxReconnectAttempts) {\n reject(err);\n }\n });\n\n this.socket.on('error', (error: any) => {\n console.error('[ExGuardRealtime] Socket error:', error);\n const err = new Error(`Socket error: ${error}`);\n this.config.onError(err);\n });\n\n this.socket.on('reconnect_attempt', (attempt: number) => {\n this.reconnectAttempts = attempt;\n console.log(`[ExGuardRealtime] Reconnecting... (attempt ${attempt})`);\n });\n\n this.socket.on('reconnect', () => {\n console.log('[ExGuardRealtime] Reconnected!');\n });\n\n this.socket.on('reconnect_failed', () => {\n console.error('[ExGuardRealtime] Reconnection failed after max attempts');\n const err = new Error('Reconnection failed after maximum attempts');\n this.config.onError(err);\n reject(err);\n });\n\n // Listen to all realtime events\n this.socket.onAny((eventName: string, payload: any) => {\n try {\n const realtimeEvent: RealtimeEvent = {\n type: eventName,\n timestamp: payload?.timestamp || Date.now(),\n data: payload?.data || payload,\n userId: payload?.userId,\n };\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to handle event:', error);\n }\n });\n\n // Set connection timeout\n setTimeout(() => {\n if (!this.socket?.connected) {\n const err = new Error('Connection timeout');\n this.config.onError(err);\n this.socket?.disconnect();\n reject(err);\n }\n }, 20000);\n\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Subscribe to channels\n */\n subscribeToChannel(channel: 'roles' | 'permissions' | 'rbac'): void {\n if (this.socket?.connected) {\n this.socket.emit(`subscribe:${channel}`);\n console.log(`[ExGuardRealtime] Subscribed to channel: ${channel}`);\n }\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n if (this.socket) {\n this.socket.disconnect();\n this.socket = 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 () => {\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 * Subscribe to all realtime events\n */\n subscribeAll(handler: RealtimeEventHandler): () => void {\n const eventTypes = ['rbac_update', 'user_update', 'role_update', 'permission_update'];\n const unsubscribes = eventTypes.map(type => this.subscribe(type, handler));\n \n return () => {\n unsubscribes.forEach(unsub => unsub());\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(): void {\n if (!this.shouldReconnect || !this.config.autoReconnect || !this.currentUrl) {\n return;\n }\n\n if (this.reconnectAttempts < this.config.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = Math.min(\n this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),\n this.config.reconnectMaxDelay\n );\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(this.currentUrl!, this.currentToken!, this.currentUserId!).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 * Manually trigger reconnection with current auth\n */\n reconnect(): Promise<void> {\n if (this.currentUrl && this.currentToken) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl, this.currentToken, this.currentUserId || undefined);\n } else if (this.currentUrl) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl);\n }\n return Promise.reject(new Error('No URL configured'));\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.socket?.connected ?? false;\n }\n\n /**\n * Get connection status\n */\n getStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n if (!this.socket) return 'disconnected';\n if (this.socket.connected) return 'connected';\n return 'disconnected';\n }\n\n /**\n * Send a message to the server\n */\n send(event: string, data: any): void {\n if (this.socket?.connected) {\n this.socket.emit(event, data);\n }\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ExGuardRealtimeConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n };\n }\n\n /**\n * Connect on-demand with user's access token from request\n * Call this in your guard or middleware with the user's token\n */\n async connectWithUserToken(url: string, accessToken: string, userId?: string): Promise<void> {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Failed to connect with user token:', error);\n }\n }\n}\n\n// Factory function for creating realtime instance\nexport function createRealtime(config?: ExGuardRealtimeConfig): ExGuardRealtime {\n return new ExGuardRealtime(config);\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;AA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;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 { \n realtime, \n RealtimeEvent, \n ExGuardRealtime,\n ExGuardRealtimeConfig,\n createRealtime \n} 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 accessToken?: string;\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n autoConnect?: boolean;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onRBACUpdate?: (event: RealtimeEvent) => void;\n onUserUpdate?: (event: RealtimeEvent) => void;\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 private _isRealtimeConnected = false;\n\n constructor(config: ExGuardEnhancedConfig) {\n this.config = {\n timeout: 10000,\n cache: {\n enabled: true,\n ttl: 300000,\n },\n realtime: {\n enabled: false,\n autoReconnect: true,\n maxReconnectAttempts: 5,\n reconnectDelay: 1000,\n },\n ...config,\n };\n\n this.cache = cache;\n \n const realtimeConfig: ExGuardRealtimeConfig = {\n autoReconnect: this.config.realtime?.autoReconnect ?? true,\n maxReconnectAttempts: this.config.realtime?.maxReconnectAttempts ?? 5,\n reconnectDelay: this.config.realtime?.reconnectDelay ?? 1000,\n onConnect: () => {\n this._isRealtimeConnected = true;\n this.config.realtime?.onConnect?.();\n },\n onDisconnect: () => {\n this._isRealtimeConnected = false;\n this.config.realtime?.onDisconnect?.();\n },\n onError: (error) => {\n this.config.realtime?.onError?.(error);\n },\n };\n \n this.realtime = createRealtime(realtimeConfig);\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 if (this.config.realtime?.enabled && this.config.realtime.url) {\n this.setupRealtime();\n }\n\n setInterval(() => {\n this.cache.cleanup();\n }, 60000);\n }\n\n private async setupRealtime(): Promise<void> {\n // Only connect if explicitly enabled AND URL is provided\n if (!this.config.realtime?.enabled || !this.config.realtime?.url) {\n return;\n }\n\n try {\n await this.realtime.connect(\n this.config.realtime.url, \n this.config.realtime.accessToken\n );\n\n // Subscribe to channels for realtime updates\n this.realtime.subscribeToChannel('rbac');\n this.realtime.subscribeToChannel('roles');\n this.realtime.subscribeToChannel('permissions');\n \n // Listen to all events using wildcard\n this.realtime.subscribe('*', (event: RealtimeEvent) => {\n console.log('[ExGuardBackend] Realtime event received:', event);\n \n // Handle specific event types\n if (event.type.includes('rbac') || event.type === 'rbac_update') {\n this.config.realtime?.onRBACUpdate?.(event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n \n if (event.type.includes('user') || event.type === 'user_update') {\n this.config.realtime?.onUserUpdate?.(event);\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n \n if (event.type.includes('role') || event.type === 'role_update') {\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n \n if (event.type.includes('permission') || event.type === 'permission_update') {\n if (event.userId) {\n this.cache.clearUserCache(event.userId);\n } else {\n this.cache.clear();\n }\n }\n });\n\n } catch (error) {\n console.warn('[ExGuardBackend] Realtime connection failed (will retry on demand):', error);\n }\n }\n\n /**\n * Manually connect to realtime server\n */\n async connectRealtime(url?: string, accessToken?: string): Promise<void> {\n const wsUrl = url || this.config.realtime?.url;\n const wsToken = accessToken || this.config.realtime?.accessToken;\n \n if (!wsUrl) {\n throw new Error('WebSocket URL is required');\n }\n \n await this.setupRealtime();\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnectRealtime(): void {\n this.realtime.disconnect();\n }\n\n /**\n * Check if realtime is connected\n */\n isRealtimeConnected(): boolean {\n return this._isRealtimeConnected || this.realtime.isConnected();\n }\n\n /**\n * Get realtime connection status\n */\n getRealtimeStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n return this.realtime.getStatus();\n }\n\n /**\n * Subscribe to realtime events\n */\n subscribeToRealtime(eventType: string, handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribe(eventType, handler);\n }\n\n /**\n * Subscribe to all realtime events\n */\n subscribeToAllRealtime(handler: (event: RealtimeEvent) => void): () => void {\n return this.realtime.subscribeAll(handler);\n }\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 private getCacheKey(token: string, suffix: string = ''): string {\n const userId = this.extractUserIdFromToken(token) || 'unknown';\n return `user:${userId}:${suffix}`;\n }\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 this.cache.set(cacheKey, data, this.config.cache.ttl);\n \n return data;\n }\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 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 this.cache.set(cacheKey, hasPermission, this.config.cache.ttl! / 2);\n \n return hasPermission;\n }\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 this.cache.set(cacheKey, hasRole, this.config.cache.ttl! / 2);\n \n return hasRole;\n }\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 this.cache.set(cacheKey, permissions, this.config.cache.ttl);\n \n return permissions;\n }\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 this.cache.set(cacheKey, roles, this.config.cache.ttl);\n \n return roles;\n }\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 this.cache.set(cacheKey, fieldOffices, this.config.cache.ttl);\n \n return fieldOffices;\n }\n\n async hasPermissions(token: string, permissions: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 async hasRoles(token: string, roles: string[]): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\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 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 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 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 clearAllCache(): void {\n this.cache.clear();\n console.log('[ExGuardBackend] All cache cleared');\n }\n\n getCacheStats(): { size: number; keys: string[] } {\n return this.cache.getStats();\n }\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 - clears ALL caches related to this user\n */\n clearUserCache(userId: string): void {\n // Clear all keys that contain this userId\n const keysToDelete = Array.from(this.cache.keys()).filter(key => \n key.includes(userId)\n );\n \n console.log(`[ExGuardCache] Clearing cache for user ${userId}, found ${keysToDelete.length} keys:`, keysToDelete);\n \n keysToDelete.forEach(key => {\n this.cache.delete(key);\n this.notifySubscribers(key);\n });\n \n if (keysToDelete.length === 0) {\n console.log(`[ExGuardCache] No cache entries found for user ${userId}`);\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 with Socket.IO support\n * Works in both browser and Node.js environments\n */\n\nimport { io, type Socket } from 'socket.io-client';\n\nexport interface RealtimeEvent {\n type: string;\n userId?: string;\n data?: any;\n timestamp: number;\n}\n\nexport interface RealtimeEventHandler {\n (event: RealtimeEvent): void;\n}\n\nexport interface RealtimeConnectionHandler {\n (): void;\n}\n\nexport interface RealtimeAuthOptions {\n accessToken?: string;\n apiKey?: string;\n bearerToken?: string;\n userId?: string;\n}\n\nexport interface RealtimeErrorHandler {\n (error: Error): void;\n}\n\nexport interface ExGuardRealtimeConfig {\n autoReconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n reconnectMaxDelay?: number;\n onConnect?: RealtimeConnectionHandler;\n onDisconnect?: RealtimeConnectionHandler;\n onError?: RealtimeErrorHandler;\n autoConnect?: boolean;\n}\n\nexport class ExGuardRealtime {\n private handlers = new Map<string, Set<RealtimeEventHandler>>();\n private socket: Socket | null = null;\n private reconnectAttempts = 0;\n private config: Required<ExGuardRealtimeConfig>;\n private currentUrl: string | null = null;\n private currentToken: string | null = null;\n private currentUserId: string | null = null;\n private shouldReconnect = true;\n\n constructor(config: ExGuardRealtimeConfig = {}) {\n this.config = {\n autoReconnect: config.autoReconnect ?? true,\n maxReconnectAttempts: config.maxReconnectAttempts ?? 5,\n reconnectDelay: config.reconnectDelay ?? 1000,\n reconnectMaxDelay: config.reconnectMaxDelay ?? 30000,\n onConnect: config.onConnect ?? (() => {}),\n onDisconnect: config.onDisconnect ?? (() => {}),\n onError: config.onError ?? ((error: Error) => console.error('[ExGuardRealtime] Error:', error)),\n autoConnect: config.autoConnect ?? false,\n };\n }\n\n /**\n * Initialize and optionally connect to realtime server\n */\n async init(url?: string, accessToken?: string, userId?: string): Promise<void> {\n if (url) {\n this.currentUrl = url;\n this.currentToken = accessToken ?? null;\n this.currentUserId = userId ?? null;\n if (this.config.autoConnect) {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Auto-connect failed, will retry on demand:', error);\n }\n }\n }\n }\n\n /**\n * Connect to realtime server using Socket.IO\n * @param url - Server URL (e.g., https://api.example.com)\n * @param auth - Authentication options (accessToken, apiKey, bearerToken, userId)\n */\n connect(url: string, auth?: string | RealtimeAuthOptions, userId?: string): Promise<void> {\n let authToken: string | undefined;\n let authUserId: string | undefined;\n\n if (typeof auth === 'string') {\n authToken = auth;\n authUserId = userId || 'unknown';\n } else if (typeof auth === 'object') {\n authToken = auth.accessToken || auth.bearerToken || auth.apiKey;\n authUserId = auth.userId || userId || 'unknown';\n }\n\n return new Promise((resolve, reject) => {\n this.shouldReconnect = true;\n this.currentUrl = url;\n this.currentToken = authToken ?? null;\n this.currentUserId = authUserId ?? null;\n\n try {\n // Disconnect existing socket\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n\n const socketUrl = `${url}/realtime`;\n console.log('[ExGuardRealtime] Connecting to:', socketUrl);\n\n this.socket = io(socketUrl, {\n auth: {\n token: authToken,\n userId: authUserId,\n },\n transports: ['websocket', 'polling'],\n reconnection: this.config.autoReconnect,\n reconnectionDelay: this.config.reconnectDelay,\n reconnectionDelayMax: this.config.reconnectMaxDelay,\n reconnectionAttempts: this.config.maxReconnectAttempts,\n timeout: 20000,\n });\n\n this.socket.on('connect', () => {\n this.reconnectAttempts = 0;\n console.log('[ExGuardRealtime] Connected! Socket ID:', this.socket?.id);\n this.config.onConnect();\n resolve();\n });\n\n this.socket.on('disconnect', (reason: string) => {\n console.log('[ExGuardRealtime] Disconnected:', reason);\n this.config.onDisconnect();\n if (this.shouldReconnect && this.config.autoReconnect) {\n this.handleReconnect();\n }\n });\n\n this.socket.on('connect_error', (error: any) => {\n console.error('[ExGuardRealtime] Connection error:', error.message);\n const err = new Error(`Connection error: ${error.message}`);\n this.config.onError(err);\n if (!this.shouldReconnect || this.reconnectAttempts >= this.config.maxReconnectAttempts) {\n reject(err);\n }\n });\n\n this.socket.on('error', (error: any) => {\n console.error('[ExGuardRealtime] Socket error:', error);\n const err = new Error(`Socket error: ${error}`);\n this.config.onError(err);\n });\n\n this.socket.on('reconnect_attempt', (attempt: number) => {\n this.reconnectAttempts = attempt;\n console.log(`[ExGuardRealtime] Reconnecting... (attempt ${attempt})`);\n });\n\n this.socket.on('reconnect', () => {\n console.log('[ExGuardRealtime] Reconnected!');\n });\n\n this.socket.on('reconnect_failed', () => {\n console.error('[ExGuardRealtime] Reconnection failed after max attempts');\n const err = new Error('Reconnection failed after maximum attempts');\n this.config.onError(err);\n reject(err);\n });\n\n // Listen to all realtime events\n this.socket.onAny((eventName: string, payload: any) => {\n try {\n const realtimeEvent: RealtimeEvent = {\n type: eventName,\n timestamp: payload?.timestamp || Date.now(),\n data: payload?.data || payload,\n userId: payload?.userId,\n };\n this.handleEvent(realtimeEvent);\n } catch (error) {\n console.error('[ExGuardRealtime] Failed to handle event:', error);\n }\n });\n\n // Set connection timeout\n setTimeout(() => {\n if (!this.socket?.connected) {\n const err = new Error('Connection timeout');\n this.config.onError(err);\n this.socket?.disconnect();\n reject(err);\n }\n }, 20000);\n\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Subscribe to channels\n */\n subscribeToChannel(channel: 'roles' | 'permissions' | 'rbac'): void {\n if (this.socket?.connected) {\n this.socket.emit(`subscribe:${channel}`);\n console.log(`[ExGuardRealtime] Subscribed to channel: ${channel}`);\n }\n }\n\n /**\n * Disconnect from realtime server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n }\n\n /**\n * Subscribe to realtime events\n * Use '*' as eventType to receive ALL 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 () => {\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 * Subscribe to ALL realtime events (wildcard)\n */\n subscribeAll(handler: RealtimeEventHandler): () => void {\n return this.subscribe('*', handler);\n }\n\n /**\n * Handle incoming realtime events\n */\n private handleEvent(event: RealtimeEvent): void {\n console.log('[ExGuardRealtime] Received event:', event);\n \n // Call specific event handlers\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 // Call wildcard handlers for ALL events\n const wildcardHandlers = this.handlers.get('*');\n if (wildcardHandlers) {\n wildcardHandlers.forEach(handler => {\n try {\n handler(event);\n } catch (error) {\n console.error('[ExGuardRealtime] Wildcard handler error:', error);\n }\n });\n }\n }\n\n /**\n * Handle reconnection logic\n */\n private handleReconnect(): void {\n if (!this.shouldReconnect || !this.config.autoReconnect || !this.currentUrl) {\n return;\n }\n\n if (this.reconnectAttempts < this.config.maxReconnectAttempts) {\n this.reconnectAttempts++;\n const delay = Math.min(\n this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),\n this.config.reconnectMaxDelay\n );\n \n console.log(`[ExGuardRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);\n \n setTimeout(() => {\n this.connect(this.currentUrl!, this.currentToken!, this.currentUserId!).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 * Manually trigger reconnection with current auth\n */\n reconnect(): Promise<void> {\n if (this.currentUrl && this.currentToken) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl, this.currentToken, this.currentUserId || undefined);\n } else if (this.currentUrl) {\n this.reconnectAttempts = 0;\n return this.connect(this.currentUrl);\n }\n return Promise.reject(new Error('No URL configured'));\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.socket?.connected ?? false;\n }\n\n /**\n * Get connection status\n */\n getStatus(): 'connecting' | 'connected' | 'disconnected' | 'reconnecting' {\n if (!this.socket) return 'disconnected';\n if (this.socket.connected) return 'connected';\n return 'disconnected';\n }\n\n /**\n * Send a message to the server\n */\n send(event: string, data: any): void {\n if (this.socket?.connected) {\n this.socket.emit(event, data);\n }\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ExGuardRealtimeConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n };\n }\n\n /**\n * Connect on-demand with user's access token from request\n * Call this in your guard or middleware with the user's token\n */\n async connectWithUserToken(url: string, accessToken: string, userId?: string): Promise<void> {\n try {\n await this.connect(url, accessToken, userId);\n } catch (error) {\n console.warn('[ExGuardRealtime] Failed to connect with user token:', error);\n }\n }\n}\n\n// Factory function for creating realtime instance\nexport function createRealtime(config?: ExGuardRealtimeConfig): ExGuardRealtime {\n return new ExGuardRealtime(config);\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,MAC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