@payez/next-mvp 4.1.8 → 4.1.9

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 (155) hide show
  1. package/README.md +792 -792
  2. package/dist/auth/better-auth.js +15 -3
  3. package/dist/components/account/MobileNavDrawer.js +18 -18
  4. package/dist/components/account/UserAvatarMenu.js +1 -1
  5. package/dist/components/admin/AlertSettingsTab.js +40 -40
  6. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  7. package/dist/lib/idp-fetch.js +9 -25
  8. package/dist/pages/login/page.js +28 -28
  9. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  10. package/package.json +1 -1
  11. package/scripts/dev-broker.ps1 +35 -35
  12. package/scripts/dev-local.ps1 +45 -45
  13. package/src/api/auth-handler.ts +548 -548
  14. package/src/api-handlers/account/change-password.ts +142 -142
  15. package/src/api-handlers/account/update-phone.ts +79 -79
  16. package/src/api-handlers/account/verify-email.ts +125 -125
  17. package/src/api-handlers/account/verify-sms.ts +125 -125
  18. package/src/api-handlers/admin/analytics.ts +443 -443
  19. package/src/api-handlers/admin/audit.ts +223 -223
  20. package/src/api-handlers/admin/index.ts +63 -63
  21. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  22. package/src/api-handlers/admin/sessions.ts +318 -318
  23. package/src/api-handlers/admin/site-logs.ts +365 -365
  24. package/src/api-handlers/admin/users.ts +242 -242
  25. package/src/api-handlers/admin/vibe-data.ts +324 -324
  26. package/src/api-handlers/auth/refresh.ts +682 -682
  27. package/src/api-handlers/auth/signout.ts +199 -199
  28. package/src/api-handlers/auth/status.ts +20 -20
  29. package/src/api-handlers/auth/update-session.ts +110 -110
  30. package/src/api-handlers/auth/verify-code.ts +112 -112
  31. package/src/api-handlers/session/refresh-viability.ts +36 -36
  32. package/src/api-handlers/test/force-expire.ts +60 -60
  33. package/src/auth/auth-decision.ts +229 -229
  34. package/src/auth/better-auth.ts +15 -3
  35. package/src/auth/route-config.ts +219 -219
  36. package/src/auth/types/auth-types.ts +555 -555
  37. package/src/auth/types/index.ts +7 -7
  38. package/src/auth/utils/idp-client.ts +445 -445
  39. package/src/auth/utils/index.ts +6 -6
  40. package/src/auth/utils/token-utils.ts +243 -243
  41. package/src/client/AuthContext.tsx +143 -143
  42. package/src/client/fetch-with-auth.ts +47 -47
  43. package/src/components/SessionSync.tsx +138 -138
  44. package/src/components/SignalRHealthCheck.tsx +131 -131
  45. package/src/components/account/MobileNavDrawer.tsx +305 -305
  46. package/src/components/account/UserAvatarMenu.tsx +266 -266
  47. package/src/components/account/index.ts +13 -13
  48. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  49. package/src/components/admin/AnalyticsTab.tsx +703 -703
  50. package/src/components/admin/DataBrowserTab.tsx +505 -505
  51. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  52. package/src/components/admin/SessionsTab.tsx +414 -414
  53. package/src/components/admin/StatsTab.tsx +379 -379
  54. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  55. package/src/components/admin/index.ts +59 -59
  56. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  57. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  58. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  59. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  60. package/src/components/recovery/CompleteStep.tsx +36 -36
  61. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  62. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  63. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  64. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  65. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  66. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  67. package/src/components/ui/BetaBadge.tsx +58 -58
  68. package/src/components/ui/Footer.tsx +93 -93
  69. package/src/config/env.ts +57 -57
  70. package/src/config/logger.ts +62 -62
  71. package/src/config/vibe-log-transport.ts +264 -264
  72. package/src/hooks/useAuth.ts +117 -117
  73. package/src/hooks/useAuthSettings.ts +97 -97
  74. package/src/hooks/useAvailableProviders.ts +120 -120
  75. package/src/hooks/usePasswordValidation.ts +127 -127
  76. package/src/hooks/usePublicAuthSettings.ts +149 -149
  77. package/src/hooks/useSessionExpiration.ts +101 -101
  78. package/src/hooks/useViabilitySession.ts +336 -336
  79. package/src/index.ts +60 -60
  80. package/src/lib/api-handler.ts +643 -643
  81. package/src/lib/app-slug.ts +178 -178
  82. package/src/lib/geolocation.ts +265 -265
  83. package/src/lib/idp-fetch.ts +10 -26
  84. package/src/lib/jwt-decode.ts +82 -82
  85. package/src/lib/roles.ts +177 -177
  86. package/src/lib/site-logger.ts +245 -245
  87. package/src/lib/standardized-client-api.ts +901 -901
  88. package/src/lib/test-aware-get-token.ts +41 -41
  89. package/src/lib/user-agent-parser.ts +252 -252
  90. package/src/logging/api/admin-analytics.ts +51 -51
  91. package/src/logging/api/audit-log.ts +53 -53
  92. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  93. package/src/logging/components/AuditLogViewer.tsx +125 -125
  94. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  95. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  96. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  97. package/src/logging/hooks/useAuditLog.ts +24 -24
  98. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  99. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  100. package/src/logging/index.ts +18 -18
  101. package/src/logging/types/analytics.ts +81 -81
  102. package/src/logging/types/audit.ts +31 -31
  103. package/src/logging/types/index.ts +3 -3
  104. package/src/middleware/create-middleware.ts +663 -663
  105. package/src/middleware/rbac-check.ts +279 -279
  106. package/src/middleware/twofa-presets.ts +224 -224
  107. package/src/pages/admin-login/page.tsx +221 -221
  108. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  109. package/src/pages/admin-page-permissions/index.ts +7 -7
  110. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  111. package/src/pages/admin-roles/modals.tsx +469 -469
  112. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  113. package/src/pages/client-admin/index.ts +33 -33
  114. package/src/pages/coming-soon/page.tsx +83 -83
  115. package/src/pages/login/page.tsx +456 -456
  116. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  117. package/src/pages/profile/index.ts +9 -9
  118. package/src/pages/profile/page.tsx +166 -166
  119. package/src/pages/recovery/page.tsx +234 -234
  120. package/src/pages/roles/MyRolesPage.tsx +211 -211
  121. package/src/pages/roles/components.tsx +294 -294
  122. package/src/pages/roles/index.ts +17 -17
  123. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  124. package/src/pages/security/index.ts +9 -9
  125. package/src/pages/security/page.tsx +507 -507
  126. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  127. package/src/pages/settings/index.ts +9 -9
  128. package/src/pages/settings/page.tsx +47 -47
  129. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  130. package/src/pages/showcase/index.ts +13 -13
  131. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  132. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  133. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  134. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  135. package/src/pages/test-env/index.ts +25 -25
  136. package/src/pages/verify-code/page.tsx +652 -652
  137. package/src/routes/account/update-phone.ts +13 -13
  138. package/src/routes/auth/logout.ts +108 -108
  139. package/src/routes/auth/nextauth.ts +45 -45
  140. package/src/routes/auth/settings.ts +75 -75
  141. package/src/routes/auth/viability.ts +224 -224
  142. package/src/server/auth-guard.ts +170 -170
  143. package/src/server/slim-middleware.ts +117 -117
  144. package/src/server/with-auth.ts +93 -93
  145. package/src/stores/authStore.ts +1899 -1899
  146. package/src/templates/instrumentation.ts +41 -41
  147. package/src/utils/logout.ts +30 -30
  148. package/src/vibe/client.ts +590 -590
  149. package/src/vibe/enterprise-auth.ts +208 -208
  150. package/src/vibe/errors.ts +185 -185
  151. package/src/vibe/generic.ts +431 -431
  152. package/src/vibe/hooks/index.ts +367 -367
  153. package/src/vibe/index.ts +132 -132
  154. package/src/vibe/sessions.ts +551 -551
  155. package/src/vibe/types.ts +577 -577
