@payez/next-mvp 4.1.7 → 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 (154) 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/pages/login/page.js +28 -28
  8. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  9. package/package.json +1 -1
  10. package/scripts/dev-broker.ps1 +35 -35
  11. package/scripts/dev-local.ps1 +45 -45
  12. package/src/api/auth-handler.ts +548 -548
  13. package/src/api-handlers/account/change-password.ts +142 -142
  14. package/src/api-handlers/account/update-phone.ts +79 -79
  15. package/src/api-handlers/account/verify-email.ts +125 -125
  16. package/src/api-handlers/account/verify-sms.ts +125 -125
  17. package/src/api-handlers/admin/analytics.ts +443 -443
  18. package/src/api-handlers/admin/audit.ts +223 -223
  19. package/src/api-handlers/admin/index.ts +63 -63
  20. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  21. package/src/api-handlers/admin/sessions.ts +318 -318
  22. package/src/api-handlers/admin/site-logs.ts +365 -365
  23. package/src/api-handlers/admin/users.ts +242 -242
  24. package/src/api-handlers/admin/vibe-data.ts +324 -324
  25. package/src/api-handlers/auth/refresh.ts +682 -682
  26. package/src/api-handlers/auth/signout.ts +199 -199
  27. package/src/api-handlers/auth/status.ts +20 -20
  28. package/src/api-handlers/auth/update-session.ts +110 -110
  29. package/src/api-handlers/auth/verify-code.ts +112 -112
  30. package/src/api-handlers/session/refresh-viability.ts +36 -36
  31. package/src/api-handlers/test/force-expire.ts +60 -60
  32. package/src/auth/auth-decision.ts +229 -229
  33. package/src/auth/better-auth.ts +15 -3
  34. package/src/auth/route-config.ts +219 -219
  35. package/src/auth/types/auth-types.ts +555 -555
  36. package/src/auth/types/index.ts +7 -7
  37. package/src/auth/utils/idp-client.ts +445 -445
  38. package/src/auth/utils/index.ts +6 -6
  39. package/src/auth/utils/token-utils.ts +243 -243
  40. package/src/client/AuthContext.tsx +143 -143
  41. package/src/client/fetch-with-auth.ts +47 -47
  42. package/src/components/SessionSync.tsx +138 -138
  43. package/src/components/SignalRHealthCheck.tsx +131 -131
  44. package/src/components/account/MobileNavDrawer.tsx +305 -305
  45. package/src/components/account/UserAvatarMenu.tsx +266 -266
  46. package/src/components/account/index.ts +13 -13
  47. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  48. package/src/components/admin/AnalyticsTab.tsx +703 -703
  49. package/src/components/admin/DataBrowserTab.tsx +505 -505
  50. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  51. package/src/components/admin/SessionsTab.tsx +414 -414
  52. package/src/components/admin/StatsTab.tsx +379 -379
  53. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  54. package/src/components/admin/index.ts +59 -59
  55. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  56. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  57. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  58. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  59. package/src/components/recovery/CompleteStep.tsx +36 -36
  60. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  61. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  62. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  63. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  64. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  65. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  66. package/src/components/ui/BetaBadge.tsx +58 -58
  67. package/src/components/ui/Footer.tsx +93 -93
  68. package/src/config/env.ts +57 -57
  69. package/src/config/logger.ts +62 -62
  70. package/src/config/vibe-log-transport.ts +264 -264
  71. package/src/hooks/useAuth.ts +117 -117
  72. package/src/hooks/useAuthSettings.ts +97 -97
  73. package/src/hooks/useAvailableProviders.ts +120 -120
  74. package/src/hooks/usePasswordValidation.ts +127 -127
  75. package/src/hooks/usePublicAuthSettings.ts +149 -149
  76. package/src/hooks/useSessionExpiration.ts +101 -101
  77. package/src/hooks/useViabilitySession.ts +336 -336
  78. package/src/index.ts +60 -60
  79. package/src/lib/api-handler.ts +643 -643
  80. package/src/lib/app-slug.ts +178 -178
  81. package/src/lib/geolocation.ts +265 -265
  82. package/src/lib/idp-fetch.ts +110 -110
  83. package/src/lib/jwt-decode.ts +82 -82
  84. package/src/lib/roles.ts +177 -177
  85. package/src/lib/site-logger.ts +245 -245
  86. package/src/lib/standardized-client-api.ts +901 -901
  87. package/src/lib/test-aware-get-token.ts +41 -41
  88. package/src/lib/user-agent-parser.ts +252 -252
  89. package/src/logging/api/admin-analytics.ts +51 -51
  90. package/src/logging/api/audit-log.ts +53 -53
  91. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  92. package/src/logging/components/AuditLogViewer.tsx +125 -125
  93. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  94. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  95. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  96. package/src/logging/hooks/useAuditLog.ts +24 -24
  97. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  98. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  99. package/src/logging/index.ts +18 -18
  100. package/src/logging/types/analytics.ts +81 -81
  101. package/src/logging/types/audit.ts +31 -31
  102. package/src/logging/types/index.ts +3 -3
  103. package/src/middleware/create-middleware.ts +663 -663
  104. package/src/middleware/rbac-check.ts +279 -279
  105. package/src/middleware/twofa-presets.ts +224 -224
  106. package/src/pages/admin-login/page.tsx +221 -221
  107. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  108. package/src/pages/admin-page-permissions/index.ts +7 -7
  109. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  110. package/src/pages/admin-roles/modals.tsx +469 -469
  111. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  112. package/src/pages/client-admin/index.ts +33 -33
  113. package/src/pages/coming-soon/page.tsx +83 -83
  114. package/src/pages/login/page.tsx +456 -456
  115. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  116. package/src/pages/profile/index.ts +9 -9
  117. package/src/pages/profile/page.tsx +166 -166
  118. package/src/pages/recovery/page.tsx +234 -234
  119. package/src/pages/roles/MyRolesPage.tsx +211 -211
  120. package/src/pages/roles/components.tsx +294 -294
  121. package/src/pages/roles/index.ts +17 -17
  122. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  123. package/src/pages/security/index.ts +9 -9
  124. package/src/pages/security/page.tsx +507 -507
  125. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  126. package/src/pages/settings/index.ts +9 -9
  127. package/src/pages/settings/page.tsx +47 -47
  128. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  129. package/src/pages/showcase/index.ts +13 -13
  130. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  131. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  132. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  133. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  134. package/src/pages/test-env/index.ts +25 -25
  135. package/src/pages/verify-code/page.tsx +652 -652
  136. package/src/routes/account/update-phone.ts +13 -13
  137. package/src/routes/auth/logout.ts +108 -108
  138. package/src/routes/auth/nextauth.ts +45 -45
  139. package/src/routes/auth/settings.ts +75 -75
  140. package/src/routes/auth/viability.ts +224 -224
  141. package/src/server/auth-guard.ts +170 -170
  142. package/src/server/slim-middleware.ts +117 -117
  143. package/src/server/with-auth.ts +93 -93
  144. package/src/stores/authStore.ts +1899 -1899
  145. package/src/templates/instrumentation.ts +41 -41
  146. package/src/utils/logout.ts +30 -30
  147. package/src/vibe/client.ts +590 -590
  148. package/src/vibe/enterprise-auth.ts +208 -208
  149. package/src/vibe/errors.ts +185 -185
  150. package/src/vibe/generic.ts +431 -431
  151. package/src/vibe/hooks/index.ts +367 -367
  152. package/src/vibe/index.ts +132 -132
  153. package/src/vibe/sessions.ts +551 -551
  154. package/src/vibe/types.ts +577 -577
