@eminuckan/spine 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +45 -6
  3. package/dist/access/evaluator.d.ts +3 -0
  4. package/dist/access/evaluator.d.ts.map +1 -0
  5. package/dist/access/index.d.ts +3 -0
  6. package/dist/access/index.d.ts.map +1 -0
  7. package/dist/access/index.js +4 -0
  8. package/dist/access/types.d.ts +30 -0
  9. package/dist/access/types.d.ts.map +1 -0
  10. package/dist/access-DlAqsVGQ.js +59 -0
  11. package/dist/access-DlAqsVGQ.js.map +1 -0
  12. package/dist/api-client/index.js +2 -2
  13. package/dist/api-client/server.js +3 -3
  14. package/dist/{api-client-DsrxK05Z.js → api-client-CZapXIF8.js} +1 -1
  15. package/dist/{api-client-DsrxK05Z.js.map → api-client-CZapXIF8.js.map} +1 -1
  16. package/dist/auth/auth.server.d.ts +21 -16
  17. package/dist/auth/auth.server.d.ts.map +1 -1
  18. package/dist/auth/index.d.ts +1 -1
  19. package/dist/auth/index.d.ts.map +1 -1
  20. package/dist/auth/redis-session-storage.server.d.ts +18 -1
  21. package/dist/auth/redis-session-storage.server.d.ts.map +1 -1
  22. package/dist/auth/route-protection.server.d.ts.map +1 -1
  23. package/dist/auth/server.d.ts +1 -1
  24. package/dist/auth/server.d.ts.map +1 -1
  25. package/dist/auth/server.js +4 -4
  26. package/dist/auth/types.d.ts +65 -20
  27. package/dist/auth/types.d.ts.map +1 -1
  28. package/dist/auth.server-B3ODGIX4.js +1057 -0
  29. package/dist/auth.server-B3ODGIX4.js.map +1 -0
  30. package/dist/auth.server-wdKsjQsn.js +5 -0
  31. package/dist/identity/index.js +1 -1
  32. package/dist/identity/server.js +2 -2
  33. package/dist/{identity-CFa1txoj.js → identity-yT2ijZF0.js} +1 -1
  34. package/dist/{identity-CFa1txoj.js.map → identity-yT2ijZF0.js.map} +1 -1
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +11 -9
  38. package/dist/permission-service-CvGpwI0d.js +95 -0
  39. package/dist/permission-service-CvGpwI0d.js.map +1 -0
  40. package/dist/permissions/index.js +2 -1
  41. package/dist/{permissions-D5ScGGnd.js → permissions-OUK8Eql2.js} +3 -95
  42. package/dist/permissions-OUK8Eql2.js.map +1 -0
  43. package/dist/query-client/index.js +1 -1
  44. package/dist/{query-client-Bpe08pk9.js → query-client-Bh3TyB8W.js} +2 -2
  45. package/dist/query-client-Bh3TyB8W.js.map +1 -0
  46. package/dist/react-router/index.js +11 -9
  47. package/dist/react-router/server.js +18 -16
  48. package/dist/redis-session-storage.server-D0-72FV-.js +500 -0
  49. package/dist/redis-session-storage.server-D0-72FV-.js.map +1 -0
  50. package/dist/{server-BHfKHKF_.js → server-B7JN86_0.js} +13 -9
  51. package/dist/server-B7JN86_0.js.map +1 -0
  52. package/dist/{server-C3L8J7iE.js → server-BmiuV28c.js} +2 -2
  53. package/dist/{server-C3L8J7iE.js.map → server-BmiuV28c.js.map} +1 -1
  54. package/dist/{server-BxvRxjCK.js → server-Ce9jQRdL.js} +2 -2
  55. package/dist/{server-BxvRxjCK.js.map → server-Ce9jQRdL.js.map} +1 -1
  56. package/dist/{server-DZmcd2Lr.js → server-DeBlxoaW.js} +3 -3
  57. package/dist/{server-DZmcd2Lr.js.map → server-DeBlxoaW.js.map} +1 -1
  58. package/dist/{server-CouYoZiw.js → server-hGrElJMG.js} +2 -2
  59. package/dist/{server-CouYoZiw.js.map → server-hGrElJMG.js.map} +1 -1
  60. package/dist/server.js +18 -16
  61. package/dist/signalr/index.js +1 -1
  62. package/dist/{signalr-SJ-1sIxw.js → signalr-CSfCz1Ik.js} +1 -1
  63. package/dist/{signalr-SJ-1sIxw.js.map → signalr-CSfCz1Ik.js.map} +1 -1
  64. package/dist/tenant/index.js +1 -1
  65. package/dist/tenant/server.js +2 -2
  66. package/dist/{tenant-C6KPaSCX.js → tenant-BErqEENp.js} +1 -1
  67. package/dist/{tenant-C6KPaSCX.js.map → tenant-BErqEENp.js.map} +1 -1
  68. package/dist/{types-BnKaWdfe.js → types-BaaE6wjY.js} +1 -1
  69. package/dist/{types-BnKaWdfe.js.map → types-BaaE6wjY.js.map} +1 -1
  70. package/package.json +7 -2
  71. package/dist/auth.server-BPiCtlJE.js +0 -5
  72. package/dist/auth.server-Cx2h2qu3.js +0 -724
  73. package/dist/auth.server-Cx2h2qu3.js.map +0 -1
  74. package/dist/permissions-D5ScGGnd.js.map +0 -1
  75. package/dist/query-client-Bpe08pk9.js.map +0 -1
  76. package/dist/redis-session-storage.server-BR_0y-QO.js +0 -250
  77. package/dist/redis-session-storage.server-BR_0y-QO.js.map +0 -1
  78. package/dist/server-BHfKHKF_.js.map +0 -1
  79. /package/dist/{src-CJ2RLi94.js → src-B9rDUgSb.js} +0 -0
@@ -1,3 +1,3 @@
1
- import { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers } from "../query-client-Bpe08pk9.js";
1
+ import { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers } from "../query-client-Bh3TyB8W.js";
2
2
 
3
3
  export { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers };
@@ -38,7 +38,7 @@ function createDefaultLogoutHandler() {
38
38
  return (returnUrl) => {
39
39
  if (typeof window !== "undefined") {
40
40
  const currentUrl = returnUrl || window.location.pathname + window.location.search;
41
- window.location.href = `/auth/logout?returnUrl=${encodeURIComponent(currentUrl)}`;
41
+ window.location.href = `/auth/logout?logout=local&returnUrl=${encodeURIComponent(currentUrl)}`;
42
42
  }
43
43
  };
44
44
  }
