@payez/next-mvp 3.9.0 → 4.0.0

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 (149) hide show
  1. package/dist/api/auth-handler.d.ts +1 -2
  2. package/dist/api/auth-handler.js +9 -9
  3. package/dist/api-handlers/account/change-password.js +110 -112
  4. package/dist/api-handlers/admin/analytics.d.ts +19 -20
  5. package/dist/api-handlers/admin/analytics.js +378 -379
  6. package/dist/api-handlers/admin/audit.d.ts +19 -20
  7. package/dist/api-handlers/admin/audit.js +213 -214
  8. package/dist/api-handlers/admin/index.d.ts +21 -22
  9. package/dist/api-handlers/admin/index.js +42 -43
  10. package/dist/api-handlers/admin/redis-sessions.d.ts +35 -36
  11. package/dist/api-handlers/admin/redis-sessions.js +203 -204
  12. package/dist/api-handlers/admin/sessions.d.ts +20 -21
  13. package/dist/api-handlers/admin/sessions.js +283 -284
  14. package/dist/api-handlers/admin/site-logs.d.ts +45 -46
  15. package/dist/api-handlers/admin/site-logs.js +317 -318
  16. package/dist/api-handlers/admin/stats.d.ts +20 -21
  17. package/dist/api-handlers/admin/stats.js +239 -240
  18. package/dist/api-handlers/admin/users.d.ts +19 -20
  19. package/dist/api-handlers/admin/users.js +221 -222
  20. package/dist/api-handlers/admin/vibe-data.d.ts +79 -80
  21. package/dist/api-handlers/admin/vibe-data.js +267 -268
  22. package/dist/api-handlers/auth/refresh.js +633 -635
  23. package/dist/api-handlers/auth/signout.js +186 -187
  24. package/dist/api-handlers/auth/status.js +4 -7
  25. package/dist/api-handlers/auth/update-session.d.ts +1 -1
  26. package/dist/api-handlers/auth/update-session.js +12 -14
  27. package/dist/api-handlers/auth/verify-code.d.ts +43 -43
  28. package/dist/api-handlers/auth/verify-code.js +90 -94
  29. package/dist/api-handlers/session/viability.js +114 -146
  30. package/dist/api-handlers/test/force-expire.js +59 -65
  31. package/dist/auth/auth-decision.js +182 -182
  32. package/dist/auth/better-auth.d.ts +3 -6
  33. package/dist/auth/better-auth.js +3 -6
  34. package/dist/auth/route-config.js +2 -2
  35. package/dist/auth/utils/token-utils.d.ts +83 -84
  36. package/dist/auth/utils/token-utils.js +218 -219
  37. package/dist/client/AuthContext.js +115 -112
  38. package/dist/client/better-auth-client.d.ts +1020 -961
  39. package/dist/client/better-auth-client.js +54 -7
  40. package/dist/client/fetch-with-auth.js +2 -2
  41. package/dist/components/SessionSync.js +121 -119
  42. package/dist/components/account/MobileNavDrawer.js +64 -64
  43. package/dist/components/account/UserAvatarMenu.js +91 -88
  44. package/dist/components/admin/VibeAdminLayout.js +71 -69
  45. package/dist/hooks/useAuth.js +9 -7
  46. package/dist/hooks/useAuthSettings.js +93 -93
  47. package/dist/hooks/useAvailableProviders.d.ts +43 -45
  48. package/dist/hooks/useAvailableProviders.js +112 -108
  49. package/dist/hooks/useSessionExpiration.d.ts +2 -3
  50. package/dist/hooks/useSessionExpiration.js +2 -2
  51. package/dist/hooks/useViabilitySession.js +3 -2
  52. package/dist/index.js +4 -6
  53. package/dist/lib/app-slug.d.ts +95 -95
  54. package/dist/lib/app-slug.js +172 -172
  55. package/dist/lib/standardized-client-api.js +10 -5
  56. package/dist/lib/startup-init.js +21 -25
  57. package/dist/lib/test-aware-get-token.js +86 -81
  58. package/dist/lib/token-lifecycle.d.ts +78 -52
  59. package/dist/lib/token-lifecycle.js +360 -398
  60. package/dist/pages/admin-login/page.js +73 -83
  61. package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -177
  62. package/dist/pages/login/page.js +202 -211
  63. package/dist/pages/showcase/ShowcasePage.js +142 -140
  64. package/dist/pages/test-env/EmergencyLogoutPage.js +99 -98
  65. package/dist/pages/test-env/JwtInspectPage.js +116 -114
  66. package/dist/pages/test-env/RefreshTokenPage.js +4 -2
  67. package/dist/pages/test-env/TestEnvPage.js +51 -49
  68. package/dist/pages/verify-code/page.js +412 -408
  69. package/dist/routes/auth/logout.d.ts +31 -31
  70. package/dist/routes/auth/logout.js +98 -113
  71. package/dist/routes/auth/nextauth.d.ts +14 -11
  72. package/dist/routes/auth/nextauth.js +25 -57
  73. package/dist/routes/auth/session.js +157 -179
  74. package/dist/routes/auth/viability.js +190 -201
  75. package/dist/server/auth.d.ts +50 -0
  76. package/dist/server/auth.js +62 -0
  77. package/dist/stores/authStore.js +19 -23
  78. package/dist/utils/logout.js +5 -5
  79. package/package.json +1 -3
  80. package/src/api/auth-handler.ts +550 -549
  81. package/src/api-handlers/account/change-password.ts +5 -8
  82. package/src/api-handlers/admin/analytics.ts +4 -6
  83. package/src/api-handlers/admin/audit.ts +5 -7
  84. package/src/api-handlers/admin/index.ts +1 -2
  85. package/src/api-handlers/admin/redis-sessions.ts +6 -8
  86. package/src/api-handlers/admin/sessions.ts +5 -7
  87. package/src/api-handlers/admin/site-logs.ts +8 -10
  88. package/src/api-handlers/admin/stats.ts +4 -6
  89. package/src/api-handlers/admin/users.ts +5 -7
  90. package/src/api-handlers/admin/vibe-data.ts +10 -12
  91. package/src/api-handlers/auth/refresh.ts +5 -7
  92. package/src/api-handlers/auth/signout.ts +5 -6
  93. package/src/api-handlers/auth/status.ts +4 -7
  94. package/src/api-handlers/auth/update-session.ts +123 -125
  95. package/src/api-handlers/auth/verify-code.ts +9 -13
  96. package/src/api-handlers/session/viability.ts +10 -47
  97. package/src/api-handlers/test/force-expire.ts +4 -11
  98. package/src/auth/auth-decision.ts +1 -1
  99. package/src/auth/better-auth.ts +138 -141
  100. package/src/auth/route-config.ts +219 -219
  101. package/src/auth/utils/token-utils.ts +0 -1
  102. package/src/client/AuthContext.tsx +6 -2
  103. package/src/client/better-auth-client.ts +54 -7
  104. package/src/client/fetch-with-auth.ts +47 -47
  105. package/src/components/SessionSync.tsx +6 -5
  106. package/src/components/account/MobileNavDrawer.tsx +3 -3
  107. package/src/components/account/UserAvatarMenu.tsx +6 -3
  108. package/src/components/admin/VibeAdminLayout.tsx +4 -2
  109. package/src/config/logger.ts +1 -1
  110. package/src/hooks/useAuth.ts +117 -115
  111. package/src/hooks/useAuthSettings.ts +2 -2
  112. package/src/hooks/useAvailableProviders.ts +9 -5
  113. package/src/hooks/useSessionExpiration.ts +101 -102
  114. package/src/hooks/useViabilitySession.ts +336 -335
  115. package/src/index.ts +60 -63
  116. package/src/lib/api-handler.ts +0 -1
  117. package/src/lib/app-slug.ts +6 -6
  118. package/src/lib/standardized-client-api.ts +901 -895
  119. package/src/lib/startup-init.ts +243 -247
  120. package/src/lib/test-aware-get-token.ts +22 -12
  121. package/src/lib/token-lifecycle.ts +12 -53
  122. package/src/pages/admin-login/page.tsx +9 -17
  123. package/src/pages/client-admin/ClientSiteAdminPage.tsx +4 -2
  124. package/src/pages/login/page.tsx +21 -28
  125. package/src/pages/showcase/ShowcasePage.tsx +4 -2
  126. package/src/pages/test-env/EmergencyLogoutPage.tsx +7 -6
  127. package/src/pages/test-env/JwtInspectPage.tsx +5 -3
  128. package/src/pages/test-env/RefreshTokenPage.tsx +157 -155
  129. package/src/pages/test-env/TestEnvPage.tsx +4 -2
  130. package/src/pages/verify-code/page.tsx +10 -6
  131. package/src/routes/auth/logout.ts +7 -25
  132. package/src/routes/auth/nextauth.ts +45 -71
  133. package/src/routes/auth/session.ts +25 -50
  134. package/src/routes/auth/viability.ts +7 -19
  135. package/src/server/auth.ts +60 -0
  136. package/src/stores/authStore.ts +1899 -1904
  137. package/src/utils/logout.ts +30 -30
  138. package/src/auth/auth-options.ts +0 -237
  139. package/src/auth/callbacks/index.ts +0 -7
  140. package/src/auth/callbacks/jwt.ts +0 -382
  141. package/src/auth/callbacks/session.ts +0 -243
  142. package/src/auth/callbacks/signin.ts +0 -56
  143. package/src/auth/events/index.ts +0 -5
  144. package/src/auth/events/signout.ts +0 -33
  145. package/src/auth/providers/credentials.ts +0 -256
  146. package/src/auth/providers/index.ts +0 -6
  147. package/src/auth/providers/oauth.ts +0 -114
  148. package/src/lib/nextauth-secret.ts +0 -121
  149. package/src/types/next-auth.d.ts +0 -15