@@ -1,336 +1,336 @@
1
- /**
2
- * useViabilitySession - Redis-backed session state hook
3
- *
4
- * This hook provides the REAL session state by consulting Redis via /api/session/viability
5
- * instead of relying on the potentially stale NextAuth JWT cookie.
6
- *
7
- * Redis is the single source of truth. This hook:
8
- * 1. Polls /api/session/viability to get actual session state from Redis
9
- * 2. Returns consistent auth state across all components
10
- * 3. Triggers callback when session state changes unexpectedly
11
- *
12
- * Usage:
13
- * ```tsx
14
- * const { isAuthenticated, isLoading } = useViabilitySession();
15
- * ```
16
- */
17
-
18
- 'use client';
19
-
20
- import { useState, useEffect, useRef } from 'react';
21
- import { authClient } from '../client/better-auth-client';
22
-
23
- export interface ViabilityState {
24
- /** Whether the user is authenticated according to Redis */
25
- isAuthenticated: boolean;
26
- /** Whether the viability check is in progress */
27
- isLoading: boolean;
28
- /** Whether 2FA is required for this client */
29
- requires2FA: boolean;
30
- /** Whether 2FA has been completed for this session */
31
- twoFactorComplete: boolean;
32
- /** Whether the access token has expired (refresh may be needed) */
33
- accessTokenExpired: boolean;
34
- /** Whether a refresh token is available */
35
- hasRefreshToken: boolean;
36
- /** Error message if viability check failed */
37
- error: string | null;
38
- /** Timestamp of last successful viability check */
39
- lastChecked: number | null;
40
- /** Force a viability check now */
41
- refresh: () => void;
42
- }
43
-
44
- interface ViabilityResponse {
45
- authenticated: boolean;
46
- sessionToken?: string;
47
- requires2FA?: boolean;
48
- twoFactorComplete?: boolean;
49
- accessTokenExpired?: boolean;
50
- hasRefreshToken?: boolean;
51
- }
52
-
53
- export interface UseViabilitySessionOptions {
54
- /** Polling interval in milliseconds (default: 30000 = 30 seconds) */
55
- pollInterval?: number;
56
- /** Whether to poll automatically (default: true) */
57
- enablePolling?: boolean;
58
- /** Callback when session becomes invalid */
59
- onSessionInvalid?: () => void;
60
- }
61
-
62
- // Use window to persist state across HMR in development
63
- declare global {
64
- interface Window {
65
- __viabilitySessionState?: {
66
- isAuthenticated: boolean;
67
- isLoading: boolean;
68
- requires2FA: boolean;
69
- twoFactorComplete: boolean;
70
- accessTokenExpired: boolean;
71
- hasRefreshToken: boolean;
72
- error: string | null;
73
- lastChecked: number | null;
74
- checkInProgress: boolean;
75
- prevAuth: boolean | null;
76
- intervalId: ReturnType<typeof setInterval> | null;
77
- listeners: Set<() => void>;
78
- onSessionInvalidCallbacks: Set<() => void>;
79
- };
80
- }
81
- }
82
-
83
- function getGlobalState() {
84
- if (typeof window === 'undefined') {
85
- // SSR - return default state
86
- return {
87
- isAuthenticated: false,
88
- isLoading: true,
89
- requires2FA: false,
90
- twoFactorComplete: false,
91
- accessTokenExpired: false,
92
- hasRefreshToken: false,
93
- error: null,
94
- lastChecked: null,
95
- checkInProgress: false,
96
- prevAuth: null,
97
- intervalId: null,
98
- listeners: new Set<() => void>(),
99
- onSessionInvalidCallbacks: new Set<() => void>()
100
- };
101
- }
102
-
103
- // Initialize global state on window if not present
104
- if (!window.__viabilitySessionState) {
105
- window.__viabilitySessionState = {
106
- isAuthenticated: false,
107
- isLoading: true,
108
- requires2FA: false,
109
- twoFactorComplete: false,
110
- accessTokenExpired: false,
111
- hasRefreshToken: false,
112
- error: null,
113
- lastChecked: null,
114
- checkInProgress: false,
115
- prevAuth: null,
116
- intervalId: null,
117
- listeners: new Set<() => void>(),
118
- onSessionInvalidCallbacks: new Set<() => void>()
119
- };
120
- }
121
-
122
- return window.__viabilitySessionState;
123
- }
124
-
125
- async function doViabilityCheck(): Promise<void> {
126
- const state = getGlobalState();
127
-
128
- // Prevent concurrent checks
129
- if (state.checkInProgress) return;
130
- state.checkInProgress = true;
131
-
132
- try {
133
- const response = await fetch('/api/session/viability', {
134
- method: 'GET',
135
- headers: {
136
- 'Accept': 'application/json',
137
- 'Cache-Control': 'no-store'
138
- },
139
- credentials: 'include'
140
- });
141
-
142
- if (!response.ok) {
143
- state.isLoading = false;
144
- state.error = `Viability check failed: ${response.status}`;
145
- state.lastChecked = Date.now();
146
- notifyListeners();
147
- return;
148
- }
149
-
150
- const data: ViabilityResponse = await response.json();
151
-
152
- // Detect auth state change
153
- if (state.prevAuth !== null && state.prevAuth !== data.authenticated) {
154
- console.log('[useViabilitySession] Auth state changed:', {
155
- was: state.prevAuth,
156
- now: data.authenticated
157
- });
158
-
159
- if (!data.authenticated) {
160
- // Notify all callbacks
161
- state.onSessionInvalidCallbacks.forEach(cb => {
162
- try { cb(); } catch (e) { console.error('[useViabilitySession] onSessionInvalid error:', e); }
163
- });
164
- }
165
- }
166
-
167
- state.prevAuth = data.authenticated;
168
- state.isAuthenticated = data.authenticated;
169
- state.isLoading = false;
170
- state.requires2FA = data.requires2FA ?? false;
171
- state.twoFactorComplete = data.twoFactorComplete ?? false;
172
- state.accessTokenExpired = data.accessTokenExpired ?? false;
173
- state.hasRefreshToken = data.hasRefreshToken ?? false;
174
- state.error = null;
175
- state.lastChecked = Date.now();
176
-
177
- notifyListeners();
178
-
179
- } catch (error) {
180
- console.error('[useViabilitySession] Error checking viability:', error);
181
- const state = getGlobalState();
182
- state.isLoading = false;
183
- state.error = error instanceof Error ? error.message : 'Unknown error';
184
- state.lastChecked = Date.now();
185
- notifyListeners();
186
- } finally {
187
- getGlobalState().checkInProgress = false;
188
- }
189
- }
190
-
191
- function notifyListeners() {
192
- const state = getGlobalState();
193
- state.listeners.forEach(listener => {
194
- try { listener(); } catch (e) { /* ignore */ }
195
- });
196
- }
197
-
198
- function startPolling(interval: number) {
199
- const state = getGlobalState();
200
- if (state.intervalId !== null) return; // Already polling
201
-
202
- state.intervalId = setInterval(() => {
203
- doViabilityCheck();
204
- }, interval);
205
- }
206
-
207
- function stopPolling() {
208
- const state = getGlobalState();
209
- if (state.intervalId !== null) {
210
- clearInterval(state.intervalId);
211
- state.intervalId = null;
212
- }
213
- }
214
-
215
- /**
216
- * Hook that provides Redis-backed session state
217
- */
218
- export function useViabilitySession(options: UseViabilitySessionOptions = {}): ViabilityState {
219
- const {
220
- pollInterval = 30000,
221
- enablePolling = true,
222
- onSessionInvalid
223
- } = options;
224
-
225
- const { data: _sessionData, isPending } = authClient.useSession();
226
- const nextAuthStatus = isPending ? 'loading' : _sessionData ? 'authenticated' : 'unauthenticated';
227
- const [, forceUpdate] = useState(0);
228
- const mountedRef = useRef(true);
229
- const initializedRef = useRef(false);
230
-
231
- // Register this component's onSessionInvalid callback
232
- useEffect(() => {
233
- if (onSessionInvalid) {
234
- const state = getGlobalState();
235
- state.onSessionInvalidCallbacks.add(onSessionInvalid);
236
- return () => {
237
- state.onSessionInvalidCallbacks.delete(onSessionInvalid);
238
- };
239
- }
240
- }, [onSessionInvalid]);
241
-
242
- // Subscribe to global state changes
243
- useEffect(() => {
244
- mountedRef.current = true;
245
- const listener = () => {
246
- if (mountedRef.current) {
247
- forceUpdate(n => n + 1);
248
- }
249
- };
250
- const state = getGlobalState();
251
- state.listeners.add(listener);
252
-
253
- return () => {
254
- mountedRef.current = false;
255
- state.listeners.delete(listener);
256
- };
257
- }, []);
258
-
259
- // Initial check when NextAuth status is determined - only once!
260
- useEffect(() => {
261
- if (nextAuthStatus === 'loading') {
262
- return;
263
- }
264
-
265
- const state = getGlobalState();
266
-
267
- // Only do initial check once globally
268
- if (!initializedRef.current && state.lastChecked === null) {
269
- initializedRef.current = true;
270
- doViabilityCheck();
271
- }
272
- }, [nextAuthStatus]);
273
-
274
- // Manage polling - only one interval for all hook instances
275
- useEffect(() => {
276
- if (!enablePolling || nextAuthStatus === 'loading') {
277
- return;
278
- }
279
-
280
- // Start polling if not already started
281
- startPolling(pollInterval);
282
-
283
- // Cleanup: only stop if this is the last listener
284
- return () => {
285
- const state = getGlobalState();
286
- // Small delay to allow other components to register
287
- setTimeout(() => {
288
- if (state.listeners.size === 0) {
289
- stopPolling();
290
- }
291
- }, 100);
292
- };
293
- }, [enablePolling, pollInterval, nextAuthStatus]);
294
-
295
- // Check viability on focus (user returns to tab) - with debounce
296
- useEffect(() => {
297
- const handleFocus = () => {
298
- const state = getGlobalState();
299
- // Debounce: only check if last check was > 10 seconds ago
300
- if (state.lastChecked !== null &&
301
- Date.now() - state.lastChecked > 10000) {
302
- doViabilityCheck();
303
- }
304
- };
305
-
306
- window.addEventListener('focus', handleFocus);
307
- return () => window.removeEventListener('focus', handleFocus);
308
- }, []);
309
-
310
- // Return current state
311
- const state = getGlobalState();
312
- return {
313
- isAuthenticated: state.isAuthenticated,
314
- isLoading: state.isLoading,
315
- requires2FA: state.requires2FA,
316
- twoFactorComplete: state.twoFactorComplete,
317
- accessTokenExpired: state.accessTokenExpired,
318
- hasRefreshToken: state.hasRefreshToken,
319
- error: state.error,
320
- lastChecked: state.lastChecked,
321
- refresh: doViabilityCheck
322
- };
323
- }
324
-
325
- /**
326
- * Simplified hook that just returns authentication status
327
- * Use this in components that only need to know if user is logged in
328
- */
329
- export function useIsAuthenticated(): { isAuthenticated: boolean; isLoading: boolean } {
330
- const { isAuthenticated, isLoading } = useViabilitySession({
331
- pollInterval: 60000, // Less frequent polling for simple status
332
- enablePolling: true
333
- });
334
-
335
- return { isAuthenticated, isLoading };
336
- }
1
+ /**
2
+ * useViabilitySession - Redis-backed session state hook
3
+ *
4
+ * This hook provides the REAL session state by consulting Redis via /api/session/viability
5
+ * instead of relying on the potentially stale NextAuth JWT cookie.
6
+ *
7
+ * Redis is the single source of truth. This hook:
8
+ * 1. Polls /api/session/viability to get actual session state from Redis
9
+ * 2. Returns consistent auth state across all components
10
+ * 3. Triggers callback when session state changes unexpectedly
11
+ *
12
+ * Usage:
13
+ * ```tsx
14
+ * const { isAuthenticated, isLoading } = useViabilitySession();
15
+ * ```
16
+ */
17
+
18
+ 'use client';
19
+
20
+ import { useState, useEffect, useRef } from 'react';
21
+ import { authClient } from '../client/better-auth-client';
22
+
23
+ export interface ViabilityState {
24
+ /** Whether the user is authenticated according to Redis */
25
+ isAuthenticated: boolean;
26
+ /** Whether the viability check is in progress */
27
+ isLoading: boolean;
28
+ /** Whether 2FA is required for this client */
29
+ requires2FA: boolean;
30
+ /** Whether 2FA has been completed for this session */
31
+ twoFactorComplete: boolean;
32
+ /** Whether the access token has expired (refresh may be needed) */
33
+ accessTokenExpired: boolean;
34
+ /** Whether a refresh token is available */
35
+ hasRefreshToken: boolean;
36
+ /** Error message if viability check failed */
37
+ error: string | null;
38
+ /** Timestamp of last successful viability check */
39
+ lastChecked: number | null;
40
+ /** Force a viability check now */
41
+ refresh: () => void;
42
+ }
43
+
44
+ interface ViabilityResponse {
45
+ authenticated: boolean;
46
+ sessionToken?: string;
47
+ requires2FA?: boolean;
48
+ twoFactorComplete?: boolean;
49
+ accessTokenExpired?: boolean;
50
+ hasRefreshToken?: boolean;
51
+ }
52
+
53
+ export interface UseViabilitySessionOptions {
54
+ /** Polling interval in milliseconds (default: 30000 = 30 seconds) */
55
+ pollInterval?: number;
56
+ /** Whether to poll automatically (default: true) */
57
+ enablePolling?: boolean;
58
+ /** Callback when session becomes invalid */
59
+ onSessionInvalid?: () => void;
60
+ }
61
+
62
+ // Use window to persist state across HMR in development
63
+ declare global {
64
+ interface Window {
65
+ __viabilitySessionState?: {
66
+ isAuthenticated: boolean;
67
+ isLoading: boolean;
68
+ requires2FA: boolean;
69
+ twoFactorComplete: boolean;
70
+ accessTokenExpired: boolean;
71
+ hasRefreshToken: boolean;
72
+ error: string | null;
73
+ lastChecked: number | null;
74
+ checkInProgress: boolean;
75
+ prevAuth: boolean | null;
76
+ intervalId: ReturnType<typeof setInterval> | null;
77
+ listeners: Set<() => void>;
78
+ onSessionInvalidCallbacks: Set<() => void>;
79
+ };
80
+ }
81
+ }
82
+
83
+ function getGlobalState() {
84
+ if (typeof window === 'undefined') {
85
+ // SSR - return default state
86
+ return {
87
+ isAuthenticated: false,
88
+ isLoading: true,
89
+ requires2FA: false,
90
+ twoFactorComplete: false,
91
+ accessTokenExpired: false,
92
+ hasRefreshToken: false,
93
+ error: null,
94
+ lastChecked: null,
95
+ checkInProgress: false,
96
+ prevAuth: null,
97
+ intervalId: null,
98
+ listeners: new Set<() => void>(),
99
+ onSessionInvalidCallbacks: new Set<() => void>()
100
+ };
101
+ }
102
+
103
+ // Initialize global state on window if not present
104
+ if (!window.__viabilitySessionState) {
105
+ window.__viabilitySessionState = {
106
+ isAuthenticated: false,
107
+ isLoading: true,
108
+ requires2FA: false,
109
+ twoFactorComplete: false,
110
+ accessTokenExpired: false,
111
+ hasRefreshToken: false,
112
+ error: null,
113
+ lastChecked: null,
114
+ checkInProgress: false,
115
+ prevAuth: null,
116
+ intervalId: null,
117
+ listeners: new Set<() => void>(),
118
+ onSessionInvalidCallbacks: new Set<() => void>()
119
+ };
120
+ }
121
+
122
+ return window.__viabilitySessionState;
123
+ }
124
+
125
+ async function doViabilityCheck(): Promise<void> {
126
+ const state = getGlobalState();
127
+
128
+ // Prevent concurrent checks
129
+ if (state.checkInProgress) return;
130
+ state.checkInProgress = true;
131
+
132
+ try {
133
+ const response = await fetch('/api/session/viability', {
134
+ method: 'GET',
135
+ headers: {
136
+ 'Accept': 'application/json',
137
+ 'Cache-Control': 'no-store'
138
+ },
139
+ credentials: 'include'
140
+ });
141
+
142
+ if (!response.ok) {
143
+ state.isLoading = false;
144
+ state.error = `Viability check failed: ${response.status}`;
145
+ state.lastChecked = Date.now();
146
+ notifyListeners();
147
+ return;
148
+ }
149
+
150
+ const data: ViabilityResponse = await response.json();
151
+
152
+ // Detect auth state change
153
+ if (state.prevAuth !== null && state.prevAuth !== data.authenticated) {
154
+ console.log('[useViabilitySession] Auth state changed:', {
155
+ was: state.prevAuth,
156
+ now: data.authenticated
157
+ });
158
+
159
+ if (!data.authenticated) {
160
+ // Notify all callbacks
161
+ state.onSessionInvalidCallbacks.forEach(cb => {
162
+ try { cb(); } catch (e) { console.error('[useViabilitySession] onSessionInvalid error:', e); }
163
+ });
164
+ }
165
+ }
166
+
167
+ state.prevAuth = data.authenticated;
168
+ state.isAuthenticated = data.authenticated;
169
+ state.isLoading = false;
170
+ state.requires2FA = data.requires2FA ?? false;
171
+ state.twoFactorComplete = data.twoFactorComplete ?? false;
172
+ state.accessTokenExpired = data.accessTokenExpired ?? false;
173
+ state.hasRefreshToken = data.hasRefreshToken ?? false;
174
+ state.error = null;
175
+ state.lastChecked = Date.now();
176
+
177
+ notifyListeners();
178
+
179
+ } catch (error) {
180
+ console.error('[useViabilitySession] Error checking viability:', error);
181
+ const state = getGlobalState();
182
+ state.isLoading = false;
183
+ state.error = error instanceof Error ? error.message : 'Unknown error';
184
+ state.lastChecked = Date.now();
185
+ notifyListeners();
186
+ } finally {
187
+ getGlobalState().checkInProgress = false;
188
+ }
189
+ }
190
+
191
+ function notifyListeners() {
192
+ const state = getGlobalState();
193
+ state.listeners.forEach(listener => {
194
+ try { listener(); } catch (e) { /* ignore */ }
195
+ });
196
+ }
197
+
198
+ function startPolling(interval: number) {
199
+ const state = getGlobalState();
200
+ if (state.intervalId !== null) return; // Already polling
201
+
202
+ state.intervalId = setInterval(() => {
203
+ doViabilityCheck();
204
+ }, interval);
205
+ }
206
+
207
+ function stopPolling() {
208
+ const state = getGlobalState();
209
+ if (state.intervalId !== null) {
210
+ clearInterval(state.intervalId);
211
+ state.intervalId = null;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Hook that provides Redis-backed session state
217
+ */
218
+ export function useViabilitySession(options: UseViabilitySessionOptions = {}): ViabilityState {
219
+ const {
220
+ pollInterval = 30000,
221
+ enablePolling = true,
222
+ onSessionInvalid
223
+ } = options;
224
+
225
+ const { data: _sessionData, isPending } = authClient.useSession();
226
+ const nextAuthStatus = isPending ? 'loading' : _sessionData ? 'authenticated' : 'unauthenticated';
227
+ const [, forceUpdate] = useState(0);
228
+ const mountedRef = useRef(true);
229
+ const initializedRef = useRef(false);
230
+
231
+ // Register this component's onSessionInvalid callback
232
+ useEffect(() => {
233
+ if (onSessionInvalid) {
234
+ const state = getGlobalState();
235
+ state.onSessionInvalidCallbacks.add(onSessionInvalid);
236
+ return () => {
237
+ state.onSessionInvalidCallbacks.delete(onSessionInvalid);
238
+ };
239
+ }
240
+ }, [onSessionInvalid]);
241
+
242
+ // Subscribe to global state changes
243
+ useEffect(() => {
244
+ mountedRef.current = true;
245
+ const listener = () => {
246
+ if (mountedRef.current) {
247
+ forceUpdate(n => n + 1);
248
+ }
249
+ };
250
+ const state = getGlobalState();
251
+ state.listeners.add(listener);
252
+
253
+ return () => {
254
+ mountedRef.current = false;
255
+ state.listeners.delete(listener);
256
+ };
257
+ }, []);
258
+
259
+ // Initial check when NextAuth status is determined - only once!
260
+ useEffect(() => {
261
+ if (nextAuthStatus === 'loading') {
262
+ return;
263
+ }
264
+
265
+ const state = getGlobalState();
266
+
267
+ // Only do initial check once globally
268
+ if (!initializedRef.current && state.lastChecked === null) {
269
+ initializedRef.current = true;
270
+ doViabilityCheck();
271
+ }
272
+ }, [nextAuthStatus]);
273
+
274
+ // Manage polling - only one interval for all hook instances
275
+ useEffect(() => {
276
+ if (!enablePolling || nextAuthStatus === 'loading') {
277
+ return;
278
+ }
279
+
280
+ // Start polling if not already started
281
+ startPolling(pollInterval);
282
+
283
+ // Cleanup: only stop if this is the last listener
284
+ return () => {
285
+ const state = getGlobalState();
286
+ // Small delay to allow other components to register
287
+ setTimeout(() => {
288
+ if (state.listeners.size === 0) {
289
+ stopPolling();
290
+ }
291
+ }, 100);
292
+ };
293
+ }, [enablePolling, pollInterval, nextAuthStatus]);
294
+
295
+ // Check viability on focus (user returns to tab) - with debounce
296
+ useEffect(() => {
297
+ const handleFocus = () => {
298
+ const state = getGlobalState();
299
+ // Debounce: only check if last check was > 10 seconds ago
300
+ if (state.lastChecked !== null &&
301
+ Date.now() - state.lastChecked > 10000) {
302
+ doViabilityCheck();
303
+ }
304
+ };
305
+
306
+ window.addEventListener('focus', handleFocus);
307
+ return () => window.removeEventListener('focus', handleFocus);
308
+ }, []);
309
+
310
+ // Return current state
311
+ const state = getGlobalState();
312
+ return {
313
+ isAuthenticated: state.isAuthenticated,
314
+ isLoading: state.isLoading,
315
+ requires2FA: state.requires2FA,
316
+ twoFactorComplete: state.twoFactorComplete,
317
+ accessTokenExpired: state.accessTokenExpired,
318
+ hasRefreshToken: state.hasRefreshToken,
319
+ error: state.error,
320
+ lastChecked: state.lastChecked,
321
+ refresh: doViabilityCheck
322
+ };
323
+ }
324
+
325
+ /**
326
+ * Simplified hook that just returns authentication status
327
+ * Use this in components that only need to know if user is logged in
328
+ */
329
+ export function useIsAuthenticated(): { isAuthenticated: boolean; isLoading: boolean } {
330
+ const { isAuthenticated, isLoading } = useViabilitySession({
331
+ pollInterval: 60000, // Less frequent polling for simple status
332
+ enablePolling: true
333
+ });
334
+
335
+ return { isAuthenticated, isLoading };
336
+ }