@@ -171,4 +171,4 @@ const invalidationHelpers = {
171
171
 
172
172
  //#endregion
173
173
  export { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers };
174
- //# sourceMappingURL=query-client-Bpe08pk9.js.map
174
+ //# sourceMappingURL=query-client-Bh3TyB8W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-client-Bh3TyB8W.js","names":["DEFAULT_CONFIG: Required<Omit<QueryClientConfig, 'logger' | 'onLogout'>>","error: unknown","returnUrl?: string","config: QueryClientConfig","cachePresets: CachePresets","module: T","filters?: Record<string, unknown>","id: string","queryClient: QueryClient","module: string","queryKey: readonly unknown[]"],"sources":["../src/query-client/query-config.ts"],"sourcesContent":["/**\n * Query Client Configuration\n * \n * Optimized caching strategy for different types of data:\n * - Static data (rarely changes): Long staleTime and gcTime\n * - Dynamic data (changes frequently): Short staleTime\n * - Critical data (needs to be fresh): Very short staleTime with prefetching\n */\n\nimport { QueryClient, QueryCache, MutationCache } from '@tanstack/react-query';\nimport type { QueryClientConfig, CachePresets } from './types';\n\n/**\n * Default configuration\n */\nconst DEFAULT_CONFIG: Required<Omit<QueryClientConfig, 'logger' | 'onLogout'>> = {\n staleTime: 5 * 60 * 1000, // 5 minutes\n gcTime: 10 * 60 * 1000, // 10 minutes\n maxRetries: 3,\n maxMutationRetries: 1,\n refetchOnWindowFocus: true,\n refetchOnReconnect: false,\n refetchOnMount: false,\n};\n\n/**\n * Check if error is a 401 Unauthorized error\n */\nfunction is401Error(error: unknown): boolean {\n if (error instanceof Response) {\n return error.status === 401;\n }\n\n if (error && typeof error === 'object' && 'status' in error) {\n return (error as any).status === 401;\n }\n\n return false;\n}\n\n/**\n * Check if error requires logout (refresh token expired)\n */\nfunction shouldLogout(error: unknown): boolean {\n if (error && typeof error === 'object') {\n // Check for shouldLogout flag from server\n if ('shouldLogout' in error && (error as any).shouldLogout === true) {\n return true;\n }\n\n // Check for SESSION_EXPIRED code\n if ('code' in error && (error as any).code === 'SESSION_EXPIRED') {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Create default logout handler\n */\nfunction createDefaultLogoutHandler(): (returnUrl?: string) => void {\n return (returnUrl?: string) => {\n if (typeof window !== 'undefined') {\n const currentUrl = returnUrl || window.location.pathname + window.location.search;\n window.location.href = `/auth/logout?logout=local&returnUrl=${encodeURIComponent(currentUrl)}`;\n }\n };\n}\n\n/**\n * Create optimized QueryClient instance\n * \n * @param config - Configuration options\n * @returns Configured QueryClient with optimized defaults\n */\nexport function createQueryClient(config: QueryClientConfig = {}): QueryClient {\n const {\n staleTime,\n gcTime,\n maxRetries,\n maxMutationRetries,\n refetchOnWindowFocus,\n refetchOnReconnect,\n refetchOnMount,\n logger,\n onLogout,\n } = { ...DEFAULT_CONFIG, ...config };\n\n const handleLogout = onLogout || createDefaultLogoutHandler();\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime,\n gcTime,\n retry: (failureCount, error) => {\n // Don't retry 401 errors - the fetch client handles refresh flows separately\n if (is401Error(error)) {\n logger?.debug?.('Query failed with 401, not retrying');\n return false;\n }\n return failureCount < maxRetries;\n },\n retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),\n refetchOnWindowFocus,\n refetchOnReconnect,\n refetchOnMount,\n },\n mutations: {\n retry: (failureCount, error) => {\n if (is401Error(error)) {\n logger?.debug?.('Mutation failed with 401, not retrying');\n return false;\n }\n return failureCount < maxMutationRetries;\n },\n retryDelay: 1000,\n },\n },\n queryCache: new QueryCache({\n onError: (error) => {\n if (shouldLogout(error)) {\n handleLogout();\n return;\n }\n logger?.error?.('Query error', error instanceof Error ? error : undefined, {\n is401: is401Error(error),\n });\n },\n }),\n mutationCache: new MutationCache({\n onError: (error) => {\n if (shouldLogout(error)) {\n handleLogout();\n return;\n }\n logger?.error?.('Mutation error', error instanceof Error ? error : undefined, {\n is401: is401Error(error),\n });\n },\n }),\n });\n\n return queryClient;\n}\n\n/**\n * Cache Presets for different data types\n * \n * Use these presets for consistent caching across the application.\n */\nexport const cachePresets: CachePresets = {\n /**\n * Static data - rarely changes\n * Good for: permissions, roles, system settings\n */\n static: {\n staleTime: 30 * 60 * 1000, // 30 minutes\n gcTime: 60 * 60 * 1000, // 1 hour\n refetchOnWindowFocus: false,\n },\n\n /**\n * Normal data - changes occasionally\n * Good for: properties, users, organizations\n */\n normal: {\n staleTime: 5 * 60 * 1000, // 5 minutes\n gcTime: 10 * 60 * 1000, // 10 minutes\n refetchOnWindowFocus: true,\n },\n\n /**\n * Dynamic data - changes frequently\n * Good for: transactions, activities, notifications\n */\n dynamic: {\n staleTime: 1 * 60 * 1000, // 1 minute\n gcTime: 5 * 60 * 1000, // 5 minutes\n refetchOnWindowFocus: true,\n },\n\n /**\n * Realtime data - always fresh\n * Good for: live status, counters, dashboards\n */\n realtime: {\n staleTime: 0, // Always stale\n gcTime: 1 * 60 * 1000, // 1 minute\n refetchOnWindowFocus: true,\n },\n};\n\n/**\n * Create base query keys for a module\n */\nexport function createQueryKeyFactory<T extends string>(\n module: T\n): {\n all: readonly [T];\n lists: () => readonly [T, 'list'];\n list: (filters?: Record<string, unknown>) => readonly [T, 'list', Record<string, unknown>?];\n details: () => readonly [T, 'detail'];\n detail: (id: string) => readonly [T, 'detail', string];\n} {\n return {\n all: [module] as const,\n lists: () => [module, 'list'] as const,\n list: (filters?: Record<string, unknown>) => [module, 'list', filters] as const,\n details: () => [module, 'detail'] as const,\n detail: (id: string) => [module, 'detail', id] as const,\n };\n}\n\n/**\n * Invalidation helpers for common patterns\n */\nexport const invalidationHelpers = {\n /**\n * Invalidate all queries for a module\n */\n invalidateModule: async (queryClient: QueryClient, module: string): Promise<void> => {\n await queryClient.invalidateQueries({ queryKey: [module] });\n },\n\n /**\n * Invalidate all list queries for a module\n */\n invalidateLists: async (queryClient: QueryClient, module: string): Promise<void> => {\n await queryClient.invalidateQueries({ queryKey: [module, 'list'] });\n },\n\n /**\n * Invalidate a specific detail query\n */\n invalidateDetail: async (\n queryClient: QueryClient,\n module: string,\n id: string\n ): Promise<void> => {\n await queryClient.invalidateQueries({ queryKey: [module, 'detail', id] });\n },\n\n /**\n * Invalidate and refetch (useful for critical data)\n */\n invalidateAndRefetch: async (queryClient: QueryClient, queryKey: readonly unknown[]): Promise<void> => {\n await queryClient.invalidateQueries({ queryKey });\n await queryClient.refetchQueries({ queryKey });\n },\n};\n"],"mappings":"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"}
@@ -1,11 +1,13 @@
1
1
  import { LOG_LEVEL_PRIORITY, LogLevel, Logger, createLogger, defaultLoggerConfig, logger } from "../logging-_h2mi3L9.js";
2
- import { PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, getPermissionChecker, getPermissions, initializePermissions, useAllPermissions, useHasModulePermission, useHasPermission, useHasPermissions, useModulePermission, usePermission, usePermissionChecker, usePermissionStore, usePermissions } from "../permissions-D5ScGGnd.js";
3
- import { TenantProvider, configureTenantEndpoints, initializeTenantStore, useCurrentOrganization, useCurrentTenant, useOrganization, useTenant, useTenantStore, useTenantSwitcher } from "../tenant-C6KPaSCX.js";
4
- import { IdentityContextProvider, configureIdentityEndpoints, configureIdentityStore, resetIdentityStoreConfig, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useUserPermissions, useUserTenants } from "../identity-CFa1txoj.js";
5
- import { isApiClientError } from "../types-BnKaWdfe.js";
6
- import { ApiError, ErrorCodes, ErrorHandler, calculateBackoffDelay, createRetryFetch, fetchWithTimeout, handleApiError, isRetryableError, withRetry } from "../api-client-DsrxK05Z.js";
7
- import { IdentitySignalRClient, SignalRClient, cleanupSignalR, createIdentitySignalRClient, getIdentitySignalRClient, initializeSignalR } from "../signalr-SJ-1sIxw.js";
8
- import { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers } from "../query-client-Bpe08pk9.js";
9
- import "../src-CJ2RLi94.js";
2
+ import { PermissionChecker } from "../permission-service-CvGpwI0d.js";
3
+ import { PERMISSION_MODULES, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, getPermissionChecker, getPermissions, initializePermissions, useAllPermissions, useHasModulePermission, useHasPermission, useHasPermissions, useModulePermission, usePermission, usePermissionChecker, usePermissionStore, usePermissions } from "../permissions-OUK8Eql2.js";
4
+ import { evaluateAccessRequirement } from "../access-DlAqsVGQ.js";
5
+ import { TenantProvider, configureTenantEndpoints, initializeTenantStore, useCurrentOrganization, useCurrentTenant, useOrganization, useTenant, useTenantStore, useTenantSwitcher } from "../tenant-BErqEENp.js";
6
+ import { IdentityContextProvider, configureIdentityEndpoints, configureIdentityStore, resetIdentityStoreConfig, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useUserPermissions, useUserTenants } from "../identity-yT2ijZF0.js";
7
+ import { isApiClientError } from "../types-BaaE6wjY.js";
8
+ import { ApiError, ErrorCodes, ErrorHandler, calculateBackoffDelay, createRetryFetch, fetchWithTimeout, handleApiError, isRetryableError, withRetry } from "../api-client-CZapXIF8.js";
9
+ import { IdentitySignalRClient, SignalRClient, cleanupSignalR, createIdentitySignalRClient, getIdentitySignalRClient, initializeSignalR } from "../signalr-CSfCz1Ik.js";
10
+ import { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers } from "../query-client-Bh3TyB8W.js";
11
+ import "../src-B9rDUgSb.js";
10
12
 
11
- export { ApiError, ErrorCodes, ErrorHandler, IdentityContextProvider, IdentitySignalRClient, LOG_LEVEL_PRIORITY, LogLevel, Logger, PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, SignalRClient, TenantProvider, cachePresets, calculateBackoffDelay, cleanupSignalR, configureIdentityEndpoints, configureIdentityStore, configureTenantEndpoints, createIdentitySignalRClient, createLogger, createQueryClient, createQueryKeyFactory, createRetryFetch, defaultLoggerConfig, fetchWithTimeout, getIdentitySignalRClient, getPermissionChecker, getPermissions, handleApiError, initializePermissions, initializeSignalR, initializeTenantStore, invalidationHelpers, isApiClientError, isRetryableError, logger, resetIdentityStoreConfig, useAllPermissions, useCurrentOrganization, useCurrentTenant, useHasModulePermission, useHasPermission, useHasPermissions, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useModulePermission, useOrganization, usePermission, usePermissionChecker, usePermissionStore, usePermissions, useTenant, useTenantStore, useTenantSwitcher, useUserPermissions, useUserTenants, withRetry };
13
+ export { ApiError, ErrorCodes, ErrorHandler, IdentityContextProvider, IdentitySignalRClient, LOG_LEVEL_PRIORITY, LogLevel, Logger, PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, SignalRClient, TenantProvider, cachePresets, calculateBackoffDelay, cleanupSignalR, configureIdentityEndpoints, configureIdentityStore, configureTenantEndpoints, createIdentitySignalRClient, createLogger, createQueryClient, createQueryKeyFactory, createRetryFetch, defaultLoggerConfig, evaluateAccessRequirement, fetchWithTimeout, getIdentitySignalRClient, getPermissionChecker, getPermissions, handleApiError, initializePermissions, initializeSignalR, initializeTenantStore, invalidationHelpers, isApiClientError, isRetryableError, logger, resetIdentityStoreConfig, useAllPermissions, useCurrentOrganization, useCurrentTenant, useHasModulePermission, useHasPermission, useHasPermissions, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useModulePermission, useOrganization, usePermission, usePermissionChecker, usePermissionStore, usePermissions, useTenant, useTenantStore, useTenantSwitcher, useUserPermissions, useUserTenants, withRetry };
@@ -1,18 +1,20 @@
1
1
  import { LOG_LEVEL_PRIORITY, LogLevel, Logger, createLogger, defaultLoggerConfig, logger } from "../logging-_h2mi3L9.js";
2
- import { PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, getPermissionChecker, getPermissions, initializePermissions, useAllPermissions, useHasModulePermission, useHasPermission, useHasPermissions, useModulePermission, usePermission, usePermissionChecker, usePermissionStore, usePermissions } from "../permissions-D5ScGGnd.js";
3
- import { TenantProvider, configureTenantEndpoints, initializeTenantStore, useCurrentOrganization, useCurrentTenant, useOrganization, useTenant, useTenantStore, useTenantSwitcher } from "../tenant-C6KPaSCX.js";
4
- import { IdentityContextProvider, configureIdentityEndpoints, configureIdentityStore, resetIdentityStoreConfig, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useUserPermissions, useUserTenants } from "../identity-CFa1txoj.js";
5
- import { isApiClientError } from "../types-BnKaWdfe.js";
6
- import { ApiError, ErrorCodes, ErrorHandler, calculateBackoffDelay, createRetryFetch, fetchWithTimeout, handleApiError, isRetryableError, withRetry } from "../api-client-DsrxK05Z.js";
7
- import { IdentitySignalRClient, SignalRClient, cleanupSignalR, createIdentitySignalRClient, getIdentitySignalRClient, initializeSignalR } from "../signalr-SJ-1sIxw.js";
8
- import { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers } from "../query-client-Bpe08pk9.js";
9
- import "../src-CJ2RLi94.js";
10
- import { AUTH_ERROR_COOKIE_PREFIX, cleanupExpiredOAuthStates, closeRedisConnection, createAuthSession, createOAuthState, deleteOAuthState, destroyAuthSession, getAuthSession, getOAuthState, isSessionValid, requireAuthSession, updateAuthSession } from "../redis-session-storage.server-BR_0y-QO.js";
11
- import { clearAuthErrorHeaders, clearAuthServerCache, configureAuthClaimMapping, extractUserInfo, getAccessToken, getAuthError, getUser, handleCallback, hasAuthError, login, logout, refreshTokens, requireAuth, resetAuthClaimMapping } from "../auth.server-Cx2h2qu3.js";
12
- import { attemptTokenRefresh, authRoute, configureRouteProtection, isTokenExpiredResponse, onboardingRoute, protectRoute, publicRoute, resetRouteProtectionConfig, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute } from "../server-BHfKHKF_.js";
13
- import { clearActiveTenant, clearCurrentTenant, configureIdentityContextFetcher, configureTenantCookie, getActiveTenant, getAvailableTenants, getCurrentTenant, getTenantFromIdentityContext, initializeTenant, resetTenantCookieConfig, setActiveTenant, setCurrentTenant } from "../server-BxvRxjCK.js";
14
- import { clearIdentityContextCache, configureIdentityAPIFetcher, configurePermissionFetcher, contextToUserInfo, fetchIdentityContext, fetchUserPermissions, getIdentityContext, hasContextVersionChanged, updateContextVersion } from "../server-C3L8J7iE.js";
15
- import { checkPermission, configurePermissionRouteProtection, requirePermission, resetPermissionRouteProtection, withPermission } from "../server-CouYoZiw.js";
16
- import { createAPIConfigFactory, createApiClient, createFetchMiddleware } from "../server-DZmcd2Lr.js";
2
+ import { PermissionChecker } from "../permission-service-CvGpwI0d.js";
3
+ import { PERMISSION_MODULES, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, getPermissionChecker, getPermissions, initializePermissions, useAllPermissions, useHasModulePermission, useHasPermission, useHasPermissions, useModulePermission, usePermission, usePermissionChecker, usePermissionStore, usePermissions } from "../permissions-OUK8Eql2.js";
4
+ import { evaluateAccessRequirement } from "../access-DlAqsVGQ.js";
5
+ import { TenantProvider, configureTenantEndpoints, initializeTenantStore, useCurrentOrganization, useCurrentTenant, useOrganization, useTenant, useTenantStore, useTenantSwitcher } from "../tenant-BErqEENp.js";
6
+ import { IdentityContextProvider, configureIdentityEndpoints, configureIdentityStore, resetIdentityStoreConfig, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useUserPermissions, useUserTenants } from "../identity-yT2ijZF0.js";
7
+ import { isApiClientError } from "../types-BaaE6wjY.js";
8
+ import { ApiError, ErrorCodes, ErrorHandler, calculateBackoffDelay, createRetryFetch, fetchWithTimeout, handleApiError, isRetryableError, withRetry } from "../api-client-CZapXIF8.js";
9
+ import { IdentitySignalRClient, SignalRClient, cleanupSignalR, createIdentitySignalRClient, getIdentitySignalRClient, initializeSignalR } from "../signalr-CSfCz1Ik.js";
10
+ import { cachePresets, createQueryClient, createQueryKeyFactory, invalidationHelpers } from "../query-client-Bh3TyB8W.js";
11
+ import "../src-B9rDUgSb.js";
12
+ import { AUTH_ERROR_COOKIE_PREFIX, cleanupExpiredOAuthStates, closeRedisConnection, createAuthSession, createOAuthState, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, getAuthSession, getAuthSessionById, getCurrentAuthSessionId, getOAuthState, isSessionValid, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, requireAuthSession, updateAuthSession } from "../redis-session-storage.server-D0-72FV-.js";
13
+ import { clearAuthErrorHeaders, clearAuthServerCache, configureAuthClaimMapping, extractUserInfo, getAccessToken, getAuthError, getUser, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, login, logout, refreshTokens, requireAuth, resetAuthClaimMapping } from "../auth.server-B3ODGIX4.js";
14
+ import { attemptTokenRefresh, authRoute, configureRouteProtection, isTokenExpiredResponse, onboardingRoute, protectRoute, publicRoute, resetRouteProtectionConfig, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute } from "../server-B7JN86_0.js";
15
+ import { clearActiveTenant, clearCurrentTenant, configureIdentityContextFetcher, configureTenantCookie, getActiveTenant, getAvailableTenants, getCurrentTenant, getTenantFromIdentityContext, initializeTenant, resetTenantCookieConfig, setActiveTenant, setCurrentTenant } from "../server-Ce9jQRdL.js";
16
+ import { clearIdentityContextCache, configureIdentityAPIFetcher, configurePermissionFetcher, contextToUserInfo, fetchIdentityContext, fetchUserPermissions, getIdentityContext, hasContextVersionChanged, updateContextVersion } from "../server-BmiuV28c.js";
17
+ import { checkPermission, configurePermissionRouteProtection, requirePermission, resetPermissionRouteProtection, withPermission } from "../server-hGrElJMG.js";
18
+ import { createAPIConfigFactory, createApiClient, createFetchMiddleware } from "../server-DeBlxoaW.js";
17
19
 
18
- export { AUTH_ERROR_COOKIE_PREFIX, ApiError, ErrorCodes, ErrorHandler, IdentityContextProvider, IdentitySignalRClient, LOG_LEVEL_PRIORITY, LogLevel, Logger, PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, SignalRClient, TenantProvider, attemptTokenRefresh, authRoute, cachePresets, calculateBackoffDelay, checkPermission, cleanupExpiredOAuthStates, cleanupSignalR, clearActiveTenant, clearAuthErrorHeaders, clearAuthServerCache, clearCurrentTenant, clearIdentityContextCache, closeRedisConnection, configureAuthClaimMapping, configureIdentityAPIFetcher, configureIdentityContextFetcher, configureIdentityEndpoints, configureIdentityStore, configurePermissionFetcher, configurePermissionRouteProtection, configureRouteProtection, configureTenantCookie, configureTenantEndpoints, contextToUserInfo, createAPIConfigFactory, createApiClient, createAuthSession, createFetchMiddleware, createIdentitySignalRClient, createLogger, createOAuthState, createQueryClient, createQueryKeyFactory, createRetryFetch, defaultLoggerConfig, deleteOAuthState, destroyAuthSession, extractUserInfo, fetchIdentityContext, fetchUserPermissions, fetchWithTimeout, getAccessToken, getActiveTenant, getAuthError, getAuthSession, getAvailableTenants, getCurrentTenant, getIdentityContext, getIdentitySignalRClient, getOAuthState, getPermissionChecker, getPermissions, getTenantFromIdentityContext, getUser, handleApiError, handleCallback, hasAuthError, hasContextVersionChanged, initializePermissions, initializeSignalR, initializeTenant, initializeTenantStore, invalidationHelpers, isApiClientError, isRetryableError, isSessionValid, isTokenExpiredResponse, logger, login, logout, onboardingRoute, protectRoute, publicRoute, refreshTokens, requireAuth, requireAuthSession, requirePermission, resetAuthClaimMapping, resetIdentityStoreConfig, resetPermissionRouteProtection, resetRouteProtectionConfig, resetTenantCookieConfig, setActiveTenant, setCurrentTenant, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute, updateAuthSession, updateContextVersion, useAllPermissions, useCurrentOrganization, useCurrentTenant, useHasModulePermission, useHasPermission, useHasPermissions, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useModulePermission, useOrganization, usePermission, usePermissionChecker, usePermissionStore, usePermissions, useTenant, useTenantStore, useTenantSwitcher, useUserPermissions, useUserTenants, withPermission, withRetry };
20
+ export { AUTH_ERROR_COOKIE_PREFIX, ApiError, ErrorCodes, ErrorHandler, IdentityContextProvider, IdentitySignalRClient, LOG_LEVEL_PRIORITY, LogLevel, Logger, PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, SignalRClient, TenantProvider, attemptTokenRefresh, authRoute, cachePresets, calculateBackoffDelay, checkPermission, cleanupExpiredOAuthStates, cleanupSignalR, clearActiveTenant, clearAuthErrorHeaders, clearAuthServerCache, clearCurrentTenant, clearIdentityContextCache, closeRedisConnection, configureAuthClaimMapping, configureIdentityAPIFetcher, configureIdentityContextFetcher, configureIdentityEndpoints, configureIdentityStore, configurePermissionFetcher, configurePermissionRouteProtection, configureRouteProtection, configureTenantCookie, configureTenantEndpoints, contextToUserInfo, createAPIConfigFactory, createApiClient, createAuthSession, createFetchMiddleware, createIdentitySignalRClient, createLogger, createOAuthState, createQueryClient, createQueryKeyFactory, createRetryFetch, defaultLoggerConfig, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, evaluateAccessRequirement, extractUserInfo, fetchIdentityContext, fetchUserPermissions, fetchWithTimeout, getAccessToken, getActiveTenant, getAuthError, getAuthSession, getAuthSessionById, getAvailableTenants, getCurrentAuthSessionId, getCurrentTenant, getIdentityContext, getIdentitySignalRClient, getOAuthState, getPermissionChecker, getPermissions, getTenantFromIdentityContext, getUser, handleApiError, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, hasContextVersionChanged, initializePermissions, initializeSignalR, initializeTenant, initializeTenantStore, invalidationHelpers, isApiClientError, isRetryableError, isSessionValid, isTokenExpiredResponse, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, logger, login, logout, onboardingRoute, protectRoute, publicRoute, refreshTokens, requireAuth, requireAuthSession, requirePermission, resetAuthClaimMapping, resetIdentityStoreConfig, resetPermissionRouteProtection, resetRouteProtectionConfig, resetTenantCookieConfig, setActiveTenant, setCurrentTenant, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute, updateAuthSession, updateContextVersion, useAllPermissions, useCurrentOrganization, useCurrentTenant, useHasModulePermission, useHasPermission, useHasPermissions, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useModulePermission, useOrganization, usePermission, usePermissionChecker, usePermissionStore, usePermissions, useTenant, useTenantStore, useTenantSwitcher, useUserPermissions, useUserTenants, withPermission, withRetry };
@@ -0,0 +1,500 @@
1
+ import { logger } from "./logging-_h2mi3L9.js";
2
+ import Redis from "ioredis";
3
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
4
+
5
+ //#region src/auth/redis-session-storage.server.ts
6
+ let redis = null;
7
+ function getRedis() {
8
+ if (!redis) {
9
+ redis = new Redis(process.env.REDIS_URL || "redis://localhost:6379");
10
+ redis.on("error", (err) => {
11
+ logger.error("Redis Client Error", err);
12
+ });
13
+ redis.on("connect", () => {
14
+ logger.info("Redis connected successfully");
15
+ });
16
+ }
17
+ return redis;
18
+ }
19
+ const KEY_PREFIX = process.env.REDIS_KEY_PREFIX || "";
20
+ const REDIS_KEYS = {
21
+ oauthState: (stateId) => `${KEY_PREFIX}oauth:state:${stateId}`,
22
+ session: (sessionId) => `${KEY_PREFIX}session:${sessionId}`,
23
+ sessionByUser: (userId) => `${KEY_PREFIX}session:index:user:${userId}`,
24
+ sessionBySid: (sid) => `${KEY_PREFIX}session:index:sid:${sid}`,
25
+ sessionBySessionState: (sessionState) => `${KEY_PREFIX}session:index:session_state:${sessionState}`
26
+ };
27
+ const DEFAULT_SESSION_SECRET = "default-secret-change-in-production";
28
+ const DEFAULT_SESSION_TTL = 60 * 60 * 24 * 7;
29
+ const DEFAULT_OAUTH_STATE_TTL = 10 * 60;
30
+ const OAUTH_STATE_TTL = resolvePositiveIntegerEnv("OAUTH_STATE_TTL", DEFAULT_OAUTH_STATE_TTL);
31
+ const SESSION_TTL = resolvePositiveIntegerEnv("SESSION_DEFAULT_TTL", resolvePositiveIntegerEnv("SESSION_TTL", DEFAULT_SESSION_TTL));
32
+ const SESSION_COOKIE_NAME = process.env.SESSION_COOKIE_NAME || "__session_id";
33
+ const SESSION_SECRET = resolveSessionSecret();
34
+ const SESSION_COOKIE_SECURE = resolveCookieSecure();
35
+ const SESSION_COOKIE_PATH = "/";
36
+ const SESSION_COOKIE_SAME_SITE = resolveCookieSameSite();
37
+ const SESSION_COOKIE_DOMAIN = process.env.SESSION_COOKIE_DOMAIN?.trim();
38
+ const SESSION_ENCRYPTION_ENABLED = resolveSessionEncryptionEnabled();
39
+ const SESSION_ENCRYPTION_KEY = resolveSessionEncryptionKey(SESSION_ENCRYPTION_ENABLED);
40
+ const AUTH_ERROR_COOKIE_PREFIX = SESSION_COOKIE_NAME.replace("_session", "").replace("__", "");
41
+ function resolveBooleanEnv(name, defaultValue) {
42
+ const value = process.env[name]?.trim().toLowerCase();
43
+ if (!value) return defaultValue;
44
+ if ([
45
+ "1",
46
+ "true",
47
+ "yes",
48
+ "on"
49
+ ].includes(value)) return true;
50
+ if ([
51
+ "0",
52
+ "false",
53
+ "no",
54
+ "off"
55
+ ].includes(value)) return false;
56
+ throw new Error(`${name} must be a boolean value.`);
57
+ }
58
+ function resolvePositiveIntegerEnv(name, defaultValue) {
59
+ const value = process.env[name]?.trim();
60
+ if (!value) return defaultValue;
61
+ const parsed = Number(value);
62
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${name} must be a positive integer.`);
63
+ return parsed;
64
+ }
65
+ function resolveSessionSecret() {
66
+ const secret = process.env.SESSION_SECRET?.trim();
67
+ if (!secret || secret === DEFAULT_SESSION_SECRET) {
68
+ if (process.env.NODE_ENV === "production") throw new Error("SESSION_SECRET must be set to a unique random value in production.");
69
+ return DEFAULT_SESSION_SECRET;
70
+ }
71
+ if (secret.length < 32) throw new Error("SESSION_SECRET must be at least 32 characters long.");
72
+ return secret;
73
+ }
74
+ function resolveCookieSecure() {
75
+ return resolveBooleanEnv("SESSION_COOKIE_SECURE", process.env.NODE_ENV === "production");
76
+ }
77
+ function resolveCookieSameSite() {
78
+ const value = process.env.SESSION_COOKIE_SAME_SITE?.trim().toLowerCase();
79
+ const sameSite = value === "strict" ? "Strict" : value === "none" ? "None" : "Lax";
80
+ if (sameSite === "None" && !SESSION_COOKIE_SECURE) throw new Error("SESSION_COOKIE_SAME_SITE=None requires SESSION_COOKIE_SECURE=true.");
81
+ return sameSite;
82
+ }
83
+ function resolveSessionEncryptionEnabled() {
84
+ const enabled = resolveBooleanEnv("SESSION_ENCRYPTION", process.env.NODE_ENV === "production");
85
+ if (process.env.NODE_ENV === "production" && !enabled) throw new Error("SESSION_ENCRYPTION cannot be disabled in production.");
86
+ return enabled;
87
+ }
88
+ function decodeBase64Url(value) {
89
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
90
+ const padded = normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "=");
91
+ return Buffer.from(padded, "base64");
92
+ }
93
+ function resolveSessionEncryptionKey(enabled) {
94
+ if (!enabled) return null;
95
+ const value = process.env.SESSION_ENCRYPTION_KEY?.trim();
96
+ if (!value) throw new Error("SESSION_ENCRYPTION_KEY is required when session encryption is enabled.");
97
+ const key = /^[0-9a-f]{64}$/i.test(value) ? Buffer.from(value, "hex") : decodeBase64Url(value);
98
+ if (key.length !== 32) throw new Error("SESSION_ENCRYPTION_KEY must decode to exactly 32 bytes. Generate one with: openssl rand -base64 32");
99
+ return key;
100
+ }
101
+ function parseCookieHeader(cookieHeader) {
102
+ if (!cookieHeader) return {};
103
+ return cookieHeader.split(";").map((part) => part.trim()).filter(Boolean).reduce((cookies, part) => {
104
+ const separatorIndex = part.indexOf("=");
105
+ if (separatorIndex <= 0) return cookies;
106
+ const name = part.slice(0, separatorIndex).trim();
107
+ const value = part.slice(separatorIndex + 1).trim();
108
+ if (!name) return cookies;
109
+ cookies[name] = value;
110
+ return cookies;
111
+ }, {});
112
+ }
113
+ function createCookieSignature(value, secret) {
114
+ return createHmac("sha256", secret).update(value).digest("base64url");
115
+ }
116
+ function safelyCompareValues(left, right) {
117
+ const leftBuffer = Buffer.from(left);
118
+ const rightBuffer = Buffer.from(right);
119
+ if (leftBuffer.length !== rightBuffer.length) return false;
120
+ return timingSafeEqual(leftBuffer, rightBuffer);
121
+ }
122
+ function signSessionId(sessionId) {
123
+ const signature = createCookieSignature(sessionId, SESSION_SECRET);
124
+ return `${sessionId}.${signature}`;
125
+ }
126
+ function unsignSessionId(cookieValue) {
127
+ if (!cookieValue) return null;
128
+ let decodedValue;
129
+ try {
130
+ decodedValue = decodeURIComponent(cookieValue);
131
+ } catch {
132
+ return null;
133
+ }
134
+ const separatorIndex = decodedValue.lastIndexOf(".");
135
+ if (separatorIndex <= 0 || separatorIndex === decodedValue.length - 1) return null;
136
+ const sessionId = decodedValue.slice(0, separatorIndex);
137
+ const signature = decodedValue.slice(separatorIndex + 1);
138
+ const expectedSignature = createCookieSignature(sessionId, SESSION_SECRET);
139
+ return safelyCompareValues(signature, expectedSignature) ? sessionId : null;
140
+ }
141
+ function serializeSessionCookieValue(sessionId, options) {
142
+ const signedValue = encodeURIComponent(signSessionId(sessionId));
143
+ const segments = [
144
+ `${SESSION_COOKIE_NAME}=${signedValue}`,
145
+ `Max-Age=${options.maxAge}`,
146
+ `Path=${SESSION_COOKIE_PATH}`,
147
+ `SameSite=${SESSION_COOKIE_SAME_SITE}`,
148
+ "HttpOnly"
149
+ ];
150
+ if (SESSION_COOKIE_DOMAIN) segments.push(`Domain=${SESSION_COOKIE_DOMAIN}`);
151
+ if (SESSION_COOKIE_SECURE) segments.push("Secure");
152
+ return segments.join("; ");
153
+ }
154
+ function serializeExpiredSessionCookie() {
155
+ const segments = [
156
+ `${SESSION_COOKIE_NAME}=`,
157
+ "Max-Age=0",
158
+ `Path=${SESSION_COOKIE_PATH}`,
159
+ `SameSite=${SESSION_COOKIE_SAME_SITE}`,
160
+ "HttpOnly"
161
+ ];
162
+ if (SESSION_COOKIE_DOMAIN) segments.push(`Domain=${SESSION_COOKIE_DOMAIN}`);
163
+ if (SESSION_COOKIE_SECURE) segments.push("Secure");
164
+ return segments.join("; ");
165
+ }
166
+ async function getSessionIdFromRequest(request) {
167
+ const cookies = parseCookieHeader(request.headers.get("Cookie"));
168
+ return unsignSessionId(cookies[SESSION_COOKIE_NAME]);
169
+ }
170
+ function getSessionIndexKeys(data) {
171
+ const keys = new Set();
172
+ if (data.userId) keys.add(REDIS_KEYS.sessionByUser(data.userId));
173
+ if (data.sid) keys.add(REDIS_KEYS.sessionBySid(data.sid));
174
+ if (data.sessionState) keys.add(REDIS_KEYS.sessionBySessionState(data.sessionState));
175
+ return Array.from(keys);
176
+ }
177
+ async function registerSessionIndexes(sessionId, data) {
178
+ const indexKeys = getSessionIndexKeys(data);
179
+ if (indexKeys.length === 0) return;
180
+ const redisClient = getRedis();
181
+ const pipeline = redisClient.pipeline();
182
+ for (const indexKey of indexKeys) {
183
+ pipeline.sadd(indexKey, sessionId);
184
+ pipeline.expire(indexKey, SESSION_TTL);
185
+ }
186
+ await pipeline.exec();
187
+ }
188
+ async function unregisterSessionIndexes(sessionId, data) {
189
+ const indexKeys = getSessionIndexKeys(data);
190
+ if (indexKeys.length === 0) return;
191
+ const redisClient = getRedis();
192
+ const pipeline = redisClient.pipeline();
193
+ for (const indexKey of indexKeys) pipeline.srem(indexKey, sessionId);
194
+ await pipeline.exec();
195
+ }
196
+ function parseSessionData(sessionData) {
197
+ if (!sessionData) return null;
198
+ try {
199
+ return JSON.parse(decodeSessionData(sessionData));
200
+ } catch (error) {
201
+ logger.error("Failed to parse session data", error instanceof Error ? error : void 0);
202
+ return null;
203
+ }
204
+ }
205
+ function encodeSessionData(data) {
206
+ const plaintext = JSON.stringify(data);
207
+ if (!SESSION_ENCRYPTION_KEY) return plaintext;
208
+ const iv = randomBytes(12);
209
+ const cipher = createCipheriv("aes-256-gcm", SESSION_ENCRYPTION_KEY, iv);
210
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
211
+ const tag = cipher.getAuthTag();
212
+ return [
213
+ "enc:v1",
214
+ iv.toString("base64url"),
215
+ tag.toString("base64url"),
216
+ ciphertext.toString("base64url")
217
+ ].join(":");
218
+ }
219
+ function decodeSessionData(value) {
220
+ if (!value.startsWith("enc:v1:")) {
221
+ if (SESSION_ENCRYPTION_ENABLED) logger.warn("Reading legacy plaintext auth session payload while session encryption is enabled.");
222
+ return value;
223
+ }
224
+ if (!SESSION_ENCRYPTION_KEY) throw new Error("Cannot decrypt auth session payload because SESSION_ENCRYPTION_KEY is not configured.");
225
+ const [, version, ivValue, tagValue, ciphertextValue] = value.split(":");
226
+ if (version !== "v1" || !ivValue || !tagValue || !ciphertextValue) throw new Error("Invalid encrypted auth session payload format.");
227
+ const decipher = createDecipheriv("aes-256-gcm", SESSION_ENCRYPTION_KEY, Buffer.from(ivValue, "base64url"));
228
+ decipher.setAuthTag(Buffer.from(tagValue, "base64url"));
229
+ return Buffer.concat([decipher.update(Buffer.from(ciphertextValue, "base64url")), decipher.final()]).toString("utf8");
230
+ }
231
+ async function readSessionData(sessionId) {
232
+ try {
233
+ const sessionData = await getRedis().get(REDIS_KEYS.session(sessionId));
234
+ if (!sessionData) {
235
+ logger.debug("Session not found in Redis", { sessionId });
236
+ return null;
237
+ }
238
+ await getRedis().expire(REDIS_KEYS.session(sessionId), SESSION_TTL);
239
+ return parseSessionData(sessionData);
240
+ } catch (error) {
241
+ logger.error("Failed to read session from Redis", error instanceof Error ? error : void 0);
242
+ return null;
243
+ }
244
+ }
245
+ async function writeSessionData(sessionId, data) {
246
+ try {
247
+ const existingSessionData = parseSessionData(await getRedis().get(REDIS_KEYS.session(sessionId)));
248
+ if (existingSessionData) await unregisterSessionIndexes(sessionId, existingSessionData);
249
+ await getRedis().setex(REDIS_KEYS.session(sessionId), SESSION_TTL, encodeSessionData(data));
250
+ await registerSessionIndexes(sessionId, data);
251
+ logger.debug("Updated Redis session", { sessionId });
252
+ } catch (error) {
253
+ logger.error("Failed to update session in Redis", error instanceof Error ? error : void 0);
254
+ throw error;
255
+ }
256
+ }
257
+ async function deleteSessionData(sessionId) {
258
+ try {
259
+ const existingSessionData = parseSessionData(await getRedis().get(REDIS_KEYS.session(sessionId)));
260
+ if (existingSessionData) await unregisterSessionIndexes(sessionId, existingSessionData);
261
+ await getRedis().del(REDIS_KEYS.session(sessionId));
262
+ logger.debug("Deleted Redis session", { sessionId });
263
+ } catch (error) {
264
+ logger.error("Failed to delete session from Redis", error instanceof Error ? error : void 0);
265
+ }
266
+ }
267
+ function mergeSessionData(existingData, updates) {
268
+ const nextData = { ...existingData };
269
+ Object.entries(updates).forEach(([key, value]) => {
270
+ if (value === void 0) {
271
+ delete nextData[key];
272
+ return;
273
+ }
274
+ nextData[key] = value;
275
+ });
276
+ return nextData;
277
+ }
278
+ async function getSessionIdsFromIndex(indexKey) {
279
+ const sessionIds = await getRedis().smembers(indexKey);
280
+ const activeSessionIds = [];
281
+ const staleSessionIds = [];
282
+ for (const sessionId of sessionIds) {
283
+ const exists = await getRedis().exists(REDIS_KEYS.session(sessionId));
284
+ if (exists) activeSessionIds.push(sessionId);
285
+ else staleSessionIds.push(sessionId);
286
+ }
287
+ if (staleSessionIds.length > 0) await getRedis().srem(indexKey, ...staleSessionIds);
288
+ return activeSessionIds;
289
+ }
290
+ function toAuthSessionSummary(sessionId, session, currentSessionId) {
291
+ return {
292
+ sessionId,
293
+ userId: session.userId,
294
+ email: session.user?.email,
295
+ name: session.user?.name,
296
+ issuer: session.issuer,
297
+ sid: session.sid,
298
+ sessionState: session.sessionState,
299
+ clientId: session.clientId,
300
+ ipAddress: session.ipAddress,
301
+ userAgent: session.userAgent,
302
+ createdAt: session.createdAt,
303
+ lastActivity: session.lastActivity,
304
+ expiresAt: session.expiresAt,
305
+ isCurrent: currentSessionId ? sessionId === currentSessionId : void 0
306
+ };
307
+ }
308
+ async function listSessionDataByIds(sessionIds) {
309
+ const sessions = [];
310
+ for (const sessionId of sessionIds) {
311
+ const data = await readSessionData(sessionId);
312
+ if (data) sessions.push({
313
+ sessionId,
314
+ data
315
+ });
316
+ }
317
+ return sessions;
318
+ }
319
+ function getRequestIpAddress(request) {
320
+ const forwardedFor = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
321
+ return forwardedFor || request.headers.get("cf-connecting-ip")?.trim() || request.headers.get("x-real-ip")?.trim() || void 0;
322
+ }
323
+ async function createAuthSession(request, sessionData) {
324
+ const currentSessionId = await getSessionIdFromRequest(request);
325
+ const nextSessionId = crypto.randomUUID();
326
+ const nextSessionData = mergeSessionData({}, {
327
+ ...sessionData,
328
+ sessionId: nextSessionId,
329
+ ipAddress: sessionData.ipAddress ?? getRequestIpAddress(request),
330
+ userAgent: sessionData.userAgent ?? request.headers.get("user-agent") ?? void 0
331
+ });
332
+ logger.debug("Creating auth session", { dataKeys: Object.keys(sessionData) });
333
+ if (currentSessionId) await deleteSessionData(currentSessionId);
334
+ await writeSessionData(nextSessionId, nextSessionData);
335
+ return new Headers({ "Set-Cookie": serializeSessionCookieValue(nextSessionId, { maxAge: SESSION_TTL }) });
336
+ }
337
+ async function getAuthSession(request) {
338
+ const sessionId = await getSessionIdFromRequest(request);
339
+ if (!sessionId) return {};
340
+ const session = await readSessionData(sessionId);
341
+ if (!session) return {};
342
+ return {
343
+ sessionId,
344
+ userId: session.userId,
345
+ accessToken: session.accessToken,
346
+ refreshToken: session.refreshToken,
347
+ idToken: session.idToken,
348
+ expiresAt: session.expiresAt,
349
+ issuer: session.issuer,
350
+ sid: session.sid,
351
+ sessionState: session.sessionState,
352
+ clientId: session.clientId,
353
+ ipAddress: session.ipAddress,
354
+ userAgent: session.userAgent,
355
+ user: session.user,
356
+ createdAt: session.createdAt,
357
+ lastActivity: session.lastActivity
358
+ };
359
+ }
360
+ async function updateAuthSession(request, updates) {
361
+ const currentSessionId = await getSessionIdFromRequest(request);
362
+ const currentSessionData = currentSessionId ? await readSessionData(currentSessionId) ?? {} : {};
363
+ const nextSessionId = currentSessionId ?? crypto.randomUUID();
364
+ const nextSessionData = mergeSessionData(currentSessionData, {
365
+ ...updates,
366
+ sessionId: nextSessionId
367
+ });
368
+ await writeSessionData(nextSessionId, nextSessionData);
369
+ return new Headers({ "Set-Cookie": serializeSessionCookieValue(nextSessionId, { maxAge: SESSION_TTL }) });
370
+ }
371
+ async function destroyAuthSession(request) {
372
+ const sessionId = await getSessionIdFromRequest(request);
373
+ if (sessionId) await deleteSessionData(sessionId);
374
+ return new Headers({ "Set-Cookie": serializeExpiredSessionCookie() });
375
+ }
376
+ async function getCurrentAuthSessionId(request) {
377
+ return await getSessionIdFromRequest(request);
378
+ }
379
+ async function getAuthSessionById(sessionId) {
380
+ const session = await readSessionData(sessionId);
381
+ return session ? {
382
+ ...session,
383
+ sessionId
384
+ } : null;
385
+ }
386
+ async function listAuthSessionDataForUser(userId) {
387
+ const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionByUser(userId));
388
+ return await listSessionDataByIds(sessionIds);
389
+ }
390
+ async function listAuthSessionsForUser(userId, currentSessionId) {
391
+ const sessions = await listAuthSessionDataForUser(userId);
392
+ return sessions.map(({ sessionId, data }) => toAuthSessionSummary(sessionId, data, currentSessionId)).sort((left, right) => (right.lastActivity ?? right.createdAt ?? 0) - (left.lastActivity ?? left.createdAt ?? 0));
393
+ }
394
+ async function listCurrentUserAuthSessions(request) {
395
+ const currentSession = await getAuthSession(request);
396
+ if (!currentSession.userId) return [];
397
+ return await listAuthSessionsForUser(currentSession.userId, currentSession.sessionId);
398
+ }
399
+ async function destroyAuthSessionById(sessionId) {
400
+ const session = await readSessionData(sessionId);
401
+ if (!session) return false;
402
+ await deleteSessionData(sessionId);
403
+ return true;
404
+ }
405
+ async function destroyAuthSessionsForUser(userId) {
406
+ const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionByUser(userId));
407
+ let destroyedSessions = 0;
408
+ for (const sessionId of sessionIds) if (await destroyAuthSessionById(sessionId)) destroyedSessions += 1;
409
+ return destroyedSessions;
410
+ }
411
+ async function destroyAuthSessionsBySid(sid) {
412
+ const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionBySid(sid));
413
+ let destroyedSessions = 0;
414
+ for (const sessionId of sessionIds) if (await destroyAuthSessionById(sessionId)) destroyedSessions += 1;
415
+ return destroyedSessions;
416
+ }
417
+ async function destroyAuthSessionsBySessionState(sessionState) {
418
+ const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionBySessionState(sessionState));
419
+ let destroyedSessions = 0;
420
+ for (const sessionId of sessionIds) if (await destroyAuthSessionById(sessionId)) destroyedSessions += 1;
421
+ return destroyedSessions;
422
+ }
423
+ async function destroyAuthSessionsByIdentitySession(params) {
424
+ if (params.sid) return await destroyAuthSessionsBySid(params.sid);
425
+ if (params.sessionState) return await destroyAuthSessionsBySessionState(params.sessionState);
426
+ if (params.userId) return await destroyAuthSessionsForUser(params.userId);
427
+ return 0;
428
+ }
429
+ async function requireAuthSession(request) {
430
+ const sessionData = await getAuthSession(request);
431
+ if (!sessionData.userId || !sessionData.accessToken) throw new Response("Unauthorized", { status: 401 });
432
+ return sessionData;
433
+ }
434
+ async function isSessionValid(request) {
435
+ try {
436
+ const sessionData = await getAuthSession(request);
437
+ if (!sessionData.user || !sessionData.accessToken) return false;
438
+ if (sessionData.expiresAt && Date.now() >= sessionData.expiresAt) return false;
439
+ return true;
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
444
+ async function createOAuthState(state) {
445
+ const stateId = crypto.randomUUID();
446
+ const key = REDIS_KEYS.oauthState(stateId);
447
+ await getRedis().setex(key, OAUTH_STATE_TTL, JSON.stringify(state));
448
+ logger.debug("OAuth state created", {
449
+ stateId,
450
+ ttl: OAUTH_STATE_TTL
451
+ });
452
+ return stateId;
453
+ }
454
+ async function getOAuthState(stateId) {
455
+ const key = REDIS_KEYS.oauthState(stateId);
456
+ const data = await getRedis().get(key);
457
+ if (!data) {
458
+ logger.warn("OAuth state not found or expired", { stateId });
459
+ return null;
460
+ }
461
+ try {
462
+ return JSON.parse(data);
463
+ } catch (error) {
464
+ logger.error("Failed to parse OAuth state", error instanceof Error ? error : void 0);
465
+ return null;
466
+ }
467
+ }
468
+ async function deleteOAuthState(stateId) {
469
+ const key = REDIS_KEYS.oauthState(stateId);
470
+ await getRedis().del(key);
471
+ logger.debug("OAuth state deleted", { stateId });
472
+ }
473
+ async function cleanupExpiredOAuthStates() {
474
+ const pattern = REDIS_KEYS.oauthState("*");
475
+ const keys = await getRedis().keys(pattern);
476
+ let cleaned = 0;
477
+ for (const key of keys) {
478
+ const ttl = await getRedis().ttl(key);
479
+ if (ttl === -1) {
480
+ await getRedis().del(key);
481
+ cleaned++;
482
+ }
483
+ }
484
+ logger.info("OAuth state cleanup completed", {
485
+ cleaned,
486
+ total: keys.length
487
+ });
488
+ return cleaned;
489
+ }
490
+ async function closeRedisConnection() {
491
+ if (redis) {
492
+ await redis.quit();
493
+ redis = null;
494
+ logger.info("Redis connection closed");
495
+ }
496
+ }
497
+
498
+ //#endregion
499
+ export { AUTH_ERROR_COOKIE_PREFIX, cleanupExpiredOAuthStates, closeRedisConnection, createAuthSession, createOAuthState, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, getAuthSession, getAuthSessionById, getCurrentAuthSessionId, getOAuthState, isSessionValid, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, requireAuthSession, updateAuthSession };
500
+ //# sourceMappingURL=redis-session-storage.server-D0-72FV-.js.map