@@ -1,408 +1,412 @@
1
- "use strict";
2
- /**
3
- * Themed 2FA Verification Page for @payez/next-mvp
4
- *
5
- * PLAIN STYLING, FULL FUNCTIONALITY
6
- * - Clean, professional appearance
7
- * - All functional patterns from website-membership
8
- * - Themeable via ThemeProvider
9
- *
10
- * DEPENDENCIES: Only React, Next.js, next-auth, and Tailwind CSS
11
- * NO shadcn/ui or other UI library required!
12
- *
13
- * FEATURES:
14
- * ✅ Progressive disclosure: method selection → code input
15
- * ✅ Method locking after selection (prevents accidental multi-send)
16
- * ✅ Masked contact info display (informational only)
17
- * ✅ Auto-submit when code reaches 6 digits
18
- * ✅ Cooldown timers (30s) on resend buttons
19
- * ✅ Stale session detection (401 → redirect to login)
20
- * ✅ JWT-specific error detection and messaging
21
- * ✅ Session viability polling (every 30s) to detect expiration early
22
- * ✅ Duplicate submission prevention
23
- * ✅ Success/error states with atomic management
24
- * ✅ "Change method" action
25
- * ✅ Session cleanup on success/expiry
26
- *
27
- * USAGE:
28
- * 1. Import from @payez/next-mvp/pages/verify-code
29
- * 2. Wrap your app with ThemeProvider to customize branding
30
- */
31
- 'use client';
32
- Object.defineProperty(exports, "__esModule", { value: true });
33
- exports.default = VerifyCodePage;
34
- const jsx_runtime_1 = require("react/jsx-runtime");
35
- const react_1 = require("react");
36
- const navigation_1 = require("next/navigation");
37
- const react_2 = require("next-auth/react");
38
- const react_3 = require("react");
39
- const useTheme_1 = require("../../theme/useTheme");
40
- /**
41
- * Session storage key to track that user intentionally navigated to verify-code.
42
- * Prevents auto-redirect back to dashboard when session refreshes in background.
43
- */
44
- const VERIFY_IN_PROGRESS_KEY = 'idealvibe_2fa_verify_in_progress';
45
- function VerifyCodeForm() {
46
- const router = (0, navigation_1.useRouter)();
47
- const searchParams = (0, navigation_1.useSearchParams)();
48
- const callbackUrl = searchParams?.get('callbackUrl') || '/dashboard';
49
- const { data: session, status, update: updateSession } = (0, react_2.useSession)();
50
- const colors = (0, useTheme_1.useColors)();
51
- const [method, setMethod] = (0, react_1.useState)(null);
52
- const [methodLocked, setMethodLocked] = (0, react_1.useState)(false);
53
- // Form state
54
- const [code, setCode] = (0, react_1.useState)('');
55
- const [maskedInfo, setMaskedInfo] = (0, react_1.useState)(null);
56
- const [loadingMasked, setLoadingMasked] = (0, react_1.useState)(true);
57
- // Atomic state - only one active at a time
58
- const [sending, setSending] = (0, react_1.useState)(false);
59
- const [verifying, setVerifying] = (0, react_1.useState)(false);
60
- const [success, setSuccess] = (0, react_1.useState)(false);
61
- const [error, setError] = (0, react_1.useState)(null);
62
- // Cooldown timers
63
- const [emailCooldown, setEmailCooldown] = (0, react_1.useState)(0);
64
- const [smsCooldown, setSmsCooldown] = (0, react_1.useState)(0);
65
- // Toast notifications
66
- const [toast, setToast] = (0, react_1.useState)(null);
67
- // Refs
68
- const codeInputRef = (0, react_1.useRef)(null);
69
- const lastSubmittedCode = (0, react_1.useRef)('');
70
- // Track that user is intentionally on this page
71
- const [verifyInProgress, setVerifyInProgress] = (0, react_1.useState)(false);
72
- // ==========================================================================
73
- // CRITICAL FIX: Mark that user is intentionally on verify page
74
- // This prevents auto-redirect when background token refresh updates session
75
- // ==========================================================================
76
- (0, react_1.useEffect)(() => {
77
- // On mount, mark that verification is in progress
78
- if (typeof window !== 'undefined') {
79
- const wasInProgress = sessionStorage.getItem(VERIFY_IN_PROGRESS_KEY) === 'true';
80
- if (!wasInProgress) {
81
- console.log('[2FA] User navigated to verify-code page, marking verify in progress');
82
- sessionStorage.setItem(VERIFY_IN_PROGRESS_KEY, 'true');
83
- }
84
- setVerifyInProgress(true);
85
- }
86
- }, []);
87
- // Auto-dismiss toast
88
- (0, react_1.useEffect)(() => {
89
- if (toast) {
90
- const timer = setTimeout(() => setToast(null), 2500);
91
- return () => clearTimeout(timer);
92
- }
93
- }, [toast]);
94
- // Cooldown countdown
95
- (0, react_1.useEffect)(() => {
96
- if (emailCooldown > 0) {
97
- const timer = setTimeout(() => setEmailCooldown(emailCooldown - 1), 1000);
98
- return () => clearTimeout(timer);
99
- }
100
- }, [emailCooldown]);
101
- (0, react_1.useEffect)(() => {
102
- if (smsCooldown > 0) {
103
- const timer = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000);
104
- return () => clearTimeout(timer);
105
- }
106
- }, [smsCooldown]);
107
- // Fetch masked info on mount
108
- (0, react_1.useEffect)(() => {
109
- const fetchMaskedInfo = async () => {
110
- // BUGFIX: Always set loadingMasked=false, even if not authenticated
111
- // Otherwise page stays stuck in loading spinner
112
- if (status !== 'authenticated' || !session) {
113
- setLoadingMasked(false);
114
- return;
115
- }
116
- try {
117
- const res = await fetch('/api/account/masked-info', {
118
- method: 'POST',
119
- credentials: 'include',
120
- });
121
- if (res.status === 401) {
122
- // Session expired - redirect to login
123
- setError('Your session has expired. Redirecting to login...');
124
- setTimeout(async () => {
125
- await (0, react_2.signOut)({ redirect: false });
126
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
127
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}`);
128
- }, 1200);
129
- return;
130
- }
131
- if (!res.ok) {
132
- throw new Error('Failed to load contact information');
133
- }
134
- const data = await res.json();
135
- setMaskedInfo(data);
136
- }
137
- catch (err) {
138
- console.error('[2FA] Error fetching masked info:', err);
139
- setError('Could not load your contact information. Please try again.');
140
- }
141
- finally {
142
- setLoadingMasked(false);
143
- }
144
- };
145
- fetchMaskedInfo();
146
- }, [status, session, callbackUrl, router]);
147
- // Auto-submit when code is 6 digits
148
- (0, react_1.useEffect)(() => {
149
- if (code.length === 6 && method && !verifying) {
150
- handleVerifyCode();
151
- }
152
- }, [code, method, verifying]);
153
- // ==========================================================================
154
- // Session viability check - detect expiration early and warn user
155
- // ==========================================================================
156
- (0, react_1.useEffect)(() => {
157
- if (status !== 'authenticated')
158
- return;
159
- // Check session viability every 30 seconds
160
- const checkSession = async () => {
161
- try {
162
- const res = await fetch('/api/session/viability', {
163
- credentials: 'include',
164
- });
165
- if (res.status === 401) {
166
- const data = await res.json().catch(() => ({}));
167
- // Session is no longer valid - warn user and redirect
168
- if (data.valid === false || data.mfaExpired === true) {
169
- setError('Your session has expired. Redirecting to login...');
170
- setTimeout(async () => {
171
- await (0, react_2.signOut)({ redirect: false });
172
- if (typeof window !== 'undefined') {
173
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
174
- }
175
- router.push(`/account-auth/login?error=SessionExpired`);
176
- }, 2000);
177
- }
178
- }
179
- }
180
- catch (err) {
181
- // Silent fail - let the next actual API call handle the error
182
- console.log('[2FA] Session viability check failed:', err);
183
- }
184
- };
185
- // Initial check after 5 seconds, then every 30 seconds
186
- const initialTimeout = setTimeout(checkSession, 5000);
187
- const interval = setInterval(checkSession, 30000);
188
- return () => {
189
- clearTimeout(initialTimeout);
190
- clearInterval(interval);
191
- };
192
- }, [status, router]);
193
- const handleSendCode = async (selectedMethod) => {
194
- setSending(true);
195
- setError(null);
196
- try {
197
- const res = await fetch('/api/account/send-code', {
198
- method: 'POST',
199
- headers: { 'Content-Type': 'application/json' },
200
- body: JSON.stringify({ method: selectedMethod }),
201
- credentials: 'include',
202
- });
203
- if (res.status === 401) {
204
- const errorData = await res.json().catch(() => ({}));
205
- const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
206
- setError(isJwtExpired
207
- ? 'Your 2FA session has expired. Please sign in again.'
208
- : 'Your session has expired. Redirecting to login...');
209
- setTimeout(async () => {
210
- await (0, react_2.signOut)({ redirect: false });
211
- if (typeof window !== 'undefined') {
212
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
213
- }
214
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
215
- const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
216
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
217
- }, 1500);
218
- return;
219
- }
220
- if (!res.ok) {
221
- const data = await res.json();
222
- throw new Error(data.message || data.error || 'Failed to send code');
223
- }
224
- // Lock method and set cooldown
225
- setMethod(selectedMethod);
226
- setMethodLocked(true);
227
- if (selectedMethod === 'email') {
228
- setEmailCooldown(30);
229
- }
230
- else {
231
- setSmsCooldown(30);
232
- }
233
- setToast({
234
- type: 'success',
235
- message: `Verification code sent to your ${selectedMethod === 'email' ? 'email' : 'phone'}`,
236
- });
237
- // Focus code input
238
- setTimeout(() => codeInputRef.current?.focus(), 100);
239
- }
240
- catch (err) {
241
- setError(err instanceof Error ? err.message : 'Failed to send verification code');
242
- }
243
- finally {
244
- setSending(false);
245
- }
246
- };
247
- const handleVerifyCode = async () => {
248
- if (!code || !method || code.length !== 6) {
249
- return;
250
- }
251
- // Prevent duplicate submissions
252
- if (lastSubmittedCode.current === code) {
253
- console.log('[2FA] Duplicate submission prevented');
254
- return;
255
- }
256
- lastSubmittedCode.current = code;
257
- setVerifying(true);
258
- setError(null);
259
- try {
260
- const endpoint = method === 'sms' ? '/api/account/verify-sms' : '/api/account/verify-email';
261
- const res = await fetch(endpoint, {
262
- method: 'POST',
263
- headers: { 'Content-Type': 'application/json' },
264
- body: JSON.stringify({ verificationCode: code }),
265
- credentials: 'include',
266
- });
267
- if (res.status === 401) {
268
- const errorData = await res.json().catch(() => ({}));
269
- const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
270
- setError(isJwtExpired
271
- ? 'Your 2FA session has expired. Please sign in again.'
272
- : 'Your session has expired. Redirecting to login...');
273
- setTimeout(async () => {
274
- await (0, react_2.signOut)({ redirect: false });
275
- if (typeof window !== 'undefined') {
276
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
277
- }
278
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
279
- const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
280
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
281
- }, 1500);
282
- return;
283
- }
284
- if (!res.ok) {
285
- const data = await res.json();
286
- throw new Error(data.error || data.message || 'Verification failed');
287
- }
288
- const result = await res.json();
289
- // Normalize response: support both enveloped and unwrapped payloads
290
- const payload = (result && typeof result === 'object' && 'data' in result)
291
- ? result.data
292
- : result;
293
- // Check if verification was successful
294
- const verified = payload?.verificationSuccessful === true ||
295
- payload?.twoFactorSessionVerified === true ||
296
- payload?.success === true ||
297
- // Accept token-based success (unwrapped raw tokens from backend)
298
- (!!payload?.access_token && !!payload?.refresh_token);
299
- if (!verified) {
300
- throw new Error('Verification failed. Please try again.');
301
- }
302
- // CRITICAL: If tokens are included (unwrapped response), persist them in server session
303
- if (payload?.access_token && payload?.refresh_token) {
304
- try {
305
- console.log('[2FA] Updating session with new MFA tokens...');
306
- const updateRes = await fetch('/api/auth/update-session', {
307
- method: 'POST',
308
- headers: { 'Content-Type': 'application/json' },
309
- credentials: 'include',
310
- body: JSON.stringify({
311
- access_token: payload.access_token,
312
- refresh_token: payload.refresh_token
313
- })
314
- });
315
- if (!updateRes.ok) {
316
- console.warn('[2FA] update-session returned non-OK status:', updateRes.status);
317
- const errorData = await updateRes.json();
318
- console.warn('[2FA] update-session error:', errorData);
319
- }
320
- else {
321
- console.log('[2FA] Session updated successfully with MFA tokens');
322
- }
323
- }
324
- catch (e) {
325
- console.warn('[2FA] Failed to call update-session:', e);
326
- }
327
- }
328
- // Show success state
329
- setSuccess(true);
330
- setError(null);
331
- // CRITICAL: Force NextAuth to refetch session from server
332
- // This ensures useSession() gets the updated twoFactorComplete: true
333
- console.log('[2FA] Forcing session refresh after verification...');
334
- try {
335
- await updateSession(); // This triggers /api/auth/session and updates useSession() state
336
- console.log('[2FA] Session refresh completed');
337
- }
338
- catch (e) {
339
- console.warn('[2FA] updateSession failed:', e);
340
- }
341
- // Clear verify-in-progress flag before redirect
342
- if (typeof window !== 'undefined') {
343
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
344
- }
345
- // Redirect after showing success state
346
- setTimeout(() => {
347
- window.location.href = callbackUrl;
348
- }, 1500);
349
- }
350
- catch (err) {
351
- setError(err instanceof Error ? err.message : 'Failed to verify code');
352
- lastSubmittedCode.current = ''; // Allow retry
353
- }
354
- finally {
355
- setVerifying(false);
356
- }
357
- };
358
- const handleResetMethod = () => {
359
- setMethod(null);
360
- setMethodLocked(false);
361
- setCode('');
362
- setError(null);
363
- setEmailCooldown(0);
364
- setSmsCooldown(0);
365
- lastSubmittedCode.current = '';
366
- };
367
- const handleCodeChange = (e) => {
368
- const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
369
- setCode(value);
370
- };
371
- // Loading state
372
- if (status === 'loading' || loadingMasked) {
373
- return ((0, jsx_runtime_1.jsxs)("div", { className: "flex flex-col items-center justify-center py-8", style: { background: 'hsl(var(--background))' }, children: [(0, jsx_runtime_1.jsxs)("svg", { className: "animate-spin h-10 w-10", style: { color: 'hsl(var(--primary))' }, viewBox: "0 0 24 24", fill: "none", children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" })] }), (0, jsx_runtime_1.jsx)("p", { className: "mt-4 text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: "Loading..." })] }));
374
- }
375
- return ((0, jsx_runtime_1.jsx)("div", { className: "flex items-center justify-center px-4 py-8", style: { background: 'hsl(var(--background))' }, children: (0, jsx_runtime_1.jsxs)("div", { className: "max-w-md w-full", children: [toast && ((0, jsx_runtime_1.jsx)("div", { className: `fixed top-4 right-4 p-4 rounded border transition-all duration-300 ${toast.type === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'}`, children: toast.message })), (0, jsx_runtime_1.jsxs)("div", { className: "rounded-2xl border p-8", style: { background: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }, children: [(0, jsx_runtime_1.jsxs)("div", { className: "mb-6", children: [(0, jsx_runtime_1.jsx)("h1", { className: "text-2xl font-semibold mb-2", style: { color: 'hsl(var(--foreground))' }, children: "Verify Your Identity" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: "Choose how you'd like to receive your verification code" })] }), maskedInfo && ((0, jsx_runtime_1.jsxs)("div", { className: "mb-6 p-3 rounded border text-sm", style: { background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }, children: [maskedInfo.masked_email && ((0, jsx_runtime_1.jsxs)("div", { className: "mb-1", children: ["Email: ", (0, jsx_runtime_1.jsx)("span", { className: "font-mono", children: maskedInfo.masked_email })] })), maskedInfo.masked_phone_number && ((0, jsx_runtime_1.jsxs)("div", { children: ["Phone: ", (0, jsx_runtime_1.jsx)("span", { className: "font-mono", children: maskedInfo.masked_phone_number })] }))] })), !method ? (
376
- /* Method Selection */
377
- (0, jsx_runtime_1.jsxs)("div", { className: "space-y-3", children: [(0, jsx_runtime_1.jsxs)("button", { type: "button", onClick: () => handleSendCode('email'), disabled: sending || !maskedInfo?.masked_email, className: "w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors", style: {
378
- background: 'hsl(var(--card))',
379
- borderColor: 'hsl(var(--border))',
380
- color: 'hsl(var(--foreground))'
381
- }, children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-left", children: [(0, jsx_runtime_1.jsx)("p", { className: "font-medium", style: { color: 'hsl(var(--foreground))' }, children: "Email" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: maskedInfo?.masked_email || 'Not available' })] }), (0, jsx_runtime_1.jsx)("span", { style: { color: 'hsl(var(--muted-foreground))' }, children: "\u2192" })] }), (0, jsx_runtime_1.jsxs)("button", { type: "button", onClick: () => handleSendCode('sms'), disabled: sending || !maskedInfo?.masked_phone_number, className: "w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors", style: {
382
- background: 'hsl(var(--card))',
383
- borderColor: 'hsl(var(--border))',
384
- color: 'hsl(var(--foreground))'
385
- }, children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-left", children: [(0, jsx_runtime_1.jsx)("p", { className: "font-medium", style: { color: 'hsl(var(--foreground))' }, children: "SMS" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: maskedInfo?.masked_phone_number || 'Not available' })] }), (0, jsx_runtime_1.jsx)("span", { style: { color: 'hsl(var(--muted-foreground))' }, children: "\u2192" })] })] })) : (
386
- /* Code Input */
387
- (0, jsx_runtime_1.jsxs)("div", { className: "space-y-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between p-3 rounded border", style: { background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }, children: [(0, jsx_runtime_1.jsxs)("span", { className: "text-sm", style: { color: 'hsl(var(--foreground))' }, children: ["Code sent to your ", method === 'email' ? 'email' : 'phone'] }), (0, jsx_runtime_1.jsx)("button", { type: "button", onClick: handleResetMethod, className: "text-sm hover:underline font-medium", style: { color: 'hsl(var(--primary))' }, children: "Change method" })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("label", { htmlFor: "code", className: "block text-sm font-medium mb-2", style: { color: 'hsl(var(--foreground))' }, children: "Verification Code" }), (0, jsx_runtime_1.jsx)("input", { ref: codeInputRef, id: "code", type: "text", inputMode: "numeric", pattern: "[0-9]*", maxLength: 6, value: code, onChange: handleCodeChange, className: "w-full px-4 py-3 text-center text-2xl font-mono border rounded focus:ring-2 tracking-widest", style: {
388
- background: 'hsl(var(--input))',
389
- borderColor: 'hsl(var(--border))',
390
- color: 'hsl(var(--foreground))',
391
- caretColor: 'hsl(var(--foreground))'
392
- }, placeholder: "000000", disabled: verifying || success, autoComplete: "one-time-code", autoFocus: true }), (0, jsx_runtime_1.jsx)("p", { className: "mt-2 text-sm text-center", style: { color: 'hsl(var(--muted-foreground))' }, children: "Enter the 6-digit code" })] }), (0, jsx_runtime_1.jsx)("div", { className: "min-h-[3.5rem] flex items-center", children: verifying ? ((0, jsx_runtime_1.jsxs)("div", { className: "w-full flex items-start space-x-2 p-3 rounded border", style: { background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }, children: [(0, jsx_runtime_1.jsxs)("svg", { className: "animate-spin w-4 h-4 mt-0.5", style: { color: 'hsl(var(--primary))' }, fill: "none", viewBox: "0 0 24 24", children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] }), (0, jsx_runtime_1.jsx)("span", { className: "text-sm", style: { color: 'hsl(var(--foreground))' }, children: "Verifying code..." })] })) : error ? ((0, jsx_runtime_1.jsxs)("div", { className: "w-full flex items-start space-x-2 p-3 rounded bg-red-50 border border-red-200", children: [(0, jsx_runtime_1.jsx)("span", { className: "text-red-700 text-sm font-medium", children: "\u2717" }), (0, jsx_runtime_1.jsx)("span", { className: "text-red-700 text-sm", children: error })] })) : success ? ((0, jsx_runtime_1.jsxs)("div", { className: "w-full flex items-start space-x-2 p-2.5 rounded bg-green-50 border border-green-200", children: [(0, jsx_runtime_1.jsx)("span", { className: "text-green-700 text-xs font-medium", children: "\u2713" }), (0, jsx_runtime_1.jsx)("span", { className: "text-green-700 text-xs", children: "Verification successful! Redirecting..." })] })) : null }), methodLocked && ((0, jsx_runtime_1.jsx)("button", { type: "button", onClick: () => handleSendCode(method), disabled: sending || (method === 'email' ? emailCooldown > 0 : smsCooldown > 0), className: "w-full text-sm hover:underline font-medium disabled:no-underline disabled:cursor-not-allowed disabled:opacity-50", style: { color: 'hsl(var(--primary))' }, children: sending
393
- ? 'Sending...'
394
- : method === 'email'
395
- ? emailCooldown > 0
396
- ? `Resend code in ${emailCooldown}s`
397
- : 'Resend code'
398
- : smsCooldown > 0
399
- ? `Resend code in ${smsCooldown}s`
400
- : 'Resend code' }))] }))] }), (0, jsx_runtime_1.jsx)("p", { className: "mt-4 text-center text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: (0, jsx_runtime_1.jsx)("a", { href: "/account-auth/login", className: "hover:underline font-medium", style: { color: 'hsl(var(--primary))' }, children: "Back to login" }) })] }) }));
401
- }
402
- function VerifyCodePageFallback() {
403
- const colors = (0, useTheme_1.useColors)();
404
- return ((0, jsx_runtime_1.jsx)("div", { className: "flex items-center justify-center py-8", style: { background: 'hsl(var(--background))' }, children: (0, jsx_runtime_1.jsxs)("div", { className: "text-center", children: [(0, jsx_runtime_1.jsxs)("svg", { className: "animate-spin h-10 w-10 mx-auto", style: { color: 'hsl(var(--primary))' }, xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] }), (0, jsx_runtime_1.jsx)("p", { className: "mt-4", style: { color: 'hsl(var(--muted-foreground))' }, children: "Loading..." })] }) }));
405
- }
406
- function VerifyCodePage() {
407
- return ((0, jsx_runtime_1.jsx)(react_3.Suspense, { fallback: (0, jsx_runtime_1.jsx)(VerifyCodePageFallback, {}), children: (0, jsx_runtime_1.jsx)(VerifyCodeForm, {}) }));
408
- }
1
+ "use strict";
2
+ /**
3
+ * Themed 2FA Verification Page for @payez/next-mvp
4
+ *
5
+ * PLAIN STYLING, FULL FUNCTIONALITY
6
+ * - Clean, professional appearance
7
+ * - All functional patterns from website-membership
8
+ * - Themeable via ThemeProvider
9
+ *
10
+ * DEPENDENCIES: Only React, Next.js, next-auth, and Tailwind CSS
11
+ * NO shadcn/ui or other UI library required!
12
+ *
13
+ * FEATURES:
14
+ * ✅ Progressive disclosure: method selection → code input
15
+ * ✅ Method locking after selection (prevents accidental multi-send)
16
+ * ✅ Masked contact info display (informational only)
17
+ * ✅ Auto-submit when code reaches 6 digits
18
+ * ✅ Cooldown timers (30s) on resend buttons
19
+ * ✅ Stale session detection (401 → redirect to login)
20
+ * ✅ JWT-specific error detection and messaging
21
+ * ✅ Session viability polling (every 30s) to detect expiration early
22
+ * ✅ Duplicate submission prevention
23
+ * ✅ Success/error states with atomic management
24
+ * ✅ "Change method" action
25
+ * ✅ Session cleanup on success/expiry
26
+ *
27
+ * USAGE:
28
+ * 1. Import from @payez/next-mvp/pages/verify-code
29
+ * 2. Wrap your app with ThemeProvider to customize branding
30
+ */
31
+ 'use client';
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.default = VerifyCodePage;
34
+ const jsx_runtime_1 = require("react/jsx-runtime");
35
+ const react_1 = require("react");
36
+ const navigation_1 = require("next/navigation");
37
+ const better_auth_client_1 = require("../../client/better-auth-client");
38
+ const react_2 = require("react");
39
+ const useTheme_1 = require("../../theme/useTheme");
40
+ /**
41
+ * Session storage key to track that user intentionally navigated to verify-code.
42
+ * Prevents auto-redirect back to dashboard when session refreshes in background.
43
+ */
44
+ const VERIFY_IN_PROGRESS_KEY = 'idealvibe_2fa_verify_in_progress';
45
+ function VerifyCodeForm() {
46
+ const router = (0, navigation_1.useRouter)();
47
+ const searchParams = (0, navigation_1.useSearchParams)();
48
+ const callbackUrl = searchParams?.get('callbackUrl') || '/dashboard';
49
+ const { data: sessionData, isPending } = better_auth_client_1.authClient.useSession();
50
+ const session = sessionData;
51
+ const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
52
+ // TODO: Better Auth session refresh
53
+ const updateSession = async () => { return session; };
54
+ const colors = (0, useTheme_1.useColors)();
55
+ const [method, setMethod] = (0, react_1.useState)(null);
56
+ const [methodLocked, setMethodLocked] = (0, react_1.useState)(false);
57
+ // Form state
58
+ const [code, setCode] = (0, react_1.useState)('');
59
+ const [maskedInfo, setMaskedInfo] = (0, react_1.useState)(null);
60
+ const [loadingMasked, setLoadingMasked] = (0, react_1.useState)(true);
61
+ // Atomic state - only one active at a time
62
+ const [sending, setSending] = (0, react_1.useState)(false);
63
+ const [verifying, setVerifying] = (0, react_1.useState)(false);
64
+ const [success, setSuccess] = (0, react_1.useState)(false);
65
+ const [error, setError] = (0, react_1.useState)(null);
66
+ // Cooldown timers
67
+ const [emailCooldown, setEmailCooldown] = (0, react_1.useState)(0);
68
+ const [smsCooldown, setSmsCooldown] = (0, react_1.useState)(0);
69
+ // Toast notifications
70
+ const [toast, setToast] = (0, react_1.useState)(null);
71
+ // Refs
72
+ const codeInputRef = (0, react_1.useRef)(null);
73
+ const lastSubmittedCode = (0, react_1.useRef)('');
74
+ // Track that user is intentionally on this page
75
+ const [verifyInProgress, setVerifyInProgress] = (0, react_1.useState)(false);
76
+ // ==========================================================================
77
+ // CRITICAL FIX: Mark that user is intentionally on verify page
78
+ // This prevents auto-redirect when background token refresh updates session
79
+ // ==========================================================================
80
+ (0, react_1.useEffect)(() => {
81
+ // On mount, mark that verification is in progress
82
+ if (typeof window !== 'undefined') {
83
+ const wasInProgress = sessionStorage.getItem(VERIFY_IN_PROGRESS_KEY) === 'true';
84
+ if (!wasInProgress) {
85
+ console.log('[2FA] User navigated to verify-code page, marking verify in progress');
86
+ sessionStorage.setItem(VERIFY_IN_PROGRESS_KEY, 'true');
87
+ }
88
+ setVerifyInProgress(true);
89
+ }
90
+ }, []);
91
+ // Auto-dismiss toast
92
+ (0, react_1.useEffect)(() => {
93
+ if (toast) {
94
+ const timer = setTimeout(() => setToast(null), 2500);
95
+ return () => clearTimeout(timer);
96
+ }
97
+ }, [toast]);
98
+ // Cooldown countdown
99
+ (0, react_1.useEffect)(() => {
100
+ if (emailCooldown > 0) {
101
+ const timer = setTimeout(() => setEmailCooldown(emailCooldown - 1), 1000);
102
+ return () => clearTimeout(timer);
103
+ }
104
+ }, [emailCooldown]);
105
+ (0, react_1.useEffect)(() => {
106
+ if (smsCooldown > 0) {
107
+ const timer = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000);
108
+ return () => clearTimeout(timer);
109
+ }
110
+ }, [smsCooldown]);
111
+ // Fetch masked info on mount
112
+ (0, react_1.useEffect)(() => {
113
+ const fetchMaskedInfo = async () => {
114
+ // BUGFIX: Always set loadingMasked=false, even if not authenticated
115
+ // Otherwise page stays stuck in loading spinner
116
+ if (status !== 'authenticated' || !session) {
117
+ setLoadingMasked(false);
118
+ return;
119
+ }
120
+ try {
121
+ const res = await fetch('/api/account/masked-info', {
122
+ method: 'POST',
123
+ credentials: 'include',
124
+ });
125
+ if (res.status === 401) {
126
+ // Session expired - redirect to login
127
+ setError('Your session has expired. Redirecting to login...');
128
+ setTimeout(async () => {
129
+ await better_auth_client_1.authClient.signOut();
130
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
131
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}`);
132
+ }, 1200);
133
+ return;
134
+ }
135
+ if (!res.ok) {
136
+ throw new Error('Failed to load contact information');
137
+ }
138
+ const data = await res.json();
139
+ setMaskedInfo(data);
140
+ }
141
+ catch (err) {
142
+ console.error('[2FA] Error fetching masked info:', err);
143
+ setError('Could not load your contact information. Please try again.');
144
+ }
145
+ finally {
146
+ setLoadingMasked(false);
147
+ }
148
+ };
149
+ fetchMaskedInfo();
150
+ }, [status, session, callbackUrl, router]);
151
+ // Auto-submit when code is 6 digits
152
+ (0, react_1.useEffect)(() => {
153
+ if (code.length === 6 && method && !verifying) {
154
+ handleVerifyCode();
155
+ }
156
+ }, [code, method, verifying]);
157
+ // ==========================================================================
158
+ // Session viability check - detect expiration early and warn user
159
+ // ==========================================================================
160
+ (0, react_1.useEffect)(() => {
161
+ if (status !== 'authenticated')
162
+ return;
163
+ // Check session viability every 30 seconds
164
+ const checkSession = async () => {
165
+ try {
166
+ const res = await fetch('/api/session/viability', {
167
+ credentials: 'include',
168
+ });
169
+ if (res.status === 401) {
170
+ const data = await res.json().catch(() => ({}));
171
+ // Session is no longer valid - warn user and redirect
172
+ if (data.valid === false || data.mfaExpired === true) {
173
+ setError('Your session has expired. Redirecting to login...');
174
+ setTimeout(async () => {
175
+ await better_auth_client_1.authClient.signOut();
176
+ if (typeof window !== 'undefined') {
177
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
178
+ }
179
+ router.push(`/account-auth/login?error=SessionExpired`);
180
+ }, 2000);
181
+ }
182
+ }
183
+ }
184
+ catch (err) {
185
+ // Silent fail - let the next actual API call handle the error
186
+ console.log('[2FA] Session viability check failed:', err);
187
+ }
188
+ };
189
+ // Initial check after 5 seconds, then every 30 seconds
190
+ const initialTimeout = setTimeout(checkSession, 5000);
191
+ const interval = setInterval(checkSession, 30000);
192
+ return () => {
193
+ clearTimeout(initialTimeout);
194
+ clearInterval(interval);
195
+ };
196
+ }, [status, router]);
197
+ const handleSendCode = async (selectedMethod) => {
198
+ setSending(true);
199
+ setError(null);
200
+ try {
201
+ const res = await fetch('/api/account/send-code', {
202
+ method: 'POST',
203
+ headers: { 'Content-Type': 'application/json' },
204
+ body: JSON.stringify({ method: selectedMethod }),
205
+ credentials: 'include',
206
+ });
207
+ if (res.status === 401) {
208
+ const errorData = await res.json().catch(() => ({}));
209
+ const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
210
+ setError(isJwtExpired
211
+ ? 'Your 2FA session has expired. Please sign in again.'
212
+ : 'Your session has expired. Redirecting to login...');
213
+ setTimeout(async () => {
214
+ await better_auth_client_1.authClient.signOut();
215
+ if (typeof window !== 'undefined') {
216
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
217
+ }
218
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
219
+ const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
220
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
221
+ }, 1500);
222
+ return;
223
+ }
224
+ if (!res.ok) {
225
+ const data = await res.json();
226
+ throw new Error(data.message || data.error || 'Failed to send code');
227
+ }
228
+ // Lock method and set cooldown
229
+ setMethod(selectedMethod);
230
+ setMethodLocked(true);
231
+ if (selectedMethod === 'email') {
232
+ setEmailCooldown(30);
233
+ }
234
+ else {
235
+ setSmsCooldown(30);
236
+ }
237
+ setToast({
238
+ type: 'success',
239
+ message: `Verification code sent to your ${selectedMethod === 'email' ? 'email' : 'phone'}`,
240
+ });
241
+ // Focus code input
242
+ setTimeout(() => codeInputRef.current?.focus(), 100);
243
+ }
244
+ catch (err) {
245
+ setError(err instanceof Error ? err.message : 'Failed to send verification code');
246
+ }
247
+ finally {
248
+ setSending(false);
249
+ }
250
+ };
251
+ const handleVerifyCode = async () => {
252
+ if (!code || !method || code.length !== 6) {
253
+ return;
254
+ }
255
+ // Prevent duplicate submissions
256
+ if (lastSubmittedCode.current === code) {
257
+ console.log('[2FA] Duplicate submission prevented');
258
+ return;
259
+ }
260
+ lastSubmittedCode.current = code;
261
+ setVerifying(true);
262
+ setError(null);
263
+ try {
264
+ const endpoint = method === 'sms' ? '/api/account/verify-sms' : '/api/account/verify-email';
265
+ const res = await fetch(endpoint, {
266
+ method: 'POST',
267
+ headers: { 'Content-Type': 'application/json' },
268
+ body: JSON.stringify({ verificationCode: code }),
269
+ credentials: 'include',
270
+ });
271
+ if (res.status === 401) {
272
+ const errorData = await res.json().catch(() => ({}));
273
+ const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
274
+ setError(isJwtExpired
275
+ ? 'Your 2FA session has expired. Please sign in again.'
276
+ : 'Your session has expired. Redirecting to login...');
277
+ setTimeout(async () => {
278
+ await better_auth_client_1.authClient.signOut();
279
+ if (typeof window !== 'undefined') {
280
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
281
+ }
282
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
283
+ const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
284
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
285
+ }, 1500);
286
+ return;
287
+ }
288
+ if (!res.ok) {
289
+ const data = await res.json();
290
+ throw new Error(data.error || data.message || 'Verification failed');
291
+ }
292
+ const result = await res.json();
293
+ // Normalize response: support both enveloped and unwrapped payloads
294
+ const payload = (result && typeof result === 'object' && 'data' in result)
295
+ ? result.data
296
+ : result;
297
+ // Check if verification was successful
298
+ const verified = payload?.verificationSuccessful === true ||
299
+ payload?.twoFactorSessionVerified === true ||
300
+ payload?.success === true ||
301
+ // Accept token-based success (unwrapped raw tokens from backend)
302
+ (!!payload?.access_token && !!payload?.refresh_token);
303
+ if (!verified) {
304
+ throw new Error('Verification failed. Please try again.');
305
+ }
306
+ // CRITICAL: If tokens are included (unwrapped response), persist them in server session
307
+ if (payload?.access_token && payload?.refresh_token) {
308
+ try {
309
+ console.log('[2FA] Updating session with new MFA tokens...');
310
+ const updateRes = await fetch('/api/auth/update-session', {
311
+ method: 'POST',
312
+ headers: { 'Content-Type': 'application/json' },
313
+ credentials: 'include',
314
+ body: JSON.stringify({
315
+ access_token: payload.access_token,
316
+ refresh_token: payload.refresh_token
317
+ })
318
+ });
319
+ if (!updateRes.ok) {
320
+ console.warn('[2FA] update-session returned non-OK status:', updateRes.status);
321
+ const errorData = await updateRes.json();
322
+ console.warn('[2FA] update-session error:', errorData);
323
+ }
324
+ else {
325
+ console.log('[2FA] Session updated successfully with MFA tokens');
326
+ }
327
+ }
328
+ catch (e) {
329
+ console.warn('[2FA] Failed to call update-session:', e);
330
+ }
331
+ }
332
+ // Show success state
333
+ setSuccess(true);
334
+ setError(null);
335
+ // CRITICAL: Force NextAuth to refetch session from server
336
+ // This ensures useSession() gets the updated twoFactorComplete: true
337
+ console.log('[2FA] Forcing session refresh after verification...');
338
+ try {
339
+ await updateSession(); // This triggers /api/auth/session and updates useSession() state
340
+ console.log('[2FA] Session refresh completed');
341
+ }
342
+ catch (e) {
343
+ console.warn('[2FA] updateSession failed:', e);
344
+ }
345
+ // Clear verify-in-progress flag before redirect
346
+ if (typeof window !== 'undefined') {
347
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
348
+ }
349
+ // Redirect after showing success state
350
+ setTimeout(() => {
351
+ window.location.href = callbackUrl;
352
+ }, 1500);
353
+ }
354
+ catch (err) {
355
+ setError(err instanceof Error ? err.message : 'Failed to verify code');
356
+ lastSubmittedCode.current = ''; // Allow retry
357
+ }
358
+ finally {
359
+ setVerifying(false);
360
+ }
361
+ };
362
+ const handleResetMethod = () => {
363
+ setMethod(null);
364
+ setMethodLocked(false);
365
+ setCode('');
366
+ setError(null);
367
+ setEmailCooldown(0);
368
+ setSmsCooldown(0);
369
+ lastSubmittedCode.current = '';
370
+ };
371
+ const handleCodeChange = (e) => {
372
+ const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
373
+ setCode(value);
374
+ };
375
+ // Loading state
376
+ if (status === 'loading' || loadingMasked) {
377
+ return ((0, jsx_runtime_1.jsxs)("div", { className: "flex flex-col items-center justify-center py-8", style: { background: 'hsl(var(--background))' }, children: [(0, jsx_runtime_1.jsxs)("svg", { className: "animate-spin h-10 w-10", style: { color: 'hsl(var(--primary))' }, viewBox: "0 0 24 24", fill: "none", children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" })] }), (0, jsx_runtime_1.jsx)("p", { className: "mt-4 text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: "Loading..." })] }));
378
+ }
379
+ return ((0, jsx_runtime_1.jsx)("div", { className: "flex items-center justify-center px-4 py-8", style: { background: 'hsl(var(--background))' }, children: (0, jsx_runtime_1.jsxs)("div", { className: "max-w-md w-full", children: [toast && ((0, jsx_runtime_1.jsx)("div", { className: `fixed top-4 right-4 p-4 rounded border transition-all duration-300 ${toast.type === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'}`, children: toast.message })), (0, jsx_runtime_1.jsxs)("div", { className: "rounded-2xl border p-8", style: { background: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }, children: [(0, jsx_runtime_1.jsxs)("div", { className: "mb-6", children: [(0, jsx_runtime_1.jsx)("h1", { className: "text-2xl font-semibold mb-2", style: { color: 'hsl(var(--foreground))' }, children: "Verify Your Identity" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: "Choose how you'd like to receive your verification code" })] }), maskedInfo && ((0, jsx_runtime_1.jsxs)("div", { className: "mb-6 p-3 rounded border text-sm", style: { background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }, children: [maskedInfo.masked_email && ((0, jsx_runtime_1.jsxs)("div", { className: "mb-1", children: ["Email: ", (0, jsx_runtime_1.jsx)("span", { className: "font-mono", children: maskedInfo.masked_email })] })), maskedInfo.masked_phone_number && ((0, jsx_runtime_1.jsxs)("div", { children: ["Phone: ", (0, jsx_runtime_1.jsx)("span", { className: "font-mono", children: maskedInfo.masked_phone_number })] }))] })), !method ? (
380
+ /* Method Selection */
381
+ (0, jsx_runtime_1.jsxs)("div", { className: "space-y-3", children: [(0, jsx_runtime_1.jsxs)("button", { type: "button", onClick: () => handleSendCode('email'), disabled: sending || !maskedInfo?.masked_email, className: "w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors", style: {
382
+ background: 'hsl(var(--card))',
383
+ borderColor: 'hsl(var(--border))',
384
+ color: 'hsl(var(--foreground))'
385
+ }, children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-left", children: [(0, jsx_runtime_1.jsx)("p", { className: "font-medium", style: { color: 'hsl(var(--foreground))' }, children: "Email" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: maskedInfo?.masked_email || 'Not available' })] }), (0, jsx_runtime_1.jsx)("span", { style: { color: 'hsl(var(--muted-foreground))' }, children: "\u2192" })] }), (0, jsx_runtime_1.jsxs)("button", { type: "button", onClick: () => handleSendCode('sms'), disabled: sending || !maskedInfo?.masked_phone_number, className: "w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors", style: {
386
+ background: 'hsl(var(--card))',
387
+ borderColor: 'hsl(var(--border))',
388
+ color: 'hsl(var(--foreground))'
389
+ }, children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-left", children: [(0, jsx_runtime_1.jsx)("p", { className: "font-medium", style: { color: 'hsl(var(--foreground))' }, children: "SMS" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: maskedInfo?.masked_phone_number || 'Not available' })] }), (0, jsx_runtime_1.jsx)("span", { style: { color: 'hsl(var(--muted-foreground))' }, children: "\u2192" })] })] })) : (
390
+ /* Code Input */
391
+ (0, jsx_runtime_1.jsxs)("div", { className: "space-y-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between p-3 rounded border", style: { background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }, children: [(0, jsx_runtime_1.jsxs)("span", { className: "text-sm", style: { color: 'hsl(var(--foreground))' }, children: ["Code sent to your ", method === 'email' ? 'email' : 'phone'] }), (0, jsx_runtime_1.jsx)("button", { type: "button", onClick: handleResetMethod, className: "text-sm hover:underline font-medium", style: { color: 'hsl(var(--primary))' }, children: "Change method" })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("label", { htmlFor: "code", className: "block text-sm font-medium mb-2", style: { color: 'hsl(var(--foreground))' }, children: "Verification Code" }), (0, jsx_runtime_1.jsx)("input", { ref: codeInputRef, id: "code", type: "text", inputMode: "numeric", pattern: "[0-9]*", maxLength: 6, value: code, onChange: handleCodeChange, className: "w-full px-4 py-3 text-center text-2xl font-mono border rounded focus:ring-2 tracking-widest", style: {
392
+ background: 'hsl(var(--input))',
393
+ borderColor: 'hsl(var(--border))',
394
+ color: 'hsl(var(--foreground))',
395
+ caretColor: 'hsl(var(--foreground))'
396
+ }, placeholder: "000000", disabled: verifying || success, autoComplete: "one-time-code", autoFocus: true }), (0, jsx_runtime_1.jsx)("p", { className: "mt-2 text-sm text-center", style: { color: 'hsl(var(--muted-foreground))' }, children: "Enter the 6-digit code" })] }), (0, jsx_runtime_1.jsx)("div", { className: "min-h-[3.5rem] flex items-center", children: verifying ? ((0, jsx_runtime_1.jsxs)("div", { className: "w-full flex items-start space-x-2 p-3 rounded border", style: { background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }, children: [(0, jsx_runtime_1.jsxs)("svg", { className: "animate-spin w-4 h-4 mt-0.5", style: { color: 'hsl(var(--primary))' }, fill: "none", viewBox: "0 0 24 24", children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] }), (0, jsx_runtime_1.jsx)("span", { className: "text-sm", style: { color: 'hsl(var(--foreground))' }, children: "Verifying code..." })] })) : error ? ((0, jsx_runtime_1.jsxs)("div", { className: "w-full flex items-start space-x-2 p-3 rounded bg-red-50 border border-red-200", children: [(0, jsx_runtime_1.jsx)("span", { className: "text-red-700 text-sm font-medium", children: "\u2717" }), (0, jsx_runtime_1.jsx)("span", { className: "text-red-700 text-sm", children: error })] })) : success ? ((0, jsx_runtime_1.jsxs)("div", { className: "w-full flex items-start space-x-2 p-2.5 rounded bg-green-50 border border-green-200", children: [(0, jsx_runtime_1.jsx)("span", { className: "text-green-700 text-xs font-medium", children: "\u2713" }), (0, jsx_runtime_1.jsx)("span", { className: "text-green-700 text-xs", children: "Verification successful! Redirecting..." })] })) : null }), methodLocked && ((0, jsx_runtime_1.jsx)("button", { type: "button", onClick: () => handleSendCode(method), disabled: sending || (method === 'email' ? emailCooldown > 0 : smsCooldown > 0), className: "w-full text-sm hover:underline font-medium disabled:no-underline disabled:cursor-not-allowed disabled:opacity-50", style: { color: 'hsl(var(--primary))' }, children: sending
397
+ ? 'Sending...'
398
+ : method === 'email'
399
+ ? emailCooldown > 0
400
+ ? `Resend code in ${emailCooldown}s`
401
+ : 'Resend code'
402
+ : smsCooldown > 0
403
+ ? `Resend code in ${smsCooldown}s`
404
+ : 'Resend code' }))] }))] }), (0, jsx_runtime_1.jsx)("p", { className: "mt-4 text-center text-sm", style: { color: 'hsl(var(--muted-foreground))' }, children: (0, jsx_runtime_1.jsx)("a", { href: "/account-auth/login", className: "hover:underline font-medium", style: { color: 'hsl(var(--primary))' }, children: "Back to login" }) })] }) }));
405
+ }
406
+ function VerifyCodePageFallback() {
407
+ const colors = (0, useTheme_1.useColors)();
408
+ return ((0, jsx_runtime_1.jsx)("div", { className: "flex items-center justify-center py-8", style: { background: 'hsl(var(--background))' }, children: (0, jsx_runtime_1.jsxs)("div", { className: "text-center", children: [(0, jsx_runtime_1.jsxs)("svg", { className: "animate-spin h-10 w-10 mx-auto", style: { color: 'hsl(var(--primary))' }, xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] }), (0, jsx_runtime_1.jsx)("p", { className: "mt-4", style: { color: 'hsl(var(--muted-foreground))' }, children: "Loading..." })] }) }));
409
+ }
410
+ function VerifyCodePage() {
411
+ return ((0, jsx_runtime_1.jsx)(react_2.Suspense, { fallback: (0, jsx_runtime_1.jsx)(VerifyCodePageFallback, {}), children: (0, jsx_runtime_1.jsx)(VerifyCodeForm, {}) }));
412
+ }