@@ -1,143 +1,143 @@
1
- 'use client';
2
-
3
- import React, { createContext, useContext, ReactNode, useState, useEffect } from 'react';
4
- import { authClient } from './better-auth-client';
5
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
6
- import { AuthConfig, AuthMode, FederatedProvider } from '@/types/auth';
7
-
8
- const AuthContext = createContext<AuthConfig | null>(null);
9
-
10
- const defaultConfig: AuthConfig = {
11
- mode: 'traditional',
12
- providers: [],
13
- enableRecovery: true,
14
- enableEmailSignup: true,
15
- allowPasswordReset: true,
16
- };
17
-
18
- // Map provider IDs to our FederatedProvider type
19
- const PROVIDER_MAP: Record<string, FederatedProvider> = {
20
- 'google': 'google',
21
- 'apple': 'apple',
22
- 'facebook': 'facebook',
23
- 'github': 'github',
24
- 'azure-ad': 'microsoft',
25
- 'microsoft-entra-id': 'microsoft',
26
- };
27
-
28
- // OAuth providers we support in UI (excludes credentials)
29
- const OAUTH_PROVIDER_IDS = ['google', 'apple', 'facebook', 'github', 'azure-ad', 'microsoft-entra-id'];
30
-
31
- interface AuthProviderProps {
32
- children: ReactNode;
33
- config?: Partial<AuthConfig>;
34
- /**
35
- * If true, providers will be loaded dynamically from IDP config
36
- * instead of using the static providers array from config.
37
- */
38
- useDynamicProviders?: boolean;
39
- }
40
-
41
- export function AuthProvider({ children, config, useDynamicProviders = true }: AuthProviderProps) {
42
- const [dynamicProviders, setDynamicProviders] = useState<FederatedProvider[]>([]);
43
- const [providersLoaded, setProvidersLoaded] = useState(!useDynamicProviders);
44
-
45
- // Create QueryClient instance for React Query - used internally by MVP hooks
46
- const [queryClient] = useState(() => new QueryClient({
47
- defaultOptions: {
48
- queries: {
49
- staleTime: 60 * 1000, // 1 minute
50
- retry: 1,
51
- refetchOnWindowFocus: false,
52
- },
53
- },
54
- }));
55
-
56
- // Load available providers on mount
57
- useEffect(() => {
58
- if (!useDynamicProviders) return;
59
-
60
- let mounted = true;
61
-
62
- async function fetchDynamicProviders() {
63
- try {
64
- // Better Auth doesn't have a getProviders equivalent.
65
- // Use static provider map based on configured social providers.
66
- const result: Record<string, { id: string; name: string }> | null = {
67
- google: { id: 'google', name: 'Google' },
68
- };
69
-
70
- if (!mounted) return;
71
-
72
- if (result) {
73
- // Filter to OAuth providers only and map to FederatedProvider type
74
- const oauthProviders = Object.keys(result)
75
- .filter(id => OAUTH_PROVIDER_IDS.includes(id))
76
- .map(id => PROVIDER_MAP[id])
77
- .filter((p): p is FederatedProvider => p !== undefined);
78
-
79
- setDynamicProviders(oauthProviders);
80
- }
81
- } catch (err) {
82
- // Fall back to static config providers on error
83
- } finally {
84
- if (mounted) {
85
- setProvidersLoaded(true);
86
- }
87
- }
88
- }
89
-
90
- fetchDynamicProviders();
91
-
92
- return () => {
93
- mounted = false;
94
- };
95
- }, [useDynamicProviders]);
96
-
97
- // Determine final providers list
98
- const providers = useDynamicProviders && providersLoaded
99
- ? dynamicProviders
100
- : (config?.providers ?? defaultConfig.providers);
101
-
102
- const authConfig: AuthConfig = {
103
- ...defaultConfig,
104
- ...config,
105
- providers, // Override with dynamic providers if enabled
106
- };
107
-
108
- return (
109
- <QueryClientProvider client={queryClient}>
110
- <AuthContext.Provider value={authConfig}>
111
- {children}
112
- </AuthContext.Provider>
113
- </QueryClientProvider>
114
- );
115
- }
116
-
117
- export function useAuthConfig(): AuthConfig {
118
- const context = useContext(AuthContext);
119
- if (!context) {
120
- return defaultConfig;
121
- }
122
- return context;
123
- }
124
-
125
- export function useAuthMode(): AuthMode {
126
- const config = useAuthConfig();
127
- return config.mode;
128
- }
129
-
130
- export function useFederatedProviders(): FederatedProvider[] {
131
- const config = useAuthConfig();
132
- return config.providers;
133
- }
134
-
135
- export function useFederatedAuthEnabled(): boolean {
136
- const config = useAuthConfig();
137
- return config.mode === 'federated' && config.providers.length > 0;
138
- }
139
-
140
- export function useTraditionalAuthEnabled(): boolean {
141
- const config = useAuthConfig();
142
- return config.mode === 'traditional';
143
- }
1
+ 'use client';
2
+
3
+ import React, { createContext, useContext, ReactNode, useState, useEffect } from 'react';
4
+ import { authClient } from './better-auth-client';
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
6
+ import { AuthConfig, AuthMode, FederatedProvider } from '@/types/auth';
7
+
8
+ const AuthContext = createContext<AuthConfig | null>(null);
9
+
10
+ const defaultConfig: AuthConfig = {
11
+ mode: 'traditional',
12
+ providers: [],
13
+ enableRecovery: true,
14
+ enableEmailSignup: true,
15
+ allowPasswordReset: true,
16
+ };
17
+
18
+ // Map provider IDs to our FederatedProvider type
19
+ const PROVIDER_MAP: Record<string, FederatedProvider> = {
20
+ 'google': 'google',
21
+ 'apple': 'apple',
22
+ 'facebook': 'facebook',
23
+ 'github': 'github',
24
+ 'azure-ad': 'microsoft',
25
+ 'microsoft-entra-id': 'microsoft',
26
+ };
27
+
28
+ // OAuth providers we support in UI (excludes credentials)
29
+ const OAUTH_PROVIDER_IDS = ['google', 'apple', 'facebook', 'github', 'azure-ad', 'microsoft-entra-id'];
30
+
31
+ interface AuthProviderProps {
32
+ children: ReactNode;
33
+ config?: Partial<AuthConfig>;
34
+ /**
35
+ * If true, providers will be loaded dynamically from IDP config
36
+ * instead of using the static providers array from config.
37
+ */
38
+ useDynamicProviders?: boolean;
39
+ }
40
+
41
+ export function AuthProvider({ children, config, useDynamicProviders = true }: AuthProviderProps) {
42
+ const [dynamicProviders, setDynamicProviders] = useState<FederatedProvider[]>([]);
43
+ const [providersLoaded, setProvidersLoaded] = useState(!useDynamicProviders);
44
+
45
+ // Create QueryClient instance for React Query - used internally by MVP hooks
46
+ const [queryClient] = useState(() => new QueryClient({
47
+ defaultOptions: {
48
+ queries: {
49
+ staleTime: 60 * 1000, // 1 minute
50
+ retry: 1,
51
+ refetchOnWindowFocus: false,
52
+ },
53
+ },
54
+ }));
55
+
56
+ // Load available providers on mount
57
+ useEffect(() => {
58
+ if (!useDynamicProviders) return;
59
+
60
+ let mounted = true;
61
+
62
+ async function fetchDynamicProviders() {
63
+ try {
64
+ // Better Auth doesn't have a getProviders equivalent.
65
+ // Use static provider map based on configured social providers.
66
+ const result: Record<string, { id: string; name: string }> | null = {
67
+ google: { id: 'google', name: 'Google' },
68
+ };
69
+
70
+ if (!mounted) return;
71
+
72
+ if (result) {
73
+ // Filter to OAuth providers only and map to FederatedProvider type
74
+ const oauthProviders = Object.keys(result)
75
+ .filter(id => OAUTH_PROVIDER_IDS.includes(id))
76
+ .map(id => PROVIDER_MAP[id])
77
+ .filter((p): p is FederatedProvider => p !== undefined);
78
+
79
+ setDynamicProviders(oauthProviders);
80
+ }
81
+ } catch (err) {
82
+ // Fall back to static config providers on error
83
+ } finally {
84
+ if (mounted) {
85
+ setProvidersLoaded(true);
86
+ }
87
+ }
88
+ }
89
+
90
+ fetchDynamicProviders();
91
+
92
+ return () => {
93
+ mounted = false;
94
+ };
95
+ }, [useDynamicProviders]);
96
+
97
+ // Determine final providers list
98
+ const providers = useDynamicProviders && providersLoaded
99
+ ? dynamicProviders
100
+ : (config?.providers ?? defaultConfig.providers);
101
+
102
+ const authConfig: AuthConfig = {
103
+ ...defaultConfig,
104
+ ...config,
105
+ providers, // Override with dynamic providers if enabled
106
+ };
107
+
108
+ return (
109
+ <QueryClientProvider client={queryClient}>
110
+ <AuthContext.Provider value={authConfig}>
111
+ {children}
112
+ </AuthContext.Provider>
113
+ </QueryClientProvider>
114
+ );
115
+ }
116
+
117
+ export function useAuthConfig(): AuthConfig {
118
+ const context = useContext(AuthContext);
119
+ if (!context) {
120
+ return defaultConfig;
121
+ }
122
+ return context;
123
+ }
124
+
125
+ export function useAuthMode(): AuthMode {
126
+ const config = useAuthConfig();
127
+ return config.mode;
128
+ }
129
+
130
+ export function useFederatedProviders(): FederatedProvider[] {
131
+ const config = useAuthConfig();
132
+ return config.providers;
133
+ }
134
+
135
+ export function useFederatedAuthEnabled(): boolean {
136
+ const config = useAuthConfig();
137
+ return config.mode === 'federated' && config.providers.length > 0;
138
+ }
139
+
140
+ export function useTraditionalAuthEnabled(): boolean {
141
+ const config = useAuthConfig();
142
+ return config.mode === 'traditional';
143
+ }
@@ -1,48 +1,48 @@
1
- // src/client/fetch-with-auth.ts
2
- import { authClient } from './better-auth-client';
3
-
4
- /**
5
- * A wrapper for the `fetch` API that automatically injects the session's
6
- * accessToken into the Authorization header and handles 401 Unauthorized
7
- * responses by redirecting the user to the login page.
8
- *
9
- * @param url The URL to fetch.
10
- * @param options The standard `fetch` options.
11
- * @returns A `Promise` that resolves to the `Response` object.
12
- * @throws An 'UNAUTHORIZED_REDIRECT' error after initiating the redirect to halt further execution.
13
- */
14
- export async function fetchWithAuth(url: string, options: RequestInit = {}): Promise<Response> {
15
- // 1. Retrieve the client-side session to get the accessToken.
16
- const { data: session } = await authClient.getSession();
17
-
18
- // 2. Inject the accessToken into the Authorization header.
19
- const headers = new Headers(options.headers);
20
- if ((session as any)?.accessToken) {
21
- headers.set('Authorization', `Bearer ${(session as any).accessToken}`);
22
- }
23
- options.headers = headers;
24
-
25
- const response = await fetch(url, options);
26
-
27
- // 3. Handle the 401 response intelligently.
28
- if (response.status === 401) {
29
- // If we have a valid session, this is likely a claim/permission error, not an auth error
30
- if ((session as any)?.accessToken) {
31
- console.warn('API returned 401 despite valid session. Likely insufficient claims or permissions.');
32
- // Don't redirect - let the calling code handle the error gracefully
33
- return response;
34
- }
35
-
36
- // No valid session - this is a real authentication failure
37
- console.error('Unauthorized API call (no valid session). Redirecting to login.');
38
- // SAFEGUARD: Never use auth pages as callback URLs to prevent redirect loops
39
- const pathname = window.location.pathname;
40
- const safeCallbackUrl = pathname.startsWith('/account-auth/') ? '/' : pathname;
41
- window.location.href = `/account-auth/login?callbackUrl=${encodeURIComponent(safeCallbackUrl)}`;
42
-
43
- // Throw a specific error to signal that a redirect has been initiated.
44
- throw new Error('UNAUTHORIZED_REDIRECT');
45
- }
46
-
47
- return response;
1
+ // src/client/fetch-with-auth.ts
2
+ import { authClient } from './better-auth-client';
3
+
4
+ /**
5
+ * A wrapper for the `fetch` API that automatically injects the session's
6
+ * accessToken into the Authorization header and handles 401 Unauthorized
7
+ * responses by redirecting the user to the login page.
8
+ *
9
+ * @param url The URL to fetch.
10
+ * @param options The standard `fetch` options.
11
+ * @returns A `Promise` that resolves to the `Response` object.
12
+ * @throws An 'UNAUTHORIZED_REDIRECT' error after initiating the redirect to halt further execution.
13
+ */
14
+ export async function fetchWithAuth(url: string, options: RequestInit = {}): Promise<Response> {
15
+ // 1. Retrieve the client-side session to get the accessToken.
16
+ const { data: session } = await authClient.getSession();
17
+
18
+ // 2. Inject the accessToken into the Authorization header.
19
+ const headers = new Headers(options.headers);
20
+ if ((session as any)?.accessToken) {
21
+ headers.set('Authorization', `Bearer ${(session as any).accessToken}`);
22
+ }
23
+ options.headers = headers;
24
+
25
+ const response = await fetch(url, options);
26
+
27
+ // 3. Handle the 401 response intelligently.
28
+ if (response.status === 401) {
29
+ // If we have a valid session, this is likely a claim/permission error, not an auth error
30
+ if ((session as any)?.accessToken) {
31
+ console.warn('API returned 401 despite valid session. Likely insufficient claims or permissions.');
32
+ // Don't redirect - let the calling code handle the error gracefully
33
+ return response;
34
+ }
35
+
36
+ // No valid session - this is a real authentication failure
37
+ console.error('Unauthorized API call (no valid session). Redirecting to login.');
38
+ // SAFEGUARD: Never use auth pages as callback URLs to prevent redirect loops
39
+ const pathname = window.location.pathname;
40
+ const safeCallbackUrl = pathname.startsWith('/account-auth/') ? '/' : pathname;
41
+ window.location.href = `/account-auth/login?callbackUrl=${encodeURIComponent(safeCallbackUrl)}`;
42
+
43
+ // Throw a specific error to signal that a redirect has been initiated.
44
+ throw new Error('UNAUTHORIZED_REDIRECT');
45
+ }
46
+
47
+ return response;
48
48
  }
@@ -1,138 +1,138 @@
1
- 'use client';
2
-
3
- import { useEffect, useRef } from 'react';
4
- import { authClient } from '../client/better-auth-client';
5
- import { useAuthStore } from '../stores/authStore';
6
- import { isValidSession } from '../lib/session';
7
- import {
8
- getSecureSessionCookieName,
9
- getSecureCsrfCookieName,
10
- getCallbackUrlCookieName
11
- } from '../lib/app-slug';
12
-
13
- /**
14
- * Sanitize sensitive data for logging
15
- * Never log full user IDs or emails in any environment
16
- */
17
- function sanitizeForLog(value: string | undefined, type: 'email' | 'userId'): string {
18
- if (!value) return '(empty)';
19
-
20
- if (type === 'email') {
21
- return '***@***'; // Never log emails
22
- }
23
-
24
- if (type === 'userId') {
25
- // Only show first 8 chars in development
26
- if (process.env.NODE_ENV === 'development') {
27
- return value.substring(0, 8) + '...';
28
- }
29
- return '***'; // Fully redact in production
30
- }
31
-
32
- return '***';
33
- }
34
-
35
- /**
36
- * SessionSync - Bridges NextAuth session with Zustand auth store
37
- *
38
- * CRITICAL: This component enforces strict session validation. If NextAuth
39
- * reports an authenticated status but the session data is invalid (empty user ID,
40
- * empty email, or missing access token), it forces a sign-out to prevent
41
- * contradictory state like "hasSession: true, userId: ''"
42
- *
43
- * This ensures the app NEVER shows authenticated UI with empty/invalid session data.
44
- */
45
- export function SessionSync({ children }: { children: React.ReactNode }) {
46
- const { data: sessionData, isPending } = authClient.useSession();
47
- const session = sessionData;
48
- const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
49
- const { setSession, clearSession } = useAuthStore();
50
-
51
- // Guard against duplicate sign-out calls
52
- const isSigningOutRef = useRef(false);
53
-
54
- useEffect(() => {
55
- let isMounted = true;
56
-
57
- // Only process when NextAuth has finished loading
58
- if (status === 'loading') {
59
- return;
60
- }
61
-
62
- // Strict validation: Check if session is actually valid
63
- const isValid = isValidSession(session);
64
-
65
- // CRITICAL FIX: If NextAuth says "authenticated" but session is invalid,
66
- // this is a broken state that must be fixed immediately
67
- if (status === 'authenticated' && !isValid) {
68
- // GUARD: Prevent duplicate sign-out
69
- if (isSigningOutRef.current) {
70
- console.warn('[SessionSync] Sign-out already in progress, skipping');
71
- return;
72
- }
73
- isSigningOutRef.current = true;
74
-
75
- console.error('[SessionSync] CRITICAL: Invalid session detected despite authenticated status!');
76
- console.error('[SessionSync] This indicates a session with empty user data - forcing sign-out');
77
-
78
- // Log diagnostic info with PII redaction
79
- // Note: session is typed as Session | null from NextAuth, but may have invalid/partial data
80
- const sessionData = session as any; // Explicit cast needed for error logging
81
- console.error('[SessionSync] Session data:', {
82
- hasSessionObject: !!sessionData,
83
- hasUser: !!sessionData?.user,
84
- userId: sanitizeForLog(sessionData?.user?.id, 'userId'),
85
- userEmail: sanitizeForLog(sessionData?.user?.email, 'email'),
86
- hasAccessToken: !!sessionData?.accessToken,
87
- });
88
-
89
- // Clear the auth store immediately
90
- clearSession();
91
-
92
- // FIX: Force clear all auth cookies including stale provisional tokens (app-slug prefixed)
93
- // This prevents infinite loop when provisional token exists but session is invalid
94
- // Root cause: OAuth creates provisional token before Redis session exists
95
- try {
96
- const secureSession = getSecureSessionCookieName();
97
- const secureCsrf = getSecureCsrfCookieName();
98
- const callbackUrl = getCallbackUrlCookieName();
99
- document.cookie = `${secureSession}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; Secure; SameSite=Lax`;
100
- document.cookie = `${secureCsrf}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax`;
101
- document.cookie = `__Secure-${callbackUrl}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; Secure; SameSite=Lax`;
102
- } catch (e) {
103
- // Cookie clearing failed - non-critical, continue with signout
104
- }
105
-
106
- // Force Better Auth to sign out (this will clear cookies and trigger redirect)
107
- authClient.signOut()
108
- .then(() => {
109
- if (isMounted) {
110
- // Use generic error code instead of implementation details
111
- window.location.href = '/account-auth/login?error=SessionExpired&code=1001';
112
- }
113
- })
114
- .catch((err) => {
115
- console.error('[SessionSync] Error during forced signout:', err);
116
- if (isMounted) {
117
- window.location.href = '/account-auth/login?error=SessionExpired&code=1001';
118
- }
119
- });
120
-
121
- return;
122
- }
123
-
124
- // Normal flow: Update store based on valid session status
125
- if (status === 'authenticated' && isValid) {
126
- setSession(session);
127
- } else if (status === 'unauthenticated') {
128
- clearSession();
129
- }
130
-
131
- // Cleanup function to prevent post-unmount updates
132
- return () => {
133
- isMounted = false;
134
- };
135
- }, [session, status, setSession, clearSession]);
136
-
137
- return <>{children}</>;
138
- }
1
+ 'use client';
2
+
3
+ import { useEffect, useRef } from 'react';
4
+ import { authClient } from '../client/better-auth-client';
5
+ import { useAuthStore } from '../stores/authStore';
6
+ import { isValidSession } from '../lib/session';
7
+ import {
8
+ getSecureSessionCookieName,
9
+ getSecureCsrfCookieName,
10
+ getCallbackUrlCookieName
11
+ } from '../lib/app-slug';
12
+
13
+ /**
14
+ * Sanitize sensitive data for logging
15
+ * Never log full user IDs or emails in any environment
16
+ */
17
+ function sanitizeForLog(value: string | undefined, type: 'email' | 'userId'): string {
18
+ if (!value) return '(empty)';
19
+
20
+ if (type === 'email') {
21
+ return '***@***'; // Never log emails
22
+ }
23
+
24
+ if (type === 'userId') {
25
+ // Only show first 8 chars in development
26
+ if (process.env.NODE_ENV === 'development') {
27
+ return value.substring(0, 8) + '...';
28
+ }
29
+ return '***'; // Fully redact in production
30
+ }
31
+
32
+ return '***';
33
+ }
34
+
35
+ /**
36
+ * SessionSync - Bridges NextAuth session with Zustand auth store
37
+ *
38
+ * CRITICAL: This component enforces strict session validation. If NextAuth
39
+ * reports an authenticated status but the session data is invalid (empty user ID,
40
+ * empty email, or missing access token), it forces a sign-out to prevent
41
+ * contradictory state like "hasSession: true, userId: ''"
42
+ *
43
+ * This ensures the app NEVER shows authenticated UI with empty/invalid session data.
44
+ */
45
+ export function SessionSync({ children }: { children: React.ReactNode }) {
46
+ const { data: sessionData, isPending } = authClient.useSession();
47
+ const session = sessionData;
48
+ const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
49
+ const { setSession, clearSession } = useAuthStore();
50
+
51
+ // Guard against duplicate sign-out calls
52
+ const isSigningOutRef = useRef(false);
53
+
54
+ useEffect(() => {
55
+ let isMounted = true;
56
+
57
+ // Only process when NextAuth has finished loading
58
+ if (status === 'loading') {
59
+ return;
60
+ }
61
+
62
+ // Strict validation: Check if session is actually valid
63
+ const isValid = isValidSession(session);
64
+
65
+ // CRITICAL FIX: If NextAuth says "authenticated" but session is invalid,
66
+ // this is a broken state that must be fixed immediately
67
+ if (status === 'authenticated' && !isValid) {
68
+ // GUARD: Prevent duplicate sign-out
69
+ if (isSigningOutRef.current) {
70
+ console.warn('[SessionSync] Sign-out already in progress, skipping');
71
+ return;
72
+ }
73
+ isSigningOutRef.current = true;
74
+
75
+ console.error('[SessionSync] CRITICAL: Invalid session detected despite authenticated status!');
76
+ console.error('[SessionSync] This indicates a session with empty user data - forcing sign-out');
77
+
78
+ // Log diagnostic info with PII redaction
79
+ // Note: session is typed as Session | null from NextAuth, but may have invalid/partial data
80
+ const sessionData = session as any; // Explicit cast needed for error logging
81
+ console.error('[SessionSync] Session data:', {
82
+ hasSessionObject: !!sessionData,
83
+ hasUser: !!sessionData?.user,
84
+ userId: sanitizeForLog(sessionData?.user?.id, 'userId'),
85
+ userEmail: sanitizeForLog(sessionData?.user?.email, 'email'),
86
+ hasAccessToken: !!sessionData?.accessToken,
87
+ });
88
+
89
+ // Clear the auth store immediately
90
+ clearSession();
91
+
92
+ // FIX: Force clear all auth cookies including stale provisional tokens (app-slug prefixed)
93
+ // This prevents infinite loop when provisional token exists but session is invalid
94
+ // Root cause: OAuth creates provisional token before Redis session exists
95
+ try {
96
+ const secureSession = getSecureSessionCookieName();
97
+ const secureCsrf = getSecureCsrfCookieName();
98
+ const callbackUrl = getCallbackUrlCookieName();
99
+ document.cookie = `${secureSession}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; Secure; SameSite=Lax`;
100
+ document.cookie = `${secureCsrf}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax`;
101
+ document.cookie = `__Secure-${callbackUrl}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; Secure; SameSite=Lax`;
102
+ } catch (e) {
103
+ // Cookie clearing failed - non-critical, continue with signout
104
+ }
105
+
106
+ // Force Better Auth to sign out (this will clear cookies and trigger redirect)
107
+ authClient.signOut()
108
+ .then(() => {
109
+ if (isMounted) {
110
+ // Use generic error code instead of implementation details
111
+ window.location.href = '/account-auth/login?error=SessionExpired&code=1001';
112
+ }
113
+ })
114
+ .catch((err) => {
115
+ console.error('[SessionSync] Error during forced signout:', err);
116
+ if (isMounted) {
117
+ window.location.href = '/account-auth/login?error=SessionExpired&code=1001';
118
+ }
119
+ });
120
+
121
+ return;
122
+ }
123
+
124
+ // Normal flow: Update store based on valid session status
125
+ if (status === 'authenticated' && isValid) {
126
+ setSession(session);
127
+ } else if (status === 'unauthenticated') {
128
+ clearSession();
129
+ }
130
+
131
+ // Cleanup function to prevent post-unmount updates
132
+ return () => {
133
+ isMounted = false;
134
+ };
135
+ }, [session, status, setSession, clearSession]);
136
+
137
+ return <>{children}</>;
138
